File size: 13,602 Bytes
b664155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431a182
b664155
 
f5a3825
887690a
f5a3825
b664155
 
 
 
 
 
 
 
 
 
 
 
 
 
6474f1f
b664155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
887690a
b664155
431a182
 
 
 
b664155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
887690a
b664155
 
 
 
 
 
887690a
431a182
9cdf9d7
887690a
b664155
 
 
 
 
 
 
 
887690a
 
b664155
6474f1f
b664155
 
6474f1f
b664155
6474f1f
 
b664155
 
9cdf9d7
6474f1f
887690a
b664155
 
9cdf9d7
 
b664155
 
 
 
 
 
 
6474f1f
b664155
 
 
887690a
3c1e477
 
 
 
 
b664155
 
 
 
 
 
 
 
 
 
 
6474f1f
b664155
 
6474f1f
b664155
 
 
 
 
6474f1f
351cd3f
9cdf9d7
 
 
cc438b6
887690a
 
9cdf9d7
887690a
9cdf9d7
887690a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
079a940
887690a
 
9cdf9d7
 
 
431a182
 
9cdf9d7
 
431a182
9cdf9d7
 
 
 
 
 
 
887690a
9cdf9d7
 
 
431a182
9cdf9d7
431a182
 
 
 
3b91b34
7ac3581
 
 
 
 
3b91b34
 
 
 
7ac3581
 
 
887690a
 
7ac3581
 
 
3b91b34
 
7ac3581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea16365
9cdf9d7
 
 
ea16365
b664155
6474f1f
887690a
b664155
 
 
6474f1f
b664155
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# deformes4D_engine.py
# Copyright (C) 4 de Agosto de 2025  Carlos Rodrigues dos Santos
#
# MODIFICATIONS FOR ADUC-SDR:
# Copyright (C) 2025 Carlos Rodrigues dos Santos. All rights reserved.
#
# This file is part of the ADUC-SDR project. It contains the core logic for
# video fragment generation, latent manipulation, and dynamic editing, 
# governed by the ADUC orchestrator.
# This component is licensed under the GNU Affero General Public License v3.0.

import os
import time
import imageio
import numpy as np
import torch
import logging
from PIL import Image, ImageOps
from dataclasses import dataclass
import gradio as gr
import subprocess
import gc

# Importações de especialistas, com o de áudio removido
from ltx_manager_helpers import ltx_manager_singleton
from gemini_helpers import gemini_singleton 
from upscaler_specialist import upscaler_specialist_singleton
from hd_specialist import hd_specialist_singleton
from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode

logger = logging.getLogger(__name__)

@dataclass
class LatentConditioningItem:
    """Representa uma âncora de condicionamento no espaço latente para a Câmera (Ψ)."""
    latent_tensor: torch.Tensor
    media_frame_number: int
    conditioning_strength: float

class Deformes4DEngine:
    """
    Implementa a Câmera (Ψ) e o Destilador (Δ) da arquitetura ADUC-SDR.
    Orquestra a geração, pós-produção latente e renderização final dos fragmentos de vídeo.
    """
    def __init__(self, ltx_manager, workspace_dir="deformes_workspace"):
        self.ltx_manager = ltx_manager
        self.workspace_dir = workspace_dir
        self._vae = None
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        logger.info("Especialista Deformes4D (Executor ADUC-SDR: Câmera Ψ e Destilador Δ) inicializado.")

    @property
    def vae(self):
        if self._vae is None:
            self._vae = self.ltx_manager.workers[0].pipeline.vae
        self._vae.to(self.device); self._vae.eval()
        return self._vae

    # --- MÉTODOS AUXILIARES ---

    @torch.no_grad()
    def pixels_to_latents(self, tensor: torch.Tensor) -> torch.Tensor:
        tensor = tensor.to(self.device, dtype=self.vae.dtype)
        return vae_encode(tensor, self.vae, vae_per_channel_normalize=True)

    @torch.no_grad()
    def latents_to_pixels(self, latent_tensor: torch.Tensor, decode_timestep: float = 0.05) -> torch.Tensor:
        latent_tensor = latent_tensor.to(self.device, dtype=self.vae.dtype)
        timestep_tensor = torch.tensor([decode_timestep] * latent_tensor.shape[0], device=self.device, dtype=latent_tensor.dtype)
        return vae_decode(latent_tensor, self.vae, is_video=True, timestep=timestep_tensor, vae_per_channel_normalize=True)

    def _preprocess_image_for_latent_conversion(self, image: Image.Image, target_resolution: tuple) -> Image.Image:
        if image.size != target_resolution:
            return ImageOps.fit(image, target_resolution, Image.Resampling.LANCZOS)
        return image

    def pil_to_latent(self, pil_image: Image.Image) -> torch.Tensor:
        image_np = np.array(pil_image).astype(np.float32) / 255.0
        tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
        tensor = (tensor * 2.0) - 1.0
        return self.pixels_to_latents(tensor)
    
    # --- NÚCLEO DA LÓGICA ADUC-SDR ---
    def generate_full_movie(self, keyframes: list, global_prompt: str, storyboard: list, 
                            seconds_per_fragment: float, trim_percent: int,
                            handler_strength: float, destination_convergence_strength: float, 
                            video_resolution: int, use_continuity_director: bool, 
                            progress: gr.Progress = gr.Progress()):
        
        num_transitions_to_generate = len(keyframes) - 1
        TOTAL_STEPS = num_transitions_to_generate + 3 # Fragmentos + Renderização + HD
        current_step = 0
        
        FPS = 24
        FRAMES_PER_LATENT_CHUNK = 8
        ECO_LATENT_CHUNKS = 2
        
        total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
        frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
        latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK

        if total_frames_brutos // FRAMES_PER_LATENT_CHUNK <= latents_a_podar + 1:
            raise gr.Error("A combinação de duração e poda é muito agressiva.")

        DEJAVU_FRAME_TARGET = frames_a_podar - 1 if frames_a_podar > 0 else 0
        DESTINATION_FRAME_TARGET = total_frames_brutos - 1
        
        base_ltx_params = {"guidance_scale": 2.0, "stg_scale": 0.025, "rescaling_scale": 0.15, "num_inference_steps": 20}
        keyframe_paths = [item[0] if isinstance(item, tuple) else item for item in keyframes]
        story_history = ""
        
        eco_latent_for_next_loop = None
        dejavu_latent_for_next_loop = None
        processed_latent_fragments = []

        # --- ATO I: GERAÇÃO LATENTE (LOOP DE FRAGMENTOS) ---
        for i in range(num_transitions_to_generate):
            fragment_index = i + 1
            current_step += 1
            progress(current_step / TOTAL_STEPS, desc=f"Gerando Fragmento {fragment_index}/{num_transitions_to_generate}")
            
            past_keyframe_path = keyframe_paths[i - 1] if i > 0 else keyframe_paths[i]
            start_keyframe_path = keyframe_paths[i]
            destination_keyframe_path = keyframe_paths[i + 1]
            future_story_prompt = storyboard[i + 1] if (i + 1) < len(storyboard) else "A cena final."
            decision = gemini_singleton.get_cinematic_decision(
                global_prompt, story_history, past_keyframe_path, start_keyframe_path, destination_keyframe_path,
                storyboard[i - 1] if i > 0 else "O início.", storyboard[i], future_story_prompt)
            transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
            story_history += f"\n- Ato {fragment_index}: {motion_prompt}"

            expected_height, expected_width = video_resolution, video_resolution
            downscale_factor = 2 / 3
            downscaled_height = self._quantize_to_multiple(int(expected_height * downscale_factor), 8)
            downscaled_width = self._quantize_to_multiple(int(expected_width * downscale_factor), 8)
            target_resolution_tuple = (downscaled_height, downscaled_width)

            conditioning_items = []
            if eco_latent_for_next_loop is None:
               img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
               conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_start), 0, 1.0))
            else:
               conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
               conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
            img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
            conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_dest), DESTINATION_FRAME_TARGET, destination_convergence_strength))

            current_ltx_params = {**base_ltx_params, "motion_prompt": motion_prompt}
            latents_brutos, _ = self._generate_latent_tensor_internal(conditioning_items, current_ltx_params, target_resolution_tuple, total_frames_brutos)

            last_trim = latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
            eco_latent_for_next_loop = last_trim[:, :, :ECO_LATENT_CHUNKS, :, :].clone()   
            dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
            latents_video = latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
            latents_video = latents_video[:, :, 1:, :, :]

            if transition_type == "cut":
                eco_latent_for_next_loop, dejavu_latent_for_next_loop = None, None

            upscaled_latents = self.upscale_latents(latents_video)
            refined_latents = self.refine_latents(upscaled_latents, motion_prompt=f"refining scene: {motion_prompt}")
            processed_latent_fragments.append(refined_latents)
        
        # --- ATO II: RENDERIZAÇÃO PRIMÁRIA (COM CORREÇÃO DE OOM) ---
        base_name = f"movie_{int(time.time())}"
        current_step += 1
        progress(current_step / TOTAL_STEPS, desc="Renderizando vídeo (em lotes)...")
        refined_silent_video_path = os.path.join(self.workspace_dir, f"{base_name}_refined_silent.mp4")

        with imageio.get_writer(refined_silent_video_path, fps=FPS, codec='libx264', quality=8, output_params=['-pix_fmt', 'yuv420p']) as writer:
            for i, latent_fragment in enumerate(processed_latent_fragments):
                logger.info(f"Decodificando fragmento {i+1}/{len(processed_latent_fragments)} para pixels...")
                pixel_tensor_fragment = self.latents_to_pixels(latent_fragment)
                
                pixel_tensor_fragment = pixel_tensor_fragment.squeeze(0).permute(1, 2, 3, 0)
                pixel_tensor_fragment = (pixel_tensor_fragment.clamp(-1, 1) + 1) / 2.0
                video_np_fragment = (pixel_tensor_fragment.detach().cpu().float().numpy() * 255).astype(np.uint8)
                
                for frame in video_np_fragment:
                    writer.append_data(frame)
                
                del pixel_tensor_fragment, video_np_fragment
                gc.collect()
                torch.cuda.empty_cache()
        
        logger.info(f"Vídeo base renderizado com sucesso em: {refined_silent_video_path}")
        del processed_latent_fragments
        gc.collect()
        torch.cuda.empty_cache()

        # --- ATO III: MASTERIZAÇÃO FINAL (APENAS HD) ---
        current_step += 1
        progress(current_step / TOTAL_STEPS, desc="Aprimoramento final (HD)...")
        hq_silent_video_path = os.path.join(self.workspace_dir, f"{base_name}_hq_silent.mp4")
        
        try:
            hd_specialist_singleton.process_video(
                input_video_path=refined_silent_video_path,
                output_video_path=hq_silent_video_path,
                prompt=global_prompt
            )
        except Exception as e:
            logger.error(f"Falha no aprimoramento HD: {e}. Usando vídeo de qualidade padrão.")
            os.rename(refined_silent_video_path, hq_silent_video_path)

        current_step += 1
        progress(current_step / TOTAL_STEPS, desc="Finalizando...")
        final_video_path = os.path.join(self.workspace_dir, f"{base_name}_FINAL.mp4")
        os.rename(hq_silent_video_path, final_video_path)

        logger.info(f"Processo concluído! Vídeo final (silencioso) salvo em: {final_video_path}")
        yield {"final_path": final_video_path}

    def refine_latents(self, latents: torch.Tensor,
                       fps: int = 24,
                       denoise_strength: float = 0.35,
                       refine_steps: int = 12,
                       motion_prompt: str = "refining video, improving details, cinematic quality") -> torch.Tensor:
        """
        Aplica um passe de refinamento (denoise) em um tensor latente.
        """
        logger.info(f"Refinando tensor latente com shape {latents.shape} para refinamento.")
        
        _, _, num_latent_frames, latent_h, latent_w = latents.shape

        video_scale_factor = getattr(self.vae.config, 'temporal_scale_factor', 8)
        vae_scale_factor = getattr(self.vae.config, 'spatial_downscale_factor', 8)
        
        pixel_height = latent_h * vae_scale_factor
        pixel_width = latent_w * vae_scale_factor
        pixel_frames = (num_latent_frames - 1) * video_scale_factor
        
        refined_latents_tensor, _ = self.ltx_manager.refine_latents(
            latents,
            height=pixel_height,
            width=pixel_width,
            video_total_frames=pixel_frames,
            video_fps=fps,
            motion_prompt=motion_prompt,
            current_fragment_index=int(time.time()),
            denoise_strength=denoise_strength,
            refine_steps=refine_steps
        )
        
        logger.info(f"Retornando tensor latente refinado com shape: {refined_latents_tensor.shape}")
        return refined_latents_tensor
        
    def upscale_latents(self, latents: torch.Tensor) -> torch.Tensor:
        """Interface para o UpscalerSpecialist."""
        logger.info(f"Realizando upscale em tensor latente com shape {latents.shape}.")
        return upscaler_specialist_singleton.upscale(latents)
        
    def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
        kwargs = {
            **ltx_params, 'width': target_resolution[1], 'height': target_resolution[0],
            'video_total_frames': total_frames_to_generate, 'video_fps': 24,
            'current_fragment_index': int(time.time()), 'conditioning_items_data': conditioning_items
        }
        return self.ltx_manager.generate_latent_fragment(**kwargs)

    def _quantize_to_multiple(self, n, m):
        if m == 0: return n
        quantized = int(round(n / m) * m)
        return m if n > 0 and quantized == 0 else quantized