euiia commited on
Commit
b664155
·
verified ·
1 Parent(s): afebbd9

Upload deformes4D_engine (37).py

Browse files
Files changed (1) hide show
  1. deformes4D_engine (37).py +335 -0
deformes4D_engine (37).py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # deformes4D_engine.py
2
+ # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
+ #
4
+ # MODIFICATIONS FOR ADUC-SDR:
5
+ # Copyright (C) 2025 Carlos Rodrigues dos Santos. All rights reserved.
6
+ #
7
+ # This file is part of the ADUC-SDR project. It contains the core logic for
8
+ # video fragment generation, latent manipulation, and dynamic editing,
9
+ # governed by the ADUC orchestrator.
10
+ # This component is licensed under the GNU Affero General Public License v3.0.
11
+
12
+ import os
13
+ import time
14
+ import imageio
15
+ import numpy as np
16
+ import torch
17
+ import logging
18
+ from PIL import Image, ImageOps
19
+ from dataclasses import dataclass
20
+ import gradio as gr
21
+ import subprocess
22
+ import gc
23
+
24
+ from ltx_manager_helpers import ltx_manager_singleton
25
+ from gemini_helpers import gemini_singleton
26
+ from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ @dataclass
31
+ class LatentConditioningItem:
32
+ """Representa uma âncora de condicionamento no espaço latente para a Câmera (Ψ)."""
33
+ latent_tensor: torch.Tensor
34
+ media_frame_number: int
35
+ conditioning_strength: float
36
+
37
+ class Deformes4DEngine:
38
+ """
39
+ Implementa a Câmera (Ψ) e o Destilador (Δ) da arquitetura ADUC-SDR.
40
+ É responsável pela execução da geração de fragmentos de vídeo e pela
41
+ extração dos contextos causais (Eco e Déjà-Vu).
42
+ """
43
+ def __init__(self, ltx_manager, workspace_dir="deformes_workspace"):
44
+ self.ltx_manager = ltx_manager
45
+ self.workspace_dir = workspace_dir
46
+ self._vae = None
47
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
48
+ logger.info("Especialista Deformes4D (Executor ADUC-SDR: Câmera Ψ e Destilador Δ) inicializado.")
49
+
50
+ @property
51
+ def vae(self):
52
+ if self._vae is None:
53
+ self._vae = self.ltx_manager.workers[0].pipeline.vae
54
+ self._vae.to(self.device); self._vae.eval()
55
+ return self._vae
56
+
57
+ # MÉTODOS AUXILIARES DE MANIPULAÇÃO DE DADOS E VÍDEO
58
+
59
+ def save_latent_tensor(self, tensor: torch.Tensor, path: str):
60
+ torch.save(tensor.cpu(), path)
61
+
62
+ def load_latent_tensor(self, path: str) -> torch.Tensor:
63
+ return torch.load(path, map_location=self.device)
64
+
65
+ @torch.no_grad()
66
+ def pixels_to_latents(self, tensor: torch.Tensor) -> torch.Tensor:
67
+ tensor = tensor.to(self.device, dtype=self.vae.dtype)
68
+ return vae_encode(tensor, self.vae, vae_per_channel_normalize=True)
69
+
70
+ @torch.no_grad()
71
+ def latents_to_pixels(self, latent_tensor: torch.Tensor, decode_timestep: float = 0.05) -> torch.Tensor:
72
+ latent_tensor = latent_tensor.to(self.device, dtype=self.vae.dtype)
73
+ timestep_tensor = torch.tensor([decode_timestep] * latent_tensor.shape[0], device=self.device, dtype=latent_tensor.dtype)
74
+ return vae_decode(latent_tensor, self.vae, is_video=True, timestep=timestep_tensor, vae_per_channel_normalize=True)
75
+
76
+ def save_video_from_tensor(self, video_tensor: torch.Tensor, path: str, fps: int = 24):
77
+ if video_tensor is None or video_tensor.ndim != 5 or video_tensor.shape[2] == 0:
78
+ logger.warning(f"Tentativa de salvar um tensor de vídeo inválido em {path}. Abortando.")
79
+ return
80
+ video_tensor = video_tensor.squeeze(0).permute(1, 2, 3, 0)
81
+ video_tensor = (video_tensor.clamp(-1, 1) + 1) / 2.0
82
+ video_np = (video_tensor.detach().cpu().float().numpy() * 255).astype(np.uint8)
83
+ with imageio.get_writer(path, fps=fps, codec='libx264', quality=8) as writer:
84
+ for frame in video_np: writer.append_data(frame)
85
+
86
+ def _preprocess_image_for_latent_conversion(self, image: Image.Image, target_resolution: tuple) -> Image.Image:
87
+ if image.size != target_resolution:
88
+ return ImageOps.fit(image, target_resolution, Image.Resampling.LANCZOS)
89
+ return image
90
+
91
+ def pil_to_latent(self, pil_image: Image.Image) -> torch.Tensor:
92
+ image_np = np.array(pil_image).astype(np.float32) / 255.0
93
+ tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
94
+ tensor = (tensor * 2.0) - 1.0
95
+ return self.pixels_to_latents(tensor)
96
+
97
+ def _get_video_frame_count(self, video_path: str) -> int | None:
98
+ """Usa ffprobe para obter o número exato de frames de um arquivo de vídeo."""
99
+ if not os.path.exists(video_path):
100
+ logger.error(f"Arquivo de vídeo não encontrado para contagem de frames: {video_path}")
101
+ return None
102
+ cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_frames',
103
+ '-show_entries', 'stream=nb_read_frames', '-of', 'default=nokey=1:noprint_wrappers=1', video_path]
104
+ try:
105
+ result = subprocess.run(cmd, check=True, capture_output=True, text=True, encoding='utf-8')
106
+ return int(result.stdout.strip())
107
+ except (subprocess.CalledProcessError, ValueError, FileNotFoundError) as e:
108
+ logger.error(f"Erro ao contar frames com ffprobe para {video_path}: {e}")
109
+ return None
110
+
111
+ def _trim_last_frame_ffmpeg(self, input_path: str, output_path: str) -> bool:
112
+ """Cria uma cópia de um vídeo, removendo o último frame."""
113
+ frame_count = self._get_video_frame_count(input_path)
114
+ if frame_count is None or frame_count < 2:
115
+ logger.warning(f"Não foi possível podar o último frame de {input_path}. O vídeo é muito curto ou ocorreu um erro.")
116
+ if os.path.exists(input_path):
117
+ os.rename(input_path, output_path)
118
+ return True
119
+
120
+ vf_filter = f"select='lt(n,{frame_count - 1})',setpts=PTS-STARTPTS"
121
+ cmd_list = ['ffmpeg', '-y', '-i', input_path, '-vf', vf_filter, '-an', output_path]
122
+
123
+ try:
124
+ subprocess.run(cmd_list, check=True, capture_output=True, text=True, encoding='utf-8')
125
+ logger.info(f"Último frame podado com sucesso. Vídeo final salvo em: {output_path}")
126
+ return True
127
+ except subprocess.CalledProcessError as e:
128
+ logger.error(f"Erro no FFmpeg durante a poda do último frame: {e.stderr}")
129
+ return False
130
+
131
+ def _generate_video_from_latents(self, latent_tensor, base_name: str) -> str:
132
+ """
133
+ Gera um vídeo a partir de latentes, podando o último frame para garantir concatenação limpa.
134
+ """
135
+ untrimmed_video_path = os.path.join(self.workspace_dir, f"{base_name}_untrimmed.mp4")
136
+ trimmed_video_path = os.path.join(self.workspace_dir, f"{base_name}.mp4")
137
+
138
+ logger.info(f"Renderizando vídeo bruto (com frame n+1) para: {untrimmed_video_path}")
139
+ pixel_tensor = self.latents_to_pixels(latent_tensor)
140
+ self.save_video_from_tensor(pixel_tensor, untrimmed_video_path, fps=24)
141
+ del pixel_tensor
142
+ gc.collect()
143
+ torch.cuda.empty_cache()
144
+
145
+ logger.info(f"Iniciando a poda do frame final de {untrimmed_video_path}...")
146
+ success = self._trim_last_frame_ffmpeg(untrimmed_video_path, trimmed_video_path)
147
+
148
+ if os.path.exists(untrimmed_video_path):
149
+ os.remove(untrimmed_video_path)
150
+
151
+ if not success:
152
+ logger.error("Falha na poda do último frame. O fragmento pode conter um artefato.")
153
+ return untrimmed_video_path
154
+
155
+ return trimmed_video_path
156
+
157
+ def concatenate_videos_ffmpeg(self, video_paths: list[str], output_path: str) -> str:
158
+ """Concatena uma lista de arquivos de vídeo em um único arquivo usando FFmpeg."""
159
+ if not video_paths:
160
+ raise gr.Error("Nenhum fragmento de vídeo para montar.")
161
+
162
+ list_file_path = os.path.join(self.workspace_dir, "concat_list.txt")
163
+ with open(list_file_path, 'w', encoding='utf-8') as f:
164
+ for path in video_paths:
165
+ f.write(f"file '{os.path.abspath(path)}'\n")
166
+
167
+ cmd_list = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', list_file_path, '-c', 'copy', output_path]
168
+ logger.info("Executando concatenação FFmpeg para montagem final...")
169
+
170
+ try:
171
+ subprocess.run(cmd_list, check=True, capture_output=True, text=True)
172
+ except subprocess.CalledProcessError as e:
173
+ logger.error(f"Erro no FFmpeg durante a concatenação: {e.stderr}")
174
+ raise gr.Error(f"Falha na montagem final do vídeo. Detalhes: {e.stderr}")
175
+
176
+ return output_path
177
+
178
+ # NÚCLEO DA LÓGICA ADUC-SDR
179
+ def generate_full_movie(self, keyframes: list, global_prompt: str, storyboard: list,
180
+ seconds_per_fragment: float, trim_percent: int,
181
+ handler_strength: float, destination_convergence_strength: float,
182
+ video_resolution: int, use_continuity_director: bool,
183
+ progress: gr.Progress = gr.Progress()):
184
+
185
+ # 1. Definição dos Parâmetros da Geração com base na Tese
186
+ FPS = 24
187
+ FRAMES_PER_LATENT_CHUNK = 8
188
+ ECO_LATENT_CHUNKS = 2
189
+
190
+ total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
191
+ total_latents_brutos = total_frames_brutos // FRAMES_PER_LATENT_CHUNK
192
+
193
+ frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
194
+ latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK
195
+
196
+ if total_latents_brutos <= latents_a_podar:
197
+ raise gr.Error(f"A porcentagem de poda ({trim_percent}%) é muito alta. Reduza-a ou aumente a duração.")
198
+
199
+ DEJAVU_FRAME_TARGET = frames_a_podar - 1
200
+ DESTINATION_FRAME_TARGET = total_frames_brutos - 1
201
+
202
+ logger.info("--- CONFIGURAÇÃO DA GERAÇÃO ADUC-SDR ---")
203
+ logger.info(f"Total de Latents por Geração Exploratória (V_bruto): {total_latents_brutos} ({total_frames_brutos} frames)")
204
+ logger.info(f"Latents a serem descartados (Poda Causal): {latents_a_podar} ({frames_a_podar} frames)")
205
+ logger.info(f"Chunks Latentes do Eco Causal (C): {ECO_LATENT_CHUNKS}")
206
+ logger.info(f"Frame alvo do Déjà-Vu (D): {DEJAVU_FRAME_TARGET}")
207
+ logger.info(f"Frame alvo do Destino (K): {DESTINATION_FRAME_TARGET}")
208
+ logger.info("------------------------------------------")
209
+
210
+ # 2. Inicialização do Estado
211
+ base_ltx_params = {"guidance_scale": 2.0, "stg_scale": 0.025, "rescaling_scale": 0.15, "num_inference_steps": 20, "image_cond_noise_scale": 0.00}
212
+ keyframe_paths = [item[0] if isinstance(item, tuple) else item for item in keyframes]
213
+ video_clips_paths, story_history = [], ""
214
+ target_resolution_tuple = (video_resolution, video_resolution)
215
+
216
+ eco_latent_for_next_loop = None
217
+ dejavu_latent_for_next_loop = None
218
+
219
+ if len(keyframe_paths) < 2:
220
+ raise gr.Error(f"A geração requer no mínimo 2 keyframes. Você forneceu {len(keyframe_paths)}.")
221
+
222
+ num_transitions_to_generate = len(keyframe_paths) - 1
223
+
224
+ # 3. Loop Principal de Geração de Fragmentos
225
+ for i in range(num_transitions_to_generate):
226
+ fragment_index = i + 1
227
+ logger.info(f"--- INICIANDO FRAGMENTO {fragment_index}/{num_transitions_to_generate} ---")
228
+ progress(fragment_index / num_transitions_to_generate, desc=f"Produzindo Transição {fragment_index}/{num_transitions_to_generate}")
229
+
230
+ # 3.1. Consulta ao Maestro (Γ) para obter a intenção (Pᵢ)
231
+ past_keyframe_path = keyframe_paths[i - 1] if i > 0 else keyframe_paths[i]
232
+ start_keyframe_path = keyframe_paths[i]
233
+ destination_keyframe_path = keyframe_paths[i + 1]
234
+ future_story_prompt = storyboard[i + 1] if (i + 1) < len(storyboard) else "A cena final."
235
+
236
+ decision = gemini_singleton.get_cinematic_decision(
237
+ global_prompt, story_history, past_keyframe_path, start_keyframe_path, destination_keyframe_path,
238
+ storyboard[i - 1] if i > 0 else "O início.", storyboard[i], future_story_prompt
239
+ )
240
+ transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
241
+ story_history += f"\n- Ato {fragment_index}: {motion_prompt}"
242
+
243
+ # 3.2. Montagem das Âncoras para a Fórmula Canônica Ψ({C, D, K}, P)
244
+ conditioning_items = []
245
+ logger.info(" [Ψ.1] Montando âncoras causais...")
246
+
247
+ if eco_latent_for_next_loop is None:
248
+ logger.info(" - Primeiro fragmento: Usando Keyframe inicial como âncora de partida.")
249
+ img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
250
+ conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_start), 0, 1.0))
251
+ else:
252
+ logger.info(" - Âncora 1: Eco Causal (C) - Herança do passado.")
253
+ conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
254
+ logger.info(" - Âncora 2: Déjà-Vu (D) - Memória de um futuro idealizado.")
255
+ conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
256
+
257
+ logger.info(" - Âncora 3: Destino (K) - Âncora geométrica/narrativa.")
258
+ img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
259
+ conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_dest), DESTINATION_FRAME_TARGET, destination_convergence_strength))
260
+
261
+ # 3.3. Execução da Câmera (Ψ): Geração Exploratória para criar V_bruto
262
+ logger.info(f" [Ψ.2] Câmera (Ψ) executando a geração exploratória de {total_latents_brutos} chunks latentes...")
263
+ current_ltx_params = {**base_ltx_params, "motion_prompt": motion_prompt}
264
+ latents_brutos = self._generate_latent_tensor_internal(conditioning_items, current_ltx_params, target_resolution_tuple, total_frames_brutos)
265
+ logger.info(f" - Geração concluída. Tensor latente bruto (V_bruto) criado com shape: {latents_brutos.shape}.")
266
+
267
+ # 3.4. Execução do Destilador (Δ): Implementação do Ciclo de Poda Causal (com workaround empírico)
268
+ logger.info(f" [Δ] Destilador (Δ) executando o Ciclo de Poda Causal...")
269
+
270
+
271
+ last_trim = latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
272
+ eco_latent_for_next_loop = last_trim[:, :, :2, :, :].clone()
273
+ dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
274
+
275
+ latents_video = latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
276
+ latents_video = latents_video[:, :, 1:, :, :]
277
+
278
+ logger.info(f" [Δ] latents_video {latents_video.shape}")
279
+
280
+
281
+ #last_trim = latents_brutos[:, :, -(latents_a_podar + 2):, :, :].clone()
282
+ #eco_latent_for_next_loop = last_trim[:, :, :ECO_LATENT_CHUNKS, :, :].clone()
283
+ #dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
284
+
285
+ #latents_video = latents_brutos[:, :, :-(latents_a_podar + 2), :, :].clone()
286
+ #latents_video = latents_video[:, :, 2:, :, :]
287
+
288
+ #logger.info(f" [Δ] Shape do tensor para vídeo final: {latents_video.shape}")
289
+ logger.info(f" - (Δ.1) Déjà-Vu (D) destilado. Shape: {dejavu_latent_for_next_loop.shape}")
290
+ logger.info(f" - (Δ.2) Eco Causal (C) extraído. Shape: {eco_latent_for_next_loop.shape}")
291
+
292
+ if transition_type == "cut":
293
+ logger.warning(" - DECISÃO DO MAESTRO: Corte ('cut'). Resetando a memória causal (Eco e Déjà-Vu).")
294
+ eco_latent_for_next_loop = None
295
+ dejavu_latent_for_next_loop = None
296
+
297
+ # 3.5. Renderização e Armazenamento do Fragmento Final
298
+ base_name = f"fragment_{fragment_index}_{int(time.time())}"
299
+ video_path = self._generate_video_from_latents(latents_video, base_name)
300
+ video_clips_paths.append(video_path)
301
+ logger.info(f"--- FRAGMENTO {fragment_index} FINALIZADO E SALVO EM: {video_path} ---")
302
+
303
+ # Bloco de Diagnóstico: Gera um vídeo a partir do tensor do Eco
304
+ if eco_latent_for_next_loop is not None:
305
+ logger.info("--- GERANDO VÍDEO DE DIAGNÓSTICO DO ECO CAUSAL ---")
306
+ eco_base_name = f"fragment_{fragment_index}_eco_diagnostic_{int(time.time())}"
307
+ eco_video_path = self._generate_video_from_latents(eco_latent_for_next_loop, eco_base_name)
308
+ #video_clips_paths.append(eco_video_path)
309
+ logger.info(f"Vídeo de diagnóstico do Eco salvo em: {eco_video_path} e adicionado à concatenação.")
310
+ yield {"fragment_path": eco_video_path}
311
+
312
+ yield {"fragment_path": video_path}
313
+
314
+ # 4. Montagem Final do Filme
315
+ final_movie_path = os.path.join(self.workspace_dir, f"final_movie_silent_{int(time.time())}.mp4")
316
+ self.concatenate_videos_ffmpeg(video_clips_paths, final_movie_path)
317
+
318
+ logger.info(f"Filme completo (com clipes de diagnóstico) salvo em: {final_movie_path}")
319
+ yield {"final_path": final_movie_path}
320
+
321
+ def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
322
+ final_ltx_params = {
323
+ **ltx_params, 'width': target_resolution[0], 'height': target_resolution[1],
324
+ 'video_total_frames': total_frames_to_generate, 'video_fps': 24,
325
+ 'current_fragment_index': int(time.time()), 'conditioning_items_data': conditioning_items
326
+ }
327
+ new_full_latents, _ = self.ltx_manager.generate_latent_fragment(**final_ltx_params)
328
+ gc.collect()
329
+ torch.cuda.empty_cache()
330
+ return new_full_latents
331
+
332
+ def _quantize_to_multiple(self, n, m):
333
+ if m == 0: return n
334
+ quantized = int(round(n / m) * m)
335
+ return m if n > 0 and quantized == 0 else quantized