Spaces:
Runtime error
Runtime error
Update deformes4D_engine.py
Browse files- deformes4D_engine.py +131 -86
deformes4D_engine.py
CHANGED
|
@@ -27,6 +27,7 @@ from upscaler_specialist import upscaler_specialist_singleton
|
|
| 27 |
from hd_specialist import hd_specialist_singleton
|
| 28 |
from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
|
| 29 |
from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
|
|
|
|
| 30 |
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
|
@@ -78,104 +79,141 @@ class Deformes4DEngine:
|
|
| 78 |
tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
|
| 79 |
tensor = (tensor * 2.0) - 1.0
|
| 80 |
return self.pixels_to_latents(tensor)
|
| 81 |
-
|
|
|
|
| 82 |
# --- NÚCLEO DA LÓGICA ADUC-SDR ---
|
| 83 |
-
def
|
| 84 |
seconds_per_fragment: float, trim_percent: int,
|
| 85 |
handler_strength: float, destination_convergence_strength: float,
|
| 86 |
use_upscaler: bool, use_refiner: bool, use_hd: bool, use_audio: bool,
|
| 87 |
video_resolution: int, use_continuity_director: bool,
|
| 88 |
progress: gr.Progress = gr.Progress()):
|
| 89 |
|
| 90 |
-
|
| 91 |
-
TOTAL_STEPS = num_transitions_to_generate + 4
|
| 92 |
-
current_step = 0
|
| 93 |
-
|
| 94 |
FPS = 24
|
| 95 |
FRAMES_PER_LATENT_CHUNK = 8
|
| 96 |
ECO_LATENT_CHUNKS = 2
|
| 97 |
|
| 98 |
total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
|
|
|
|
|
|
|
| 99 |
frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
|
| 100 |
latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
| 103 |
DESTINATION_FRAME_TARGET = total_frames_brutos - 1
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
keyframe_paths.append(item)
|
| 113 |
-
elif isinstance(item, tuple) and len(item) > 0:
|
| 114 |
-
keyframe_paths.append(item[0]) # Assume que o caminho está no primeiro elemento da tupla
|
| 115 |
-
elif hasattr(item, 'name'):
|
| 116 |
-
keyframe_paths.append(item.name)
|
| 117 |
-
else:
|
| 118 |
-
logger.warning(f"Item na lista de keyframes com tipo inesperado e sem atributo '.name': {type(item)}")
|
| 119 |
-
# --- [FIM DA CORREÇÃO] ---
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
eco_latent_for_next_loop = None
|
| 123 |
dejavu_latent_for_next_loop = None
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
for i in range(num_transitions_to_generate):
|
| 128 |
fragment_index = i + 1
|
| 129 |
-
|
| 130 |
-
progress(
|
| 131 |
|
|
|
|
| 132 |
past_keyframe_path = keyframe_paths[i - 1] if i > 0 else keyframe_paths[i]
|
| 133 |
start_keyframe_path = keyframe_paths[i]
|
| 134 |
destination_keyframe_path = keyframe_paths[i + 1]
|
| 135 |
future_story_prompt = storyboard[i + 1] if (i + 1) < len(storyboard) else "A cena final."
|
|
|
|
| 136 |
decision = gemini_singleton.get_cinematic_decision(
|
| 137 |
global_prompt, story_history, past_keyframe_path, start_keyframe_path, destination_keyframe_path,
|
| 138 |
-
storyboard[i - 1] if i > 0 else "O início.", storyboard[i], future_story_prompt
|
|
|
|
| 139 |
transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
|
| 140 |
story_history += f"\n- Ato {fragment_index}: {motion_prompt}"
|
| 141 |
|
| 142 |
-
|
| 143 |
-
downscale_factor = 2 / 3
|
| 144 |
-
downscaled_height = self._quantize_to_multiple(int(expected_height * downscale_factor), 8)
|
| 145 |
-
downscaled_width = self._quantize_to_multiple(int(expected_width * downscale_factor), 8)
|
| 146 |
-
target_resolution_tuple = (downscaled_height, downscaled_width)
|
| 147 |
-
|
| 148 |
conditioning_items = []
|
|
|
|
|
|
|
| 149 |
if eco_latent_for_next_loop is None:
|
|
|
|
| 150 |
img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 151 |
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_start), 0, 1.0))
|
| 152 |
else:
|
|
|
|
| 153 |
conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
|
|
|
|
| 154 |
conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
|
|
|
|
|
|
|
| 155 |
img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 156 |
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_dest), DESTINATION_FRAME_TARGET, destination_convergence_strength))
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
current_ltx_params = {**base_ltx_params, "motion_prompt": motion_prompt}
|
| 159 |
-
latents_brutos
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
last_trim = latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
|
| 162 |
-
eco_latent_for_next_loop = last_trim[:, :, :
|
| 163 |
dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
|
|
|
|
| 164 |
latents_video = latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
|
| 165 |
latents_video = latents_video[:, :, 1:, :, :]
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
if transition_type == "cut":
|
| 168 |
-
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
# --- ATO II: PÓS-PRODUÇÃO LATENTE GLOBAL (CONDICIONAL) ---
|
| 173 |
current_step += 1
|
| 174 |
progress(current_step / TOTAL_STEPS, desc="Unificação Causal (Concatenação)...")
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
|
|
|
|
|
|
|
|
|
| 179 |
if use_refiner:
|
| 180 |
current_step += 1
|
| 181 |
progress(current_step / TOTAL_STEPS, desc="Polimento Global (Denoise)...")
|
|
@@ -188,60 +226,63 @@ class Deformes4DEngine:
|
|
| 188 |
else:
|
| 189 |
logger.info("Etapa de refinamento desativada.")
|
| 190 |
|
| 191 |
-
|
| 192 |
base_name = f"movie_{int(time.time())}"
|
| 193 |
current_step += 1
|
| 194 |
progress(current_step / TOTAL_STEPS, desc="Renderização (em lotes)...")
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
processed_chunk = self.upscale_latents(latent_chunk) if use_upscaler else latent_chunk
|
| 205 |
-
pixel_tensor_chunk = self.latents_to_pixels(processed_chunk)
|
| 206 |
-
|
| 207 |
-
pixel_tensor_chunk = pixel_tensor_chunk.squeeze(0).permute(1, 2, 3, 0)
|
| 208 |
-
pixel_tensor_chunk = (pixel_tensor_chunk.clamp(-1, 1) + 1) / 2.0
|
| 209 |
-
video_np_chunk = (pixel_tensor_chunk.detach().cpu().float().numpy() * 255).astype(np.uint8)
|
| 210 |
-
|
| 211 |
-
for frame in video_np_chunk:
|
| 212 |
-
writer.append_data(frame)
|
| 213 |
-
|
| 214 |
-
del latent_chunk, processed_chunk, pixel_tensor_chunk, video_np_chunk
|
| 215 |
-
gc.collect()
|
| 216 |
-
torch.cuda.empty_cache()
|
| 217 |
-
|
| 218 |
-
del processed_latents; gc.collect(); torch.cuda.empty_cache()
|
| 219 |
-
logger.info(f"Vídeo intermediário renderizado em: {intermediate_video_path}")
|
| 220 |
-
|
| 221 |
-
final_video_path = os.path.join(self.workspace_dir, f"{base_name}_FINAL.mp4")
|
| 222 |
|
| 223 |
if use_hd:
|
| 224 |
current_step += 1
|
| 225 |
progress(current_step / TOTAL_STEPS, desc="Masterização Final (HD)...")
|
| 226 |
try:
|
| 227 |
hd_specialist_singleton.process_video(
|
| 228 |
-
input_video_path=
|
| 229 |
-
output_video_path=
|
| 230 |
-
prompt=
|
| 231 |
)
|
| 232 |
except Exception as e:
|
| 233 |
logger.error(f"Falha na masterização HD: {e}. Usando vídeo de qualidade padrão.")
|
| 234 |
-
os.rename(intermediate_video_path, final_video_path)
|
| 235 |
else:
|
| 236 |
-
logger.info("Etapa de
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
if use_audio:
|
| 240 |
-
logger.warning("Geração de áudio solicitada, mas está desativada nesta versão do código.")
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
def refine_latents(self, latents: torch.Tensor, fps: int = 24, denoise_strength: float = 0.35, refine_steps: int = 12, motion_prompt: str = "...", **kwargs) -> torch.Tensor:
|
| 246 |
logger.info(f"Refinando tensor latente com shape {latents.shape}.")
|
| 247 |
_, _, num_latent_frames, latent_h, latent_w = latents.shape
|
|
@@ -269,13 +310,17 @@ class Deformes4DEngine:
|
|
| 269 |
return upscaler_specialist_singleton.upscale(latents)
|
| 270 |
|
| 271 |
def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
|
| 272 |
-
|
| 273 |
-
**ltx_params, 'width': target_resolution[
|
| 274 |
'video_total_frames': total_frames_to_generate, 'video_fps': 24,
|
| 275 |
'current_fragment_index': int(time.time()), 'conditioning_items_data': conditioning_items
|
| 276 |
}
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
| 278 |
|
|
|
|
| 279 |
def _quantize_to_multiple(self, n, m):
|
| 280 |
if m == 0: return n
|
| 281 |
quantized = int(round(n / m) * m)
|
|
|
|
| 27 |
from hd_specialist import hd_specialist_singleton
|
| 28 |
from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
|
| 29 |
from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
|
| 30 |
+
from audio_specialist import audio_specialist_singleton
|
| 31 |
|
| 32 |
logger = logging.getLogger(__name__)
|
| 33 |
|
|
|
|
| 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 |
+
|
| 84 |
# --- NÚCLEO DA LÓGICA ADUC-SDR ---
|
| 85 |
+
def generate_full_movie_old(self, keyframes: list, global_prompt: str, storyboard: list,
|
| 86 |
seconds_per_fragment: float, trim_percent: int,
|
| 87 |
handler_strength: float, destination_convergence_strength: float,
|
| 88 |
use_upscaler: bool, use_refiner: bool, use_hd: bool, use_audio: bool,
|
| 89 |
video_resolution: int, use_continuity_director: bool,
|
| 90 |
progress: gr.Progress = gr.Progress()):
|
| 91 |
|
| 92 |
+
# 1. Definição dos Parâmetros da Geração com base na Tese
|
|
|
|
|
|
|
|
|
|
| 93 |
FPS = 24
|
| 94 |
FRAMES_PER_LATENT_CHUNK = 8
|
| 95 |
ECO_LATENT_CHUNKS = 2
|
| 96 |
|
| 97 |
total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
|
| 98 |
+
total_latents_brutos = total_frames_brutos // FRAMES_PER_LATENT_CHUNK
|
| 99 |
+
|
| 100 |
frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
|
| 101 |
latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK
|
| 102 |
|
| 103 |
+
if total_latents_brutos <= latents_a_podar:
|
| 104 |
+
raise gr.Error(f"A porcentagem de poda ({trim_percent}%) é muito alta. Reduza-a ou aumente a duração.")
|
| 105 |
+
|
| 106 |
+
DEJAVU_FRAME_TARGET = frames_a_podar - 1
|
| 107 |
DESTINATION_FRAME_TARGET = total_frames_brutos - 1
|
| 108 |
|
| 109 |
+
logger.info("--- CONFIGURAÇÃO DA GERAÇÃO ADUC-SDR ---")
|
| 110 |
+
logger.info(f"Total de Latents por Geração Exploratória (V_bruto): {total_latents_brutos} ({total_frames_brutos} frames)")
|
| 111 |
+
logger.info(f"Latents a serem descartados (Poda Causal): {latents_a_podar} ({frames_a_podar} frames)")
|
| 112 |
+
logger.info(f"Chunks Latentes do Eco Causal (C): {ECO_LATENT_CHUNKS}")
|
| 113 |
+
logger.info(f"Frame alvo do Déjà-Vu (D): {DEJAVU_FRAME_TARGET}")
|
| 114 |
+
logger.info(f"Frame alvo do Destino (K): {DESTINATION_FRAME_TARGET}")
|
| 115 |
+
logger.info("------------------------------------------")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
# 2. Inicialização do Estado
|
| 118 |
+
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}
|
| 119 |
+
keyframe_paths = [item[0] if isinstance(item, tuple) else item for item in keyframes]
|
| 120 |
+
video_clips_paths, story_history = [], ""
|
| 121 |
+
target_resolution_tuple = (video_resolution, video_resolution)
|
| 122 |
+
|
| 123 |
eco_latent_for_next_loop = None
|
| 124 |
dejavu_latent_for_next_loop = None
|
| 125 |
+
|
| 126 |
+
latent_fragments[]
|
| 127 |
+
|
| 128 |
+
if len(keyframe_paths) < 2:
|
| 129 |
+
raise gr.Error(f"A geração requer no mínimo 2 keyframes. Você forneceu {len(keyframe_paths)}.")
|
| 130 |
+
|
| 131 |
+
num_transitions_to_generate = len(keyframe_paths) - 1
|
| 132 |
+
|
| 133 |
+
# 3. Loop Principal de Geração de Fragmentos
|
| 134 |
for i in range(num_transitions_to_generate):
|
| 135 |
fragment_index = i + 1
|
| 136 |
+
logger.info(f"--- INICIANDO FRAGMENTO {fragment_index}/{num_transitions_to_generate} ---")
|
| 137 |
+
progress(fragment_index / num_transitions_to_generate, desc=f"Produzindo Transição {fragment_index}/{num_transitions_to_generate}")
|
| 138 |
|
| 139 |
+
# 3.1. Consulta ao Maestro (Γ) para obter a intenção (Pᵢ)
|
| 140 |
past_keyframe_path = keyframe_paths[i - 1] if i > 0 else keyframe_paths[i]
|
| 141 |
start_keyframe_path = keyframe_paths[i]
|
| 142 |
destination_keyframe_path = keyframe_paths[i + 1]
|
| 143 |
future_story_prompt = storyboard[i + 1] if (i + 1) < len(storyboard) else "A cena final."
|
| 144 |
+
|
| 145 |
decision = gemini_singleton.get_cinematic_decision(
|
| 146 |
global_prompt, story_history, past_keyframe_path, start_keyframe_path, destination_keyframe_path,
|
| 147 |
+
storyboard[i - 1] if i > 0 else "O início.", storyboard[i], future_story_prompt
|
| 148 |
+
)
|
| 149 |
transition_type, motion_prompt = decision["transition_type"], decision["motion_prompt"]
|
| 150 |
story_history += f"\n- Ato {fragment_index}: {motion_prompt}"
|
| 151 |
|
| 152 |
+
# 3.2. Montagem das Âncoras para a Fórmula Canônica Ψ({C, D, K}, P)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
conditioning_items = []
|
| 154 |
+
logger.info(" [Ψ.1] Montando âncoras causais...")
|
| 155 |
+
|
| 156 |
if eco_latent_for_next_loop is None:
|
| 157 |
+
logger.info(" - Primeiro fragmento: Usando Keyframe inicial como âncora de partida.")
|
| 158 |
img_start = self._preprocess_image_for_latent_conversion(Image.open(start_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 159 |
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_start), 0, 1.0))
|
| 160 |
else:
|
| 161 |
+
logger.info(" - Âncora 1: Eco Causal (C) - Herança do passado.")
|
| 162 |
conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
|
| 163 |
+
logger.info(" - Âncora 2: Déjà-Vu (D) - Memória de um futuro idealizado.")
|
| 164 |
conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
|
| 165 |
+
|
| 166 |
+
logger.info(" - Âncora 3: Destino (K) - Âncora geométrica/narrativa.")
|
| 167 |
img_dest = self._preprocess_image_for_latent_conversion(Image.open(destination_keyframe_path).convert("RGB"), target_resolution_tuple)
|
| 168 |
conditioning_items.append(LatentConditioningItem(self.pil_to_latent(img_dest), DESTINATION_FRAME_TARGET, destination_convergence_strength))
|
| 169 |
+
|
| 170 |
+
# 3.3. Execução da Câmera (Ψ): Geração Exploratória para criar V_bruto
|
| 171 |
+
logger.info(f" [Ψ.2] Câmera (Ψ) executando a geração exploratória de {total_latents_brutos} chunks latentes...")
|
| 172 |
current_ltx_params = {**base_ltx_params, "motion_prompt": motion_prompt}
|
| 173 |
+
latents_brutos = self._generate_latent_tensor_internal(conditioning_items, current_ltx_params, target_resolution_tuple, total_frames_brutos)
|
| 174 |
+
logger.info(f" - Geração concluída. Tensor latente bruto (V_bruto) criado com shape: {latents_brutos.shape}.")
|
| 175 |
+
|
| 176 |
+
# 3.4. Execução do Destilador (Δ): Implementação do Ciclo de Poda Causal (com workaround empírico)
|
| 177 |
+
logger.info(f" [Δ] Destilador (Δ) executando o Ciclo de Poda Causal...")
|
| 178 |
+
|
| 179 |
last_trim = latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
|
| 180 |
+
eco_latent_for_next_loop = last_trim[:, :, :2, :, :].clone()
|
| 181 |
dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
|
| 182 |
+
|
| 183 |
latents_video = latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
|
| 184 |
latents_video = latents_video[:, :, 1:, :, :]
|
| 185 |
|
| 186 |
+
logger.info(f" [Δ] latents_video {latents_video.shape}")
|
| 187 |
+
logger.info(f" - (Δ.1) Déjà-Vu (D) destilado. Shape: {dejavu_latent_for_next_loop.shape}")
|
| 188 |
+
logger.info(f" - (Δ.2) Eco Causal (C) extraído. Shape: {eco_latent_for_next_loop.shape}")
|
| 189 |
+
|
| 190 |
if transition_type == "cut":
|
| 191 |
+
logger.warning(" - DECISÃO DO MAESTRO: Corte ('cut'). Resetando a memória causal (Eco e Déjà-Vu).")
|
| 192 |
+
eco_latent_for_next_loop = None
|
| 193 |
+
dejavu_latent_for_next_loop = None
|
| 194 |
|
| 195 |
+
if use_upscaler:
|
| 196 |
+
latents_video = self.upscale_latents(latents_video)
|
| 197 |
+
|
| 198 |
+
latent_fragments.append(latents_video)
|
| 199 |
|
|
|
|
| 200 |
current_step += 1
|
| 201 |
progress(current_step / TOTAL_STEPS, desc="Unificação Causal (Concatenação)...")
|
| 202 |
+
|
| 203 |
+
logger.info("--- CONCATENANDO TODOS OS FRAGMENTOS LATENTES ---")
|
| 204 |
+
tensors_para_concatenar = []
|
| 205 |
+
for idx, tensor_frag in enumerate(latent_fragments):
|
| 206 |
+
# Move cada tensor para o dispositivo de destino antes de adicioná-lo à lista.
|
| 207 |
+
target_device = self.device
|
| 208 |
+
tensor_on_target_device = tensor_frag.to(target_device)
|
| 209 |
+
if idx < len(latent_fragments) - 1:
|
| 210 |
+
tensors_para_concatenar.append(tensor_on_target_device[:, :, :-1, :, :])
|
| 211 |
+
else:
|
| 212 |
+
tensors_para_concatenar.append(tensor_on_target_device)
|
| 213 |
|
| 214 |
+
processed_latents = torch.cat(tensors_para_concatenar, dim=2)
|
| 215 |
+
logger.info(f"Concatenação concluída. Shape final do tensor latente: {final_concatenated_latents.shape}")
|
| 216 |
+
|
| 217 |
if use_refiner:
|
| 218 |
current_step += 1
|
| 219 |
progress(current_step / TOTAL_STEPS, desc="Polimento Global (Denoise)...")
|
|
|
|
| 226 |
else:
|
| 227 |
logger.info("Etapa de refinamento desativada.")
|
| 228 |
|
| 229 |
+
|
| 230 |
base_name = f"movie_{int(time.time())}"
|
| 231 |
current_step += 1
|
| 232 |
progress(current_step / TOTAL_STEPS, desc="Renderização (em lotes)...")
|
| 233 |
+
|
| 234 |
+
if use_audio:
|
| 235 |
+
video_path = self._generate_video_and_audio_from_latents(processed_latents, global_prompt, base_name)
|
| 236 |
+
else:
|
| 237 |
+
video_path = os.path.join(self.workspace_dir, f"{base_name}_silent.mp4")
|
| 238 |
+
logger.info("Etapa de sonoplastia desativada.")
|
| 239 |
+
pixel_tensor = self.latents_to_pixels(processed_latents)
|
| 240 |
+
self.save_video_from_tensor(pixel_tensor, video_path, fps=24)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
if use_hd:
|
| 243 |
current_step += 1
|
| 244 |
progress(current_step / TOTAL_STEPS, desc="Masterização Final (HD)...")
|
| 245 |
try:
|
| 246 |
hd_specialist_singleton.process_video(
|
| 247 |
+
input_video_path=video_path,
|
| 248 |
+
output_video_path=video_path,
|
| 249 |
+
prompt=" "
|
| 250 |
)
|
| 251 |
except Exception as e:
|
| 252 |
logger.error(f"Falha na masterização HD: {e}. Usando vídeo de qualidade padrão.")
|
|
|
|
| 253 |
else:
|
| 254 |
+
logger.info("Etapa de edicao HD desativada.")
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
logger.info(f"Processo concluído! Vídeo final salvo em: {video_path}")
|
| 258 |
+
yield {"final_path": video_path}
|
| 259 |
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
def _generate_video_and_audio_from_latents(self, latent_tensor, audio_prompt, base_name):
|
| 262 |
+
silent_video_path = os.path.join(self.workspace_dir, f"{base_name}_silent.mp4")
|
| 263 |
+
pixel_tensor = self.latents_to_pixels(latent_tensor)
|
| 264 |
+
self.save_video_from_tensor(pixel_tensor, silent_video_path, fps=24)
|
| 265 |
+
del pixel_tensor; gc.collect()
|
| 266 |
+
|
| 267 |
+
try:
|
| 268 |
+
result = subprocess.run(
|
| 269 |
+
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", silent_video_path],
|
| 270 |
+
capture_output=True, text=True, check=True)
|
| 271 |
+
frag_duration = float(result.stdout.strip())
|
| 272 |
+
except (subprocess.CalledProcessError, ValueError, FileNotFoundError):
|
| 273 |
+
logger.warning(f"ffprobe falhou em {os.path.basename(silent_video_path)}. Calculando duração manualmente.")
|
| 274 |
+
num_pixel_frames = latent_tensor.shape[2] * 8
|
| 275 |
+
frag_duration = num_pixel_frames / 24.0
|
| 276 |
|
| 277 |
+
video_with_audio_path = audio_specialist_singleton.generate_audio_for_video(
|
| 278 |
+
video_path=silent_video_path, prompt=audio_prompt,
|
| 279 |
+
duration_seconds=frag_duration)
|
| 280 |
+
|
| 281 |
+
if os.path.exists(silent_video_path):
|
| 282 |
+
os.remove(silent_video_path)
|
| 283 |
+
return video_with_audio_path
|
| 284 |
+
|
| 285 |
+
|
| 286 |
def refine_latents(self, latents: torch.Tensor, fps: int = 24, denoise_strength: float = 0.35, refine_steps: int = 12, motion_prompt: str = "...", **kwargs) -> torch.Tensor:
|
| 287 |
logger.info(f"Refinando tensor latente com shape {latents.shape}.")
|
| 288 |
_, _, num_latent_frames, latent_h, latent_w = latents.shape
|
|
|
|
| 310 |
return upscaler_specialist_singleton.upscale(latents)
|
| 311 |
|
| 312 |
def _generate_latent_tensor_internal(self, conditioning_items, ltx_params, target_resolution, total_frames_to_generate):
|
| 313 |
+
final_ltx_params = {
|
| 314 |
+
**ltx_params, 'width': target_resolution[0], 'height': target_resolution[1],
|
| 315 |
'video_total_frames': total_frames_to_generate, 'video_fps': 24,
|
| 316 |
'current_fragment_index': int(time.time()), 'conditioning_items_data': conditioning_items
|
| 317 |
}
|
| 318 |
+
new_full_latents, _ = self.ltx_manager.generate_latent_fragment(**final_ltx_params)
|
| 319 |
+
gc.collect()
|
| 320 |
+
torch.cuda.empty_cache()
|
| 321 |
+
return new_full_latents
|
| 322 |
|
| 323 |
+
|
| 324 |
def _quantize_to_multiple(self, n, m):
|
| 325 |
if m == 0: return n
|
| 326 |
quantized = int(round(n / m) * m)
|