EU-IA commited on
Commit
74b4ab5
·
verified ·
1 Parent(s): 1c7c847

Upload deformes4D_engine_1756425074949.py

Browse files
Files changed (1) hide show
  1. deformes4D_engine_1756425074949.py +286 -0
deformes4D_engine_1756425074949.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # deformes4D_engine.py
2
+ # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
+ #
4
+ #
5
+ # MODIFICATIONS FOR ADUC-SDR:
6
+ # Copyright (C) 2025 Carlos Rodrigues dos Santos. All rights reserved.
7
+ #
8
+ # This file is part of the ADUC-SDR project. It contains the core logic for
9
+ # video fragment generation, latent manipulation, and dynamic editing,
10
+ # governed by the ADUC orchestrator.
11
+ # This component is licensed under the GNU Affero General Public License v3.0.
12
+
13
+ import os
14
+ import time
15
+ import imageio
16
+ import numpy as np
17
+ import torch
18
+ import logging
19
+ from PIL import Image, ImageOps
20
+ from dataclasses import dataclass
21
+ import gradio as gr
22
+ import subprocess
23
+ import random
24
+ import gc
25
+
26
+ from audio_specialist import audio_specialist_singleton
27
+ from ltx_manager_helpers import ltx_manager_singleton
28
+ from flux_kontext_helpers import flux_kontext_singleton
29
+ from gemini_helpers import gemini_singleton
30
+ from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ @dataclass
35
+ class LatentConditioningItem:
36
+ latent_tensor: torch.Tensor
37
+ media_frame_number: int
38
+ conditioning_strength: float
39
+
40
+ class Deformes4DEngine:
41
+ def __init__(self, ltx_manager, workspace_dir="deformes_workspace"):
42
+ self.ltx_manager = ltx_manager
43
+ self.workspace_dir = workspace_dir
44
+ self._vae = None
45
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
46
+ logger.info("Especialista Deformes4D (SDR Executor) inicializado.")
47
+
48
+ @property
49
+ def vae(self):
50
+ if self._vae is None:
51
+ self._vae = self.ltx_manager.workers[0].pipeline.vae
52
+ self._vae.to(self.device); self._vae.eval()
53
+ return self._vae
54
+
55
+ def save_latent_tensor(self, tensor: torch.Tensor, path: str):
56
+ torch.save(tensor.cpu(), path)
57
+ logger.info(f"Tensor latente salvo em: {path}")
58
+
59
+ def load_latent_tensor(self, path: str) -> torch.Tensor:
60
+ tensor = torch.load(path, map_location=self.device)
61
+ logger.info(f"Tensor latente carregado de: {path} para o dispositivo {self.device}")
62
+ return tensor
63
+
64
+ @torch.no_grad()
65
+ def pixels_to_latents(self, tensor: torch.Tensor) -> torch.Tensor:
66
+ tensor = tensor.to(self.device, dtype=self.vae.dtype)
67
+ return vae_encode(tensor, self.vae, vae_per_channel_normalize=True)
68
+
69
+ @torch.no_grad()
70
+ def latents_to_pixels(self, latent_tensor: torch.Tensor, decode_timestep: float = 0.05) -> torch.Tensor:
71
+ latent_tensor = latent_tensor.to(self.device, dtype=self.vae.dtype)
72
+ timestep_tensor = torch.tensor([decode_timestep] * latent_tensor.shape[0], device=self.device, dtype=latent_tensor.dtype)
73
+ return vae_decode(latent_tensor, self.vae, is_video=True, timestep=timestep_tensor, vae_per_channel_normalize=True)
74
+
75
+ def save_video_from_tensor(self, video_tensor: torch.Tensor, path: str, fps: int = 24):
76
+ if video_tensor is None or video_tensor.ndim != 5 or video_tensor.shape[2] == 0: return
77
+ video_tensor = video_tensor.squeeze(0).permute(1, 2, 3, 0)
78
+ video_tensor = (video_tensor.clamp(-1, 1) + 1) / 2.0
79
+ video_np = (video_tensor.detach().cpu().float().numpy() * 255).astype(np.uint8)
80
+ with imageio.get_writer(path, fps=fps, codec='libx264', quality=8) as writer:
81
+ for frame in video_np: writer.append_data(frame)
82
+ logger.info(f"Vídeo salvo em: {path}")
83
+
84
+ def _preprocess_image_for_latent_conversion(self, image: Image.Image, target_resolution: tuple) -> Image.Image:
85
+ if image.size != target_resolution:
86
+ logger.info(f" - AÇÃO: Redimensionando imagem de {image.size} para {target_resolution} antes da conversão para latente.")
87
+ return ImageOps.fit(image, target_resolution, Image.Resampling.LANCZOS)
88
+ return image
89
+
90
+ def pil_to_latent(self, pil_image: Image.Image) -> torch.Tensor:
91
+ image_np = np.array(pil_image).astype(np.float32) / 255.0
92
+ tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
93
+ tensor = (tensor * 2.0) - 1.0
94
+ return self.pixels_to_latents(tensor)
95
+
96
+ def _generate_video_and_audio_from_latents(self, latent_tensor, audio_prompt, base_name):
97
+ silent_video_path = os.path.join(self.workspace_dir, f"{base_name}_silent.mp4")
98
+ pixel_tensor = self.latents_to_pixels(latent_tensor)
99
+ self.save_video_from_tensor(pixel_tensor, silent_video_path, fps=24)
100
+ del pixel_tensor; gc.collect()
101
+
102
+ try:
103
+ result = subprocess.run(
104
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", silent_video_path],
105
+ capture_output=True, text=True, check=True)
106
+ frag_duration = float(result.stdout.strip())
107
+ except (subprocess.CalledProcessError, ValueError, FileNotFoundError):
108
+ logger.warning(f"ffprobe falhou em {os.path.basename(silent_video_path)}. Calculando duração manualmente.")
109
+ num_pixel_frames = latent_tensor.shape[2] * 8
110
+ frag_duration = num_pixel_frames / 24.0
111
+
112
+ video_with_audio_path = audio_specialist_singleton.generate_audio_for_video(
113
+ video_path=silent_video_path, prompt=audio_prompt,
114
+ duration_seconds=frag_duration)
115
+
116
+ if os.path.exists(silent_video_path):
117
+ os.remove(silent_video_path)
118
+ return video_with_audio_path
119
+
120
+ def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
121
+ final_ltx_params = {
122
+ **ltx_params,
123
+ 'width': target_resolution[0], 'height': target_resolution[1],
124
+ 'video_total_frames': total_frames_to_generate, 'video_fps': 24,
125
+ 'current_fragment_index': int(time.time()),
126
+ 'conditioning_items_data': conditioning_items
127
+ }
128
+ new_full_latents, _ = self.ltx_manager.generate_latent_fragment(**final_ltx_params)
129
+ return new_full_latents
130
+
131
+ def concatenate_videos_ffmpeg(self, video_paths: list[str], output_path: str) -> str:
132
+ if not video_paths:
133
+ raise gr.Error("Nenhum fragmento de vídeo para montar.")
134
+ list_file_path = os.path.join(self.workspace_dir, "concat_list.txt")
135
+ with open(list_file_path, 'w', encoding='utf-8') as f:
136
+ for path in video_paths:
137
+ f.write(f"file '{os.path.abspath(path)}'\n")
138
+ cmd_list = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', list_file_path, '-c', 'copy', output_path]
139
+ logger.info("Executando concatenação FFmpeg...")
140
+ try:
141
+ subprocess.run(cmd_list, check=True, capture_output=True, text=True)
142
+ except subprocess.CalledProcessError as e:
143
+ logger.error(f"Erro no FFmpeg: {e.stderr}")
144
+ raise gr.Error(f"Falha na montagem final do vídeo. Detalhes: {e.stderr}")
145
+ return output_path
146
+
147
+ def generate_full_movie(self,
148
+ keyframes: list,
149
+ global_prompt: str,
150
+ storyboard: list,
151
+ seconds_per_fragment: float,
152
+ overlap_percent: int,
153
+ echo_frames: int,
154
+ handler_strength: float,
155
+ destination_convergence_strength: float,
156
+ base_ltx_params: dict,
157
+ video_resolution: int,
158
+ use_continuity_director: bool,
159
+ progress: gr.Progress = gr.Progress()):
160
+
161
+ keyframe_paths = [item[0] if isinstance(item, tuple) else item for item in keyframes]
162
+ video_clips_paths, story_history, audio_history = [], "", "This is the beginning of the film."
163
+ target_resolution_tuple = (video_resolution, video_resolution)
164
+ n_trim_latents = self._quantize_to_multiple(int(seconds_per_fragment * 24 * (overlap_percent / 100.0)), 8)
165
+ #echo_frames = 8
166
+
167
+ previous_latents_path = None
168
+ num_transitions_to_generate = len(keyframe_paths) - 1
169
+
170
+ for i in range(num_transitions_to_generate):
171
+ progress((i + 1) / num_transitions_to_generate, desc=f"Produzindo Transição {i+1}/{num_transitions_to_generate}")
172
+
173
+ start_keyframe_path = keyframe_paths[i]
174
+ destination_keyframe_path = keyframe_paths[i+1]
175
+ present_scene_desc = storyboard[i]
176
+
177
+ is_first_fragment = previous_latents_path is None
178
+ if is_first_fragment:
179
+ transition_type = "start"
180
+ motion_prompt = gemini_singleton.get_initial_motion_prompt(
181
+ global_prompt, start_keyframe_path, destination_keyframe_path, present_scene_desc
182
+ )
183
+ else:
184
+ past_keyframe_path = keyframe_paths[i-1]
185
+ past_scene_desc = storyboard[i-1]
186
+ future_scene_desc = storyboard[i+1] if (i+1) < len(storyboard) else "A cena final."
187
+ decision = gemini_singleton.get_cinematic_decision(
188
+ global_prompt=global_prompt, story_history=story_history,
189
+ past_keyframe_path=past_keyframe_path, present_keyframe_path=start_keyframe_path,
190
+ future_keyframe_path=destination_keyframe_path, past_scene_desc=past_scene_desc,
191
+ present_scene_desc=present_scene_desc, future_scene_desc=future_scene_desc
192
+ )
193
+ transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
194
+
195
+ story_history += f"\n- Ato {i+1} ({transition_type}): {motion_prompt}"
196
+
197
+ if use_continuity_director: # Assume-se que este checkbox controla os diretores de vídeo e som
198
+ if is_first_fragment:
199
+ audio_prompt = gemini_singleton.get_sound_director_prompt(
200
+ audio_history=audio_history,
201
+ past_keyframe_path=start_keyframe_path, present_keyframe_path=start_keyframe_path,
202
+ future_keyframe_path=destination_keyframe_path, present_scene_desc=present_scene_desc,
203
+ motion_prompt=motion_prompt, future_scene_desc=storyboard[i+1] if (i+1) < len(storyboard) else "The final scene."
204
+ )
205
+ else:
206
+ audio_prompt = gemini_singleton.get_sound_director_prompt(
207
+ audio_history=audio_history, past_keyframe_path=keyframe_paths[i-1],
208
+ present_keyframe_path=start_keyframe_path, future_keyframe_path=destination_keyframe_path,
209
+ present_scene_desc=present_scene_desc, motion_prompt=motion_prompt,
210
+ future_scene_desc=storyboard[i+1] if (i+1) < len(storyboard) else "The final scene."
211
+ )
212
+ else:
213
+ audio_prompt = present_scene_desc # Fallback para o prompt da cena se o diretor de som estiver desligado
214
+
215
+ audio_history = audio_prompt
216
+
217
+ conditioning_items = []
218
+ current_ltx_params = {**base_ltx_params, "handler_strength": handler_strength, "motion_prompt": motion_prompt}
219
+ total_frames_to_generate = self._quantize_to_multiple(int(seconds_per_fragment * 24), 8) + 1
220
+
221
+ if is_first_fragment:
222
+ img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
223
+ start_latent = self.pil_to_latent(img_start)
224
+ conditioning_items.append(LatentConditioningItem(start_latent, 0, 1.0))
225
+ if transition_type != "cut":
226
+ img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
227
+ destination_latent = self.pil_to_latent(img_dest)
228
+ conditioning_items.append(LatentConditioningItem(destination_latent, total_frames_to_generate - 1, destination_convergence_strength))
229
+ else:
230
+ previous_latents = self.load_latent_tensor(previous_latents_path)
231
+ handler_latent = previous_latents[:, :, -1:, :, :]
232
+ trimmed_for_echo = previous_latents[:, :, :-n_trim_latents, :, :] if n_trim_latents > 0 and previous_latents.shape[2] > n_trim_latents else previous_latents
233
+ echo_latents = trimmed_for_echo[:, :, -echo_frames:, :, :]
234
+ handler_frame_position = n_trim_latents + echo_frames
235
+
236
+
237
+ conditioning_items.append(LatentConditioningItem(echo_latents, 0, 1.0))
238
+ conditioning_items.append(LatentConditioningItem(handler_latent, handler_frame_position, handler_strength))
239
+ del previous_latents, handler_latent, trimmed_for_echo, echo_latents; gc.collect()
240
+ if transition_type == "continuous":
241
+ img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
242
+ destination_latent = self.pil_to_latent(img_dest)
243
+ conditioning_items.append(LatentConditioningItem(destination_latent, total_frames_to_generate - 1, destination_convergence_strength))
244
+
245
+ new_full_latents = self._generate_latent_tensor_internal(conditioning_items, current_ltx_params, target_resolution_tuple, total_frames_to_generate)
246
+
247
+ base_name = f"fragment_{i}_{int(time.time())}"
248
+ new_full_latents_path = os.path.join(self.workspace_dir, f"{base_name}_full.pt")
249
+ self.save_latent_tensor(new_full_latents, new_full_latents_path)
250
+
251
+ previous_latents_path = new_full_latents_path
252
+
253
+ latents_for_video = new_full_latents
254
+
255
+ # Aplicar cortes apenas onde necessário para evitar duplicação
256
+ if not is_first_fragment:
257
+ # Remove apenas o eco do início para evitar duplicação com fragmento anterior
258
+ if echo_frames > 0 and latents_for_video.shape[2] > echo_frames:
259
+ latents_for_video = latents_for_video[:, :, echo_frames:, :, :]
260
+
261
+ # Para todos os fragmentos exceto o último, remove sobreposição do final
262
+ is_last_fragment = (i == num_transitions_to_generate - 1)
263
+ if not is_last_fragment:
264
+ if n_trim_latents > 0 and latents_for_video.shape[2] > n_trim_latents:
265
+ latents_for_video = latents_for_video[:, :, :-n_trim_latents, :, :]
266
+
267
+ video_with_audio_path = self._generate_video_and_audio_from_latents(latents_for_video, audio_prompt, base_name)
268
+ video_clips_paths.append(video_with_audio_path)
269
+
270
+
271
+ if transition_type == "cut":
272
+ previous_latents_path = None
273
+
274
+
275
+ yield {"fragment_path": video_with_audio_path}
276
+
277
+ final_movie_path = os.path.join(self.workspace_dir, f"final_movie_{int(time.time())}.mp4")
278
+ self.concatenate_videos_ffmpeg(video_clips_paths, final_movie_path)
279
+
280
+ logger.info(f"Filme completo salvo em: {final_movie_path}")
281
+ yield {"final_path": final_movie_path}
282
+
283
+ def _quantize_to_multiple(self, n, m):
284
+ if m == 0: return n
285
+ quantized = int(round(n / m) * m)
286
+ return m if n > 0 and quantized == 0 else quantized