Delete deformes4D_engine.py
Browse files- deformes4D_engine.py +0 -258
deformes4D_engine.py
DELETED
|
@@ -1,258 +0,0 @@
|
|
| 1 |
-
# deformes4D_engine.py
|
| 2 |
-
# Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
|
| 3 |
-
# (Licenciamento e cabeçalhos permanecem os mesmos)
|
| 4 |
-
|
| 5 |
-
import os
|
| 6 |
-
import time
|
| 7 |
-
import imageio
|
| 8 |
-
import numpy as np
|
| 9 |
-
import torch
|
| 10 |
-
import logging
|
| 11 |
-
from PIL import Image, ImageOps
|
| 12 |
-
from dataclasses import dataclass
|
| 13 |
-
import gradio as gr
|
| 14 |
-
import subprocess
|
| 15 |
-
import gc
|
| 16 |
-
|
| 17 |
-
from ltx_manager_helpers import ltx_manager_singleton
|
| 18 |
-
from gemini_helpers import gemini_singleton
|
| 19 |
-
from upscaler_specialist import upscaler_specialist_singleton
|
| 20 |
-
from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
|
| 21 |
-
from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
|
| 22 |
-
|
| 23 |
-
logger = logging.getLogger(__name__)
|
| 24 |
-
|
| 25 |
-
@dataclass
|
| 26 |
-
class LatentConditioningItem:
|
| 27 |
-
latent_tensor: torch.Tensor
|
| 28 |
-
media_frame_number: int
|
| 29 |
-
conditioning_strength: float
|
| 30 |
-
|
| 31 |
-
class Deformes4DEngine:
|
| 32 |
-
def __init__(self, ltx_manager, workspace_dir="deformes_workspace"):
|
| 33 |
-
self.ltx_manager = ltx_manager
|
| 34 |
-
self.workspace_dir = workspace_dir
|
| 35 |
-
self._vae = None
|
| 36 |
-
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 37 |
-
logger.info("Especialista Deformes4D (Executor ADUC-SDR: Câmera Ψ e Destilador Δ) inicializado.")
|
| 38 |
-
|
| 39 |
-
@property
|
| 40 |
-
def vae(self):
|
| 41 |
-
if self._vae is None:
|
| 42 |
-
self._vae = self.ltx_manager.workers[0].pipeline.vae
|
| 43 |
-
self._vae.to(self.device); self._vae.eval()
|
| 44 |
-
return self._vae
|
| 45 |
-
|
| 46 |
-
# MÉTODOS AUXILIARES (IDÊNTICOS AO v35)
|
| 47 |
-
def save_latent_tensor(self, tensor: torch.Tensor, path: str):
|
| 48 |
-
torch.save(tensor.cpu(), path)
|
| 49 |
-
|
| 50 |
-
def load_latent_tensor(self, path: str) -> torch.Tensor:
|
| 51 |
-
return torch.load(path, map_location=self.device)
|
| 52 |
-
|
| 53 |
-
@torch.no_grad()
|
| 54 |
-
def pixels_to_latents(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 55 |
-
tensor = tensor.to(self.device, dtype=self.vae.dtype)
|
| 56 |
-
return vae_encode(tensor, self.vae, vae_per_channel_normalize=True)
|
| 57 |
-
|
| 58 |
-
@torch.no_grad()
|
| 59 |
-
def latents_to_pixels(self, latent_tensor: torch.Tensor, decode_timestep: float = 0.05) -> torch.Tensor:
|
| 60 |
-
latent_tensor = latent_tensor.to(self.device, dtype=self.vae.dtype)
|
| 61 |
-
timestep_tensor = torch.tensor([decode_timestep] * latent_tensor.shape[0], device=self.device, dtype=latent_tensor.dtype)
|
| 62 |
-
return vae_decode(latent_tensor, self.vae, is_video=True, timestep=timestep_tensor, vae_per_channel_normalize=True)
|
| 63 |
-
|
| 64 |
-
def save_video_from_tensor(self, video_tensor: torch.Tensor, path: str, fps: int = 24):
|
| 65 |
-
if video_tensor is None or video_tensor.ndim != 5 or video_tensor.shape[2] == 0: return
|
| 66 |
-
video_tensor = video_tensor.squeeze(0).permute(1, 2, 3, 0)
|
| 67 |
-
video_tensor = (video_tensor.clamp(-1, 1) + 1) / 2.0
|
| 68 |
-
video_np = (video_tensor.detach().cpu().float().numpy() * 255).astype(np.uint8)
|
| 69 |
-
with imageio.get_writer(path, fps=fps, codec='libx264', quality=8) as writer:
|
| 70 |
-
for frame in video_np: writer.append_data(frame)
|
| 71 |
-
|
| 72 |
-
def _preprocess_image_for_latent_conversion(self, image: Image.Image, target_resolution: tuple) -> Image.Image:
|
| 73 |
-
if image.size != target_resolution:
|
| 74 |
-
return ImageOps.fit(image, target_resolution, Image.Resampling.LANCZOS)
|
| 75 |
-
return image
|
| 76 |
-
|
| 77 |
-
def pil_to_latent(self, pil_image: Image.Image) -> torch.Tensor:
|
| 78 |
-
image_np = np.array(pil_image).astype(np.float32) / 255.0
|
| 79 |
-
tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
|
| 80 |
-
tensor = (tensor * 2.0) - 1.0
|
| 81 |
-
return self.pixels_to_latents(tensor)
|
| 82 |
-
|
| 83 |
-
def _get_video_frame_count(self, video_path: str) -> int | None:
|
| 84 |
-
if not os.path.exists(video_path): return None
|
| 85 |
-
cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_frames',
|
| 86 |
-
'-show_entries', 'stream=nb_read_frames', '-of', 'default=nokey=1:noprint_wrappers=1', video_path]
|
| 87 |
-
try:
|
| 88 |
-
result = subprocess.run(cmd, check=True, capture_output=True, text=True, encoding='utf-8')
|
| 89 |
-
return int(result.stdout.strip())
|
| 90 |
-
except Exception: return None
|
| 91 |
-
|
| 92 |
-
def _trim_last_frame_ffmpeg(self, input_path: str, output_path: str) -> bool:
|
| 93 |
-
frame_count = self._get_video_frame_count(input_path)
|
| 94 |
-
if frame_count is None or frame_count < 2:
|
| 95 |
-
if os.path.exists(input_path): os.rename(input_path, output_path)
|
| 96 |
-
return True
|
| 97 |
-
vf_filter = f"select='lt(n,{frame_count - 1})',setpts=PTS-STARTPTS"
|
| 98 |
-
cmd_list = ['ffmpeg', '-y', '-i', input_path, '-vf', vf_filter, '-an', output_path]
|
| 99 |
-
try:
|
| 100 |
-
subprocess.run(cmd_list, check=True, capture_output=True, text=True, encoding='utf-8')
|
| 101 |
-
return True
|
| 102 |
-
except subprocess.CalledProcessError: return False
|
| 103 |
-
|
| 104 |
-
def concatenate_videos_ffmpeg(self, video_paths: list[str], output_path: str) -> str:
|
| 105 |
-
if not video_paths: raise gr.Error("Nenhum fragmento de vídeo para montar.")
|
| 106 |
-
list_file_path = os.path.join(self.workspace_dir, "concat_list.txt")
|
| 107 |
-
with open(list_file_path, 'w', encoding='utf-8') as f:
|
| 108 |
-
for path in video_paths: f.write(f"file '{os.path.abspath(path)}'\n")
|
| 109 |
-
cmd_list = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', list_file_path, '-c', 'copy', output_path]
|
| 110 |
-
try:
|
| 111 |
-
subprocess.run(cmd_list, check=True, capture_output=True, text=True)
|
| 112 |
-
except subprocess.CalledProcessError as e:
|
| 113 |
-
raise gr.Error(f"Falha na montagem final do vídeo. Detalhes: {e.stderr}")
|
| 114 |
-
return output_path
|
| 115 |
-
|
| 116 |
-
# --- PIPELINE DE PÓS-PRODUÇÃO LATENTE ---
|
| 117 |
-
def _render_and_post_process_latents(self,
|
| 118 |
-
low_res_latents: torch.Tensor,
|
| 119 |
-
base_name: str,
|
| 120 |
-
conditioning_items_for_refine: list,
|
| 121 |
-
motion_prompt_for_refine: str
|
| 122 |
-
) -> str:
|
| 123 |
-
high_res_latents = upscaler_specialist_singleton.upscale(low_res_latents)
|
| 124 |
-
|
| 125 |
-
_, _, _, refined_h_latent, refined_w_latent = high_res_latents.shape
|
| 126 |
-
video_h = refined_h_latent * self.ltx_manager.workers[0].pipeline.vae_scale_factor
|
| 127 |
-
video_w = refined_w_latent * self.ltx_manager.workers[0].pipeline.vae_scale_factor
|
| 128 |
-
num_latent_frames = high_res_latents.shape[2]
|
| 129 |
-
num_video_frames = num_latent_frames * self.ltx_manager.workers[0].pipeline.video_scale_factor
|
| 130 |
-
if isinstance(self.vae, CausalVideoAutoencoder):
|
| 131 |
-
num_video_frames -= 1
|
| 132 |
-
|
| 133 |
-
refine_kwargs = {
|
| 134 |
-
'height': video_h, 'width': video_w, 'video_total_frames': num_video_frames, 'video_fps': 24,
|
| 135 |
-
'current_fragment_index': int(time.time()), 'motion_prompt': motion_prompt_for_refine,
|
| 136 |
-
'conditioning_items_data': conditioning_items_for_refine,
|
| 137 |
-
'denoise_strength': 0.4, 'refine_steps': 10
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
final_latents, _ = self.ltx_manager.refine_latents(high_res_latents, **refine_kwargs)
|
| 141 |
-
|
| 142 |
-
untrimmed_video_path = os.path.join(self.workspace_dir, f"{base_name}_untrimmed.mp4")
|
| 143 |
-
trimmed_video_path = os.path.join(self.workspace_dir, f"{base_name}.mp4")
|
| 144 |
-
|
| 145 |
-
pixel_tensor = self.latents_to_pixels(final_latents)
|
| 146 |
-
self.save_video_from_tensor(pixel_tensor, untrimmed_video_path, fps=24)
|
| 147 |
-
del pixel_tensor, final_latents, high_res_latents
|
| 148 |
-
gc.collect()
|
| 149 |
-
torch.cuda.empty_cache()
|
| 150 |
-
|
| 151 |
-
success = self._trim_last_frame_ffmpeg(untrimmed_video_path, trimmed_video_path)
|
| 152 |
-
|
| 153 |
-
if os.path.exists(untrimmed_video_path):
|
| 154 |
-
os.remove(untrimmed_video_path)
|
| 155 |
-
|
| 156 |
-
return trimmed_video_path if success else untrimmed_video_path
|
| 157 |
-
|
| 158 |
-
# NÚCLEO DA LÓGICA ADUC-SDR
|
| 159 |
-
def generate_full_movie(self, keyframes: list, global_prompt: str, storyboard: list,
|
| 160 |
-
seconds_per_fragment: float, trim_percent: int,
|
| 161 |
-
handler_strength: float, destination_convergence_strength: float,
|
| 162 |
-
video_resolution: int, use_continuity_director: bool,
|
| 163 |
-
progress: gr.Progress = gr.Progress()):
|
| 164 |
-
|
| 165 |
-
FPS = 24
|
| 166 |
-
FRAMES_PER_LATENT_CHUNK = 8
|
| 167 |
-
ECO_LATENT_CHUNKS = 2
|
| 168 |
-
|
| 169 |
-
total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
|
| 170 |
-
total_latents_brutos = total_frames_brutos // FRAMES_PER_LATENT_CHUNK
|
| 171 |
-
frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
|
| 172 |
-
latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK
|
| 173 |
-
|
| 174 |
-
if total_latents_brutos <= latents_a_podar + 1:
|
| 175 |
-
raise gr.Error(f"A combinação de duração e poda é muito agressiva.")
|
| 176 |
-
|
| 177 |
-
DEJAVU_FRAME_TARGET = frames_a_podar - 1
|
| 178 |
-
DESTINATION_FRAME_TARGET = total_frames_brutos - 1
|
| 179 |
-
|
| 180 |
-
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}
|
| 181 |
-
keyframe_paths = [item[0] if isinstance(item, tuple) else item for item in keyframes]
|
| 182 |
-
video_clips_paths, story_history = [], ""
|
| 183 |
-
target_resolution_tuple = (video_resolution, video_resolution)
|
| 184 |
-
|
| 185 |
-
eco_latent_for_next_loop = None
|
| 186 |
-
dejavu_latent_for_next_loop = None
|
| 187 |
-
|
| 188 |
-
num_transitions_to_generate = len(keyframe_paths) - 1
|
| 189 |
-
|
| 190 |
-
for i in range(num_transitions_to_generate):
|
| 191 |
-
fragment_index = i + 1
|
| 192 |
-
progress(fragment_index / num_transitions_to_generate, desc=f"Produzindo Transição {fragment_index}/{num_transitions_to_generate}")
|
| 193 |
-
|
| 194 |
-
past_keyframe_path = keyframe_paths[i - 1] if i > 0 else keyframe_paths[i]
|
| 195 |
-
start_keyframe_path = keyframe_paths[i]
|
| 196 |
-
destination_keyframe_path = keyframe_paths[i + 1]
|
| 197 |
-
future_story_prompt = storyboard[i + 1] if (i + 1) < len(storyboard) else "A cena final."
|
| 198 |
-
decision = gemini_singleton.get_cinematic_decision(
|
| 199 |
-
global_prompt, story_history, past_keyframe_path, start_keyframe_path, destination_keyframe_path,
|
| 200 |
-
storyboard[i - 1] if i > 0 else "O início.", storyboard[i], future_story_prompt)
|
| 201 |
-
transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
|
| 202 |
-
story_history += f"\n- Ato {fragment_index}: {motion_prompt}"
|
| 203 |
-
|
| 204 |
-
conditioning_items = []
|
| 205 |
-
if eco_latent_for_next_loop is None:
|
| 206 |
-
img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 207 |
-
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_start), 0, 1.0))
|
| 208 |
-
else:
|
| 209 |
-
conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
|
| 210 |
-
conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
|
| 211 |
-
img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 212 |
-
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_dest), DESTINATION_FRAME_TARGET, destination_convergence_strength))
|
| 213 |
-
|
| 214 |
-
current_ltx_params = {**base_ltx_params, "motion_prompt": motion_prompt}
|
| 215 |
-
latents_brutos, _ = self._generate_latent_tensor_internal(conditioning_items, current_ltx_params, target_resolution_tuple, total_frames_brutos)
|
| 216 |
-
|
| 217 |
-
last_trim = latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
|
| 218 |
-
eco_latent_for_next_loop = last_trim[:, :, :ECO_LATENT_CHUNKS, :, :].clone()
|
| 219 |
-
dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
|
| 220 |
-
latents_video = latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
|
| 221 |
-
latents_video = latents_video[:, :, 1:, :, :]
|
| 222 |
-
|
| 223 |
-
if transition_type == "cut":
|
| 224 |
-
eco_latent_for_next_loop, dejavu_latent_for_next_loop = None, None
|
| 225 |
-
|
| 226 |
-
base_name = f"fragment_{fragment_index}_{int(time.time())}"
|
| 227 |
-
video_path = self._render_and_post_process_latents(
|
| 228 |
-
low_res_latents=latents_video, base_name=base_name,
|
| 229 |
-
conditioning_items_for_refine=conditioning_items,
|
| 230 |
-
motion_prompt_for_refine=motion_prompt)
|
| 231 |
-
video_clips_paths.append(video_path)
|
| 232 |
-
yield {"fragment_path": video_path}
|
| 233 |
-
|
| 234 |
-
if eco_latent_for_next_loop is not None:
|
| 235 |
-
eco_base_name = f"fragment_{fragment_index}_eco_diagnostic"
|
| 236 |
-
eco_pixel_tensor = self.latents_to_pixels(eco_latent_for_next_loop)
|
| 237 |
-
eco_video_path = os.path.join(self.workspace_dir, f"{eco_base_name}.mp4")
|
| 238 |
-
self.save_video_from_tensor(eco_pixel_tensor, eco_video_path)
|
| 239 |
-
video_clips_paths.append(eco_video_path)
|
| 240 |
-
yield {"fragment_path": eco_video_path}
|
| 241 |
-
|
| 242 |
-
final_movie_path = os.path.join(self.workspace_dir, f"final_movie_silent_{int(time.time())}.mp4")
|
| 243 |
-
self.concatenate_videos_ffmpeg(video_clips_paths, final_movie_path)
|
| 244 |
-
|
| 245 |
-
yield {"final_path": final_movie_path}
|
| 246 |
-
|
| 247 |
-
def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
|
| 248 |
-
kwargs = {
|
| 249 |
-
**ltx_params, 'width': target_resolution[0], 'height': target_resolution[1],
|
| 250 |
-
'video_total_frames': total_frames_to_generate, 'video_fps': 24,
|
| 251 |
-
'current_fragment_index': int(time.time()), 'conditioning_items_data': conditioning_items
|
| 252 |
-
}
|
| 253 |
-
return self.ltx_manager.generate_latent_fragment(**kwargs)
|
| 254 |
-
|
| 255 |
-
def _quantize_to_multiple(self, n, m):
|
| 256 |
-
if m == 0: return n
|
| 257 |
-
quantized = int(round(n / m) * m)
|
| 258 |
-
return m if n > 0 and quantized == 0 else quantized
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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