euiiiia commited on
Commit
f752c5c
·
verified ·
1 Parent(s): 6b637f7

Update api/ltx_server_refactored.py

Browse files
Files changed (1) hide show
  1. api/ltx_server_refactored.py +392 -278
api/ltx_server_refactored.py CHANGED
@@ -1,68 +1,96 @@
1
- # ltx_server_refactored.py — VideoService (Modular Version with Simple Overlap Chunking)
2
 
3
- # --- 0. WARNINGS E AMBIENTE ---
 
 
 
 
 
 
 
 
 
 
4
  import warnings
 
 
 
 
 
 
 
5
  warnings.filterwarnings("ignore", category=UserWarning)
6
  warnings.filterwarnings("ignore", category=FutureWarning)
7
- warnings.filterwarnings("ignore", message=".*")
8
- from huggingface_hub import logging
9
- logging.set_verbosity_error()
10
- logging.set_verbosity_warning()
11
- logging.set_verbosity_info()
12
- logging.set_verbosity_debug()
13
- LTXV_DEBUG=1
14
- LTXV_FRAME_LOG_EVERY=8
15
- import os, subprocess, shlex, tempfile
16
  import torch
17
- import json
18
  import numpy as np
19
- import random
20
- import os
21
- import shlex
22
- import yaml
23
- from typing import List, Dict
24
- from pathlib import Path
25
- import imageio
26
  from PIL import Image
27
- import tempfile
28
- from huggingface_hub import hf_hub_download
29
- import sys
30
- import subprocess
31
- import gc
32
- import shutil
33
- import contextlib
34
- import time
35
- import traceback
36
  from einops import rearrange
37
- import torch.nn.functional as F
38
- from managers.vae_manager import vae_manager_singleton
39
- from tools.video_encode_tool import video_encode_tool_singleton
 
 
40
  DEPS_DIR = Path("/data")
41
  LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
 
 
42
 
43
- # (Todas as funções de setup, helpers e inicialização da classe permanecem inalteradas)
44
- # ... (run_setup, add_deps_to_path, _query_gpu_processes_via_nvml, etc.)
45
- def run_setup():
 
 
 
46
  setup_script_path = "setup.py"
47
  if not os.path.exists(setup_script_path):
48
  print("[DEBUG] 'setup.py' não encontrado. Pulando clonagem de dependências.")
49
  return
 
 
50
  try:
51
- print("[DEBUG] Executando setup.py para dependências...")
52
- subprocess.run([sys.executable, setup_script_path], check=True)
53
- print("[DEBUG] Setup concluído com sucesso.")
54
  except subprocess.CalledProcessError as e:
55
- print(f"[DEBUG] ERRO no setup.py (code {e.returncode}). Abortando.")
56
  sys.exit(1)
 
 
 
 
 
 
 
 
 
 
57
  if not LTX_VIDEO_REPO_DIR.exists():
58
- print(f"[DEBUG] Repositório não encontrado em {LTX_VIDEO_REPO_DIR}. Rodando setup...")
59
- run_setup()
60
- def add_deps_to_path():
61
- repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
62
- if str(LTX_VIDEO_REPO_DIR.resolve()) not in sys.path:
63
- sys.path.insert(0, repo_path)
64
- print(f"[DEBUG] Repo adicionado ao sys.path: {repo_path}")
65
- def calculate_padding(orig_h, orig_w, target_h, target_w):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  pad_h = target_h - orig_h
67
  pad_w = target_w - orig_w
68
  pad_top = pad_h // 2
@@ -70,298 +98,384 @@ def calculate_padding(orig_h, orig_w, target_h, target_w):
70
  pad_left = pad_w // 2
71
  pad_right = pad_w - pad_left
72
  return (pad_left, pad_right, pad_top, pad_bottom)
73
- def log_tensor_info(tensor, name="Tensor"):
 
 
74
  if not isinstance(tensor, torch.Tensor):
75
- print(f"\n[INFO] '{name}' não é tensor.")
76
  return
77
- print(f"\n--- Tensor: {name} ---")
78
- print(f" - Shape: {tuple(tensor.shape)}")
79
- print(f" - Dtype: {tensor.dtype}")
80
  print(f" - Device: {tensor.device}")
81
  if tensor.numel() > 0:
82
  try:
83
- print(f" - Min: {tensor.min().item():.4f} Max: {tensor.max().item():.4f} Mean: {tensor.mean().item():.4f}")
84
- except Exception:
85
- pass
86
- print("------------------------------------------\n")
87
 
88
- add_deps_to_path()
89
- from ltx_video.pipelines.pipeline_ltx_video import ConditioningItem, LTXMultiScalePipeline
90
- from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
91
- from ltx_video.models.autoencoders.vae_encode import un_normalize_latents, normalize_latents
92
- from ltx_video.pipelines.pipeline_ltx_video import adain_filter_latent
93
- from api.ltx.inference import (
94
- create_ltx_video_pipeline,
95
- create_latent_upsampler,
96
- load_image_to_tensor_with_resize_and_crop,
97
- seed_everething,
98
- )
99
 
100
  class VideoService:
 
 
 
 
 
101
  def __init__(self):
 
102
  t0 = time.perf_counter()
103
- print("[DEBUG] Inicializando VideoService...")
104
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
105
- self.config = self._load_config()
106
- self.pipeline, self.latent_upsampler = self._load_models()
107
- self.pipeline.to(self.device)
108
- if self.latent_upsampler:
109
- self.latent_upsampler.to(self.device)
110
- self._apply_precision_policy()
111
  vae_manager_singleton.attach_pipeline(
112
  self.pipeline,
113
  device=self.device,
114
  autocast_dtype=self.runtime_autocast_dtype
115
  )
116
  self._tmp_dirs = set()
117
- print(f"[DEBUG] VideoService pronto. boot_time={time.perf_counter()-t0:.3f}s")
 
118
 
119
- def _load_config(self):
120
- base = LTX_VIDEO_REPO_DIR / "configs"
121
- config_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
122
- with open(config_path, "r") as file:
123
- return yaml.safe_load(file)
124
 
125
- def finalize(self, keep_paths=None, extra_paths=None, clear_gpu=True):
126
- print("[DEBUG] Finalize: iniciando limpeza...")
127
- keep = set(keep_paths or []); extras = set(extra_paths or [])
128
- gc.collect()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  try:
130
- if clear_gpu and torch.cuda.is_available():
131
- torch.cuda.empty_cache()
132
- try:
133
- torch.cuda.ipc_collect()
134
- except Exception:
135
- pass
 
 
 
 
 
 
 
 
 
 
 
 
136
  except Exception as e:
137
- print(f"[DEBUG] Finalize: limpeza GPU falhou: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  try:
139
- self._log_gpu_memory("Após finalize")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  except Exception as e:
141
- print(f"[DEBUG] Log GPU pós-finalize falhou: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- def _load_models(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  t0 = time.perf_counter()
145
  LTX_REPO = "Lightricks/LTX-Video"
146
- print("[DEBUG] Baixando checkpoint principal...")
147
- distilled_model_path = hf_hub_download(
148
- repo_id=LTX_REPO,
149
- filename=self.config["checkpoint_path"],
150
- local_dir=os.getenv("HF_HOME"),
151
- cache_dir=os.getenv("HF_HOME_CACHE"),
152
- token=os.getenv("HF_TOKEN"),
153
- )
154
- self.config["checkpoint_path"] = distilled_model_path
155
- print(f"[DEBUG] Checkpoint em: {distilled_model_path}")
156
-
157
- print("[DEBUG] Baixando upscaler espacial...")
158
- spatial_upscaler_path = hf_hub_download(
159
- repo_id=LTX_REPO,
160
- filename=self.config["spatial_upscaler_model_path"],
161
- local_dir=os.getenv("HF_HOME"),
162
- cache_dir=os.getenv("HF_HOME_CACHE"),
163
  token=os.getenv("HF_TOKEN")
164
  )
165
- self.config["spatial_upscaler_model_path"] = spatial_upscaler_path
166
- print(f"[DEBUG] Upscaler em: {spatial_upscaler_path}")
167
 
168
- print("[DEBUG] Construindo pipeline...")
169
  pipeline = create_ltx_video_pipeline(
170
  ckpt_path=self.config["checkpoint_path"],
171
  precision=self.config["precision"],
172
  text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
173
  sampler=self.config["sampler"],
174
- device="cpu",
175
- enhance_prompt=False,
176
- prompt_enhancer_image_caption_model_name_or_path=self.config["prompt_enhancer_image_caption_model_name_or_path"],
177
- prompt_enhancer_llm_model_name_or_path=self.config["prompt_enhancer_llm_model_name_or_path"],
178
  )
179
- print("[DEBUG] Pipeline pronto.")
180
 
181
  latent_upsampler = None
182
  if self.config.get("spatial_upscaler_model_path"):
183
- print("[DEBUG] Construindo latent_upsampler...")
 
 
 
 
 
 
 
184
  latent_upsampler = create_latent_upsampler(self.config["spatial_upscaler_model_path"], device="cpu")
185
- print("[DEBUG] Upsampler pronto.")
186
- print(f"[DEBUG] _load_models() tempo total={time.perf_counter()-t0:.3f}s")
 
187
  return pipeline, latent_upsampler
 
 
 
 
 
 
 
188
 
189
- def _apply_precision_policy(self):
 
190
  prec = str(self.config.get("precision", "")).lower()
191
- self.runtime_autocast_dtype = torch.float32
192
  if prec in ["float8_e4m3fn", "bfloat16"]:
193
- self.runtime_autocast_dtype = torch.bfloat16
194
  elif prec == "mixed_precision":
195
- self.runtime_autocast_dtype = torch.float16
196
-
197
- def _register_tmp_dir(self, d: str):
198
- if d and os.path.isdir(d):
199
- self._tmp_dirs.add(d); print(f"[DEBUG] Registrado tmp dir: {d}")
200
 
201
  @torch.no_grad()
202
- def _upsample_latents_internal(self, latents: torch.Tensor) -> torch.Tensor:
203
- try:
204
- if not self.latent_upsampler:
205
- raise ValueError("Latent Upsampler não está carregado.")
206
- latents_unnormalized = un_normalize_latents(latents, self.pipeline.vae, vae_per_channel_normalize=True)
207
- upsampled_latents = self.latent_upsampler(latents_unnormalized)
208
- return normalize_latents(upsampled_latents, self.pipeline.vae, vae_per_channel_normalize=True)
209
- except Exception as e:
210
- pass
211
- finally:
212
- torch.cuda.empty_cache()
213
- torch.cuda.ipc_collect()
214
- self.finalize(keep_paths=[])
215
 
216
- def _prepare_conditioning_tensor(self, filepath, height, width, padding_values):
 
217
  tensor = load_image_to_tensor_with_resize_and_crop(filepath, height, width)
218
- tensor = torch.nn.functional.pad(tensor, padding_values)
219
  return tensor.to(self.device, dtype=self.runtime_autocast_dtype)
220
 
221
-
222
- def _save_and_log_video(self, pixel_tensor, base_filename, fps, temp_dir, results_dir, used_seed, progress_callback=None):
223
- output_path = os.path.join(temp_dir, f"{base_filename}_{used_seed}.mp4")
224
- video_encode_tool_singleton.save_video_from_tensor(
225
- pixel_tensor, output_path, fps=fps, progress_callback=progress_callback
226
- )
227
- final_path = os.path.join(results_dir, f"{base_filename}_{used_seed}.mp4")
228
- shutil.move(output_path, final_path)
229
- print(f"[DEBUG] Vídeo salvo em: {final_path}")
230
- return final_path
231
-
232
- # ==============================================================================
233
- # --- FUNÇÕES MODULARES COM A LÓGICA DE CHUNKING SIMPLIFICADA ---
234
- # ==============================================================================
235
-
236
- def prepare_condition_items(self, items_list: List, height: int, width: int, num_frames: int):
237
- if not items_list: return []
238
  height_padded = ((height - 1) // 8 + 1) * 8
239
  width_padded = ((width - 1) // 8 + 1) * 8
240
- padding_values = calculate_padding(height, width, height_padded, width_padded)
241
- conditioning_items = []
242
- for media, frame, weight in items_list:
243
- tensor = self._prepare_conditioning_tensor(media, height, width, padding_values) if isinstance(media, str) else media.to(self.device, dtype=self.runtime_autocast_dtype)
244
- safe_frame = max(0, min(int(frame), num_frames - 1))
245
- conditioning_items.append(ConditioningItem(tensor, safe_frame, float(weight)))
246
- return conditioning_items
247
-
248
- def generate_low(self, prompt, negative_prompt, height, width, duration, guidance_scale, seed, conditioning_items=None):
249
- used_seed = random.randint(0, 2**32 - 1) if seed is None else int(seed)
250
- seed_everething(used_seed)
251
- FPS = 24.0
252
- actual_num_frames = max(9, int(round((round(duration * FPS) - 1) / 8.0) * 8 + 1))
253
- height_padded = ((height - 1) // 8 + 1) * 8
254
- width_padded = ((width - 1) // 8 + 1) * 8
255
- temp_dir = tempfile.mkdtemp(prefix="ltxv_low_"); self._register_tmp_dir(temp_dir)
256
- results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)
257
  downscale_factor = self.config.get("downscale_factor", 0.6666666)
258
  vae_scale_factor = self.pipeline.vae_scale_factor
259
- x_width = int(width_padded * downscale_factor)
260
- downscaled_width = x_width - (x_width % vae_scale_factor)
261
- x_height = int(height_padded * downscale_factor)
262
- downscaled_height = x_height - (x_height % vae_scale_factor)
263
- first_pass_kwargs = {
264
- "prompt": prompt, "negative_prompt": negative_prompt, "height": downscaled_height, "width": downscaled_width,
265
- "num_frames": actual_num_frames, "frame_rate": int(FPS), "generator": torch.Generator(device=self.device).manual_seed(used_seed),
266
- "output_type": "latent", "conditioning_items": conditioning_items, "guidance_scale": float(guidance_scale),
267
- **(self.config.get("first_pass", {}))
268
- }
269
- try:
270
- with torch.autocast(device_type="cuda", dtype=self.runtime_autocast_dtype, enabled=self.device == 'cuda'):
271
- latents = self.pipeline(**first_pass_kwargs).images
272
- pixel_tensor = vae_manager_singleton.decode(latents.clone(), decode_timestep=float(self.config.get("decode_timestep", 0.05)))
273
- video_path = self._save_and_log_video(pixel_tensor, "low_res_video", FPS, temp_dir, results_dir, used_seed)
274
- latents_cpu = latents.detach().to("cpu")
275
- tensor_path = os.path.join(results_dir, f"latents_low_res_{used_seed}.pt")
276
- torch.save(latents_cpu, tensor_path)
277
- return video_path, tensor_path, used_seed
278
 
279
- except Exception as e:
280
- pass
281
- finally:
282
- torch.cuda.empty_cache()
283
- torch.cuda.ipc_collect()
284
- self.finalize(keep_paths=[])
285
-
286
- def generate_upscale_denoise(self, latents_path, prompt, negative_prompt, guidance_scale, seed):
287
- used_seed = random.randint(0, 2**32 - 1) if seed is None else int(seed)
288
- seed_everething(used_seed)
289
- temp_dir = tempfile.mkdtemp(prefix="ltxv_up_"); self._register_tmp_dir(temp_dir)
290
- results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)
291
- latents_low = torch.load(latents_path).to(self.device)
292
- with torch.autocast(device_type="cuda", dtype=self.runtime_autocast_dtype, enabled=self.device == 'cuda'):
293
- upsampled_latents = self._upsample_latents_internal(latents_low)
294
- upsampled_latents = adain_filter_latent(latents=upsampled_latents, reference_latents=latents_low)
295
- del latents_low; torch.cuda.empty_cache()
296
-
297
- # --- LÓGICA DE DIVISÃO SIMPLES COM OVERLAP ---
298
- total_frames = upsampled_latents.shape[2]
299
- # Garante que mid_point seja pelo menos 1 para evitar um segundo chunk vazio se houver poucos frames
300
- mid_point = max(1, total_frames // 2)
301
- chunk1 = upsampled_latents[:, :, :mid_point, :, :]
302
- # O segundo chunk começa um frame antes para criar o overlap
303
- chunk2 = upsampled_latents[:, :, mid_point - 1:, :, :]
304
-
305
- final_latents_list = []
306
- for i, chunk in enumerate([chunk1, chunk2]):
307
- if chunk.shape[2] <= 1: continue # Pula chunks inválidos ou vazios
308
- second_pass_height = chunk.shape[3] * self.pipeline.vae_scale_factor
309
- second_pass_width = chunk.shape[4] * self.pipeline.vae_scale_factor
310
- second_pass_kwargs = {
311
- "prompt": prompt, "negative_prompt": negative_prompt, "height": second_pass_height, "width": second_pass_width,
312
- "num_frames": chunk.shape[2], "latents": chunk, "guidance_scale": float(guidance_scale),
313
- "output_type": "latent", "generator": torch.Generator(device=self.device).manual_seed(used_seed),
314
- **(self.config.get("second_pass", {}))
315
- }
316
- refined_chunk = self.pipeline(**second_pass_kwargs).images
317
- # Remove o overlap do primeiro chunk refinado antes de juntar
318
- if i == 0:
319
- final_latents_list.append(refined_chunk[:, :, :-1, :, :])
320
- else:
321
- final_latents_list.append(refined_chunk)
322
-
323
- final_latents = torch.cat(final_latents_list, dim=2)
324
- log_tensor_info(final_latents, "Latentes Upscaled/Refinados Finais")
325
-
326
- latents_cpu = final_latents.detach().to("cpu")
327
- tensor_path = os.path.join(results_dir, f"latents_refined_{used_seed}.pt")
328
- torch.save(latents_cpu, tensor_path)
329
- pixel_tensor = vae_manager_singleton.decode(final_latents, decode_timestep=float(self.config.get("decode_timestep", 0.05)))
330
- video_path = self._save_and_log_video(pixel_tensor, "refined_video", 24.0, temp_dir, results_dir, used_seed)
331
- return video_path, tensor_path
332
 
 
 
 
 
 
333
 
 
 
 
 
 
 
334
 
335
- def encode_mp4(self, latents_path: str, fps: int = 24):
336
- latents = torch.load(latents_path)
337
- seed = random.randint(0, 99999)
338
- temp_dir = tempfile.mkdtemp(prefix="ltxv_enc_"); self._register_tmp_dir(temp_dir)
339
- results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)
 
 
 
 
 
 
340
 
341
- # --- LÓGICA DE DIVISÃO SIMPLES COM OVERLAP ---
342
- total_frames = latents.shape[2]
343
- mid_point = max(1, total_frames // 2)
344
- chunk1_latents = latents[:, :, :mid_point, :, :]
345
- chunk2_latents = latents[:, :, mid_point - 1:, :, :]
346
 
347
- video_parts = []
348
- pixel_chunks_to_concat = []
349
- with torch.autocast(device_type="cuda", dtype=self.runtime_autocast_dtype, enabled=self.device == 'cuda'):
350
- for i, chunk in enumerate([chunk1_latents, chunk2_latents]):
351
- if chunk.shape[2] == 0: continue
352
- pixel_chunk = vae_manager_singleton.decode(chunk.to(self.device), decode_timestep=float(self.config.get("decode_timestep", 0.05)))
353
- # Remove o overlap do primeiro chunk de pixels
354
- if i == 0:
355
- pixel_chunks_to_concat.append(pixel_chunk[:, :, :-1, :, :])
356
- else:
357
- pixel_chunks_to_concat.append(pixel_chunk)
 
 
358
 
359
- final_pixel_tensor = torch.cat(pixel_chunks_to_concat, dim=2)
360
- final_video_path = self._save_and_log_video(final_pixel_tensor, f"final_concatenated_{seed}", fps, temp_dir, results_dir, seed)
361
- return final_video_path
 
362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
- # --- INSTANCIAÇÃO DO SERVIÇO ---
365
- print("Criando instância do VideoService. O carregamento do modelo começará agora...")
366
- video_generation_service = VideoService()
367
- print("Instância do VideoService pronta para uso.")
 
1
+ # ltx_server_clean_refactor.py — VideoService (Modular Version with Simple Overlap Chunking)
2
 
3
+ # ==============================================================================
4
+ # 0. CONFIGURAÇÃO DE AMBIENTE E IMPORTAÇÕES
5
+ # ==============================================================================
6
+ import os
7
+ import sys
8
+ import gc
9
+ import yaml
10
+ import time
11
+ import json
12
+ import random
13
+ import shutil
14
  import warnings
15
+ import tempfile
16
+ import traceback
17
+ import subprocess
18
+ from pathlib import Path
19
+ from typing import List, Dict, Optional, Tuple
20
+
21
+ # --- Configurações de Logging e Avisos ---
22
  warnings.filterwarnings("ignore", category=UserWarning)
23
  warnings.filterwarnings("ignore", category=FutureWarning)
24
+ from huggingface_hub import logging as hf_logging
25
+ hf_logging.set_verbosity_error()
26
+
27
+ # --- Importações de Bibliotecas de ML/Processamento ---
 
 
 
 
 
28
  import torch
29
+ import torch.nn.functional as F
30
  import numpy as np
 
 
 
 
 
 
 
31
  from PIL import Image
 
 
 
 
 
 
 
 
 
32
  from einops import rearrange
33
+ from huggingface_hub import hf_hub_download
34
+
35
+ # --- Constantes Globais ---
36
+ LTXV_DEBUG = True # Mude para False para desativar logs de debug
37
+ LTXV_FRAME_LOG_EVERY = 8
38
  DEPS_DIR = Path("/data")
39
  LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
40
+ RESULTS_DIR = Path("/app/output")
41
+ DEFAULT_FPS = 24.0
42
 
43
+ # ==============================================================================
44
+ # 1. SETUP E FUNÇÕES AUXILIARES DE AMBIENTE
45
+ # ==============================================================================
46
+
47
+ def _run_setup_script():
48
+ """Executa o script setup.py se o repositório LTX-Video não existir."""
49
  setup_script_path = "setup.py"
50
  if not os.path.exists(setup_script_path):
51
  print("[DEBUG] 'setup.py' não encontrado. Pulando clonagem de dependências.")
52
  return
53
+
54
+ print(f"[DEBUG] Repositório não encontrado em {LTX_VIDEO_REPO_DIR}. Executando setup.py...")
55
  try:
56
+ subprocess.run([sys.executable, setup_script_path], check=True, capture_output=True, text=True)
57
+ print("[DEBUG] Script 'setup.py' concluído com sucesso.")
 
58
  except subprocess.CalledProcessError as e:
59
+ print(f"[ERROR] Falha ao executar 'setup.py' (código {e.returncode}).\nOutput:\n{e.stdout}\n{e.stderr}")
60
  sys.exit(1)
61
+
62
+ def add_deps_to_path(repo_path: Path):
63
+ """Adiciona o diretório do repositório ao sys.path para importações locais."""
64
+ resolved_path = str(repo_path.resolve())
65
+ if resolved_path not in sys.path:
66
+ sys.path.insert(0, resolved_path)
67
+ if LTXV_DEBUG:
68
+ print(f"[DEBUG] Adicionado ao sys.path: {resolved_path}")
69
+
70
+ # --- Execução da configuração inicial ---
71
  if not LTX_VIDEO_REPO_DIR.exists():
72
+ _run_setup_script()
73
+ add_deps_to_path(LTX_VIDEO_REPO_DIR)
74
+
75
+ # --- Importações Dependentes do Path Adicionado ---
76
+ from ltx_video.pipelines.pipeline_ltx_video import ConditioningItem, LTXMultiScalePipeline
77
+ from ltx_video.models.autoencoders.vae_encode import un_normalize_latents, normalize_latents
78
+ from ltx_video.pipelines.pipeline_ltx_video import adain_filter_latent
79
+ from api.ltx.inference import (
80
+ create_ltx_video_pipeline,
81
+ create_latent_upsampler,
82
+ load_image_to_tensor_with_resize_and_crop,
83
+ seed_everything, # Renomeado para seguir convenção
84
+ )
85
+ from managers.vae_manager import vae_manager_singleton
86
+ from tools.video_encode_tool import video_encode_tool_singleton
87
+
88
+ # ==============================================================================
89
+ # 2. FUNÇÕES AUXILIARES DE PROCESSAMENTO
90
+ # ==============================================================================
91
+
92
+ def calculate_padding(orig_h: int, orig_w: int, target_h: int, target_w: int) -> Tuple[int, int, int, int]:
93
+ """Calcula o preenchimento para centralizar uma imagem em uma nova dimensão."""
94
  pad_h = target_h - orig_h
95
  pad_w = target_w - orig_w
96
  pad_top = pad_h // 2
 
98
  pad_left = pad_w // 2
99
  pad_right = pad_w - pad_left
100
  return (pad_left, pad_right, pad_top, pad_bottom)
101
+
102
+ def log_tensor_info(tensor: torch.Tensor, name: str = "Tensor"):
103
+ """Exibe informações detalhadas sobre um tensor para depuração."""
104
  if not isinstance(tensor, torch.Tensor):
105
+ print(f"\n[INFO] '{name}' não é um tensor.")
106
  return
107
+ print(f"\n--- Tensor Info: {name} ---")
108
+ print(f" - Shape: {tuple(tensor.shape)}")
109
+ print(f" - Dtype: {tensor.dtype}")
110
  print(f" - Device: {tensor.device}")
111
  if tensor.numel() > 0:
112
  try:
113
+ print(f" - Stats: Min={tensor.min().item():.4f}, Max={tensor.max().item():.4f}, Mean={tensor.mean().item():.4f}")
114
+ except RuntimeError:
115
+ print(" - Stats: Não foi possível calcular (ex: tensores bool).")
116
+ print("-" * 30)
117
 
118
+ # ==============================================================================
119
+ # 3. CLASSE PRINCIPAL DO SERVIÇO DE VÍDEO
120
+ # ==============================================================================
 
 
 
 
 
 
 
 
121
 
122
  class VideoService:
123
+ """
124
+ Serviço encapsulado para gerar vídeos usando a pipeline LTX-Video.
125
+ Gerencia o carregamento de modelos, pré-processamento, geração em múltiplos
126
+ passos (baixa resolução, upscale com denoise) e pós-processamento.
127
+ """
128
  def __init__(self):
129
+ """Inicializa o serviço, carregando configurações e modelos."""
130
  t0 = time.perf_counter()
131
+ print("[INFO] Inicializando VideoService...")
132
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
133
+ self.config = self._load_config("ltxv-13b-0.9.8-distilled-fp8.yaml")
134
+
135
+ self.pipeline, self.latent_upsampler = self._load_models_from_hub()
136
+ self._move_models_to_device()
137
+
138
+ self.runtime_autocast_dtype = self._get_precision_dtype()
139
  vae_manager_singleton.attach_pipeline(
140
  self.pipeline,
141
  device=self.device,
142
  autocast_dtype=self.runtime_autocast_dtype
143
  )
144
  self._tmp_dirs = set()
145
+ RESULTS_DIR.mkdir(exist_ok=True)
146
+ print(f"[INFO] VideoService pronto. Tempo de inicialização: {time.perf_counter()-t0:.2f}s")
147
 
148
+ # --------------------------------------------------------------------------
149
+ # --- Métodos Públicos (API do Serviço) ---
150
+ # --------------------------------------------------------------------------
 
 
151
 
152
+ def prepare_condition_items(self, items_list: List[Tuple], height: int, width: int, num_frames: int) -> List[ConditioningItem]:
153
+ """Prepara os tensores de condicionamento a partir de imagens ou tensores."""
154
+ if not items_list:
155
+ return []
156
+
157
+ height_padded = ((height - 1) // 8 + 1) * 8
158
+ width_padded = ((width - 1) // 8 + 1) * 8
159
+ padding_values = calculate_padding(height, width, height_padded, width_padded)
160
+
161
+ conditioning_items = []
162
+ for media, frame_idx, weight in items_list:
163
+ if isinstance(media, str):
164
+ tensor = self._prepare_conditioning_tensor_from_path(media, height, width, padding_values)
165
+ else: # Assume que é um tensor
166
+ tensor = media.to(self.device, dtype=self.runtime_autocast_dtype)
167
+
168
+ # Garante que o frame de condicionamento esteja dentro dos limites do vídeo
169
+ safe_frame_idx = max(0, min(int(frame_idx), num_frames - 1))
170
+ conditioning_items.append(ConditioningItem(tensor, safe_frame_idx, float(weight)))
171
+
172
+ return conditioning_items
173
+
174
+ def generate_low_resolution(self, prompt: str, negative_prompt: str, height: int, width: int, duration_secs: float, guidance_scale: float, seed: Optional[int] = None, conditioning_items: Optional[List[ConditioningItem]] = None) -> Tuple[str, str, int]:
175
+ """
176
+ Gera um vídeo de baixa resolução e retorna os caminhos para o vídeo e os latentes.
177
+ """
178
+ used_seed = random.randint(0, 2**32 - 1) if seed is None else int(seed)
179
+ seed_everything(used_seed)
180
+
181
+ actual_num_frames = max(9, int(round((round(duration_secs * DEFAULT_FPS) - 1) / 8.0) * 8 + 1))
182
+
183
+ downscaled_height, downscaled_width = self._calculate_downscaled_dims(height, width)
184
+
185
+ first_pass_kwargs = {
186
+ "prompt": prompt, "negative_prompt": negative_prompt, "height": downscaled_height,
187
+ "width": downscaled_width, "num_frames": actual_num_frames, "frame_rate": int(DEFAULT_FPS),
188
+ "generator": torch.Generator(device=self.device).manual_seed(used_seed),
189
+ "output_type": "latent", "conditioning_items": conditioning_items,
190
+ "guidance_scale": float(guidance_scale), **(self.config.get("first_pass", {}))
191
+ }
192
+
193
+ temp_dir = tempfile.mkdtemp(prefix="ltxv_low_")
194
+ self._register_tmp_dir(temp_dir)
195
+
196
  try:
197
+ with torch.autocast(device_type=self.device.split(':')[0], dtype=self.runtime_autocast_dtype, enabled=(self.device == 'cuda')):
198
+ latents = self.pipeline(**first_pass_kwargs).images
199
+ #pixel_tensor = vae_manager_singleton.decode(latents.clone(), decode_timestep=float(self.config.get("decode_timestep", 0.05)))
200
+ #video_path = self._save_video_from_tensor(pixel_tensor, "low_res_video", used_seed, temp_dir)
201
+ latents_path = self._save_latents_to_disk(latents, "latents_low_res", used_seed)
202
+
203
+ final_video_path, final_latents_path = self.generate_upscale_denoise(
204
+ latents_path=latents_path,
205
+ prompt=prompt,
206
+ negative_prompt=negative_prompt,
207
+ guidance_scale=guidance_scale,
208
+ seed=used_seed
209
+ )
210
+
211
+ print(f"[SUCCESS] PASSO 2 concluído. Vídeo final em: {final_video_path}")
212
+
213
+ return final_video_path, final_latents_path, used_seed
214
+
215
  except Exception as e:
216
+ print(f"[ERROR] Falha na geração de baixa resolução: {e}")
217
+ traceback.print_exc()
218
+ raise
219
+ finally:
220
+ self._finalize()
221
+
222
+ def generate_upscale_denoise(self, latents_path: str, prompt: str, negative_prompt: str, guidance_scale: float, seed: Optional[int] = None) -> Tuple[str, str]:
223
+ """
224
+ Aplica upscale, AdaIN e Denoise em latentes de baixa resolução usando um processo de chunking.
225
+ """
226
+ used_seed = random.randint(0, 2**32 - 1) if seed is None else int(seed)
227
+ seed_everything(used_seed)
228
+
229
+ temp_dir = tempfile.mkdtemp(prefix="ltxv_up_")
230
+ self._register_tmp_dir(temp_dir)
231
+
232
  try:
233
+ latents_low = torch.load(latents_path).to(self.device)
234
+ with torch.autocast(device_type=self.device.split(':')[0], dtype=self.runtime_autocast_dtype, enabled=(self.device == 'cuda')):
235
+ upsampled_latents = self._upsample_and_filter_latents(latents_low)
236
+ del latents_low; torch.cuda.empty_cache()
237
+
238
+ chunks = self._split_latents_with_overlap(upsampled_latents)
239
+ refined_chunks = []
240
+
241
+ for chunk in chunks:
242
+ if chunk.shape[2] <= 1: continue # Pula chunks inválidos
243
+
244
+ second_pass_height = chunk.shape[3] * self.pipeline.vae_scale_factor
245
+ second_pass_width = chunk.shape[4] * self.pipeline.vae_scale_factor
246
+
247
+ second_pass_kwargs = {
248
+ "prompt": prompt, "negative_prompt": negative_prompt, "height": second_pass_height,
249
+ "width": second_pass_width, "num_frames": chunk.shape[2], "latents": chunk,
250
+ "guidance_scale": float(guidance_scale), "output_type": "latent",
251
+ "generator": torch.Generator(device=self.device).manual_seed(used_seed),
252
+ **(self.config.get("second_pass", {}))
253
+ }
254
+ refined_chunk = self.pipeline(**second_pass_kwargs).images
255
+ refined_chunks.append(refined_chunk)
256
+
257
+ final_latents = self._merge_chunks_with_overlap(refined_chunks)
258
+ if LTXV_DEBUG:
259
+ log_tensor_info(final_latents, "Latentes Upscaled/Refinados Finais")
260
+
261
+ latents_path = self._save_latents_to_disk(final_latents, "latents_refined", used_seed)
262
+ pixel_tensor = vae_manager_singleton.decode(final_latents, decode_timestep=float(self.config.get("decode_timestep", 0.05)))
263
+ video_path = self._save_video_from_tensor(pixel_tensor, "refined_video", used_seed, temp_dir)
264
+
265
+ return video_path, latents_path
266
+
267
  except Exception as e:
268
+ print(f"[ERROR] Falha no processo de upscale e denoise: {e}")
269
+ traceback.print_exc()
270
+ raise
271
+ finally:
272
+ self._finalize()
273
+
274
+ def encode_latents_to_mp4(self, latents_path: str, fps: int = int(DEFAULT_FPS)) -> str:
275
+ """Decodifica um tensor de latentes salvo e o salva como um vídeo MP4."""
276
+ latents = torch.load(latents_path)
277
+ temp_dir = tempfile.mkdtemp(prefix="ltxv_enc_")
278
+ self._register_tmp_dir(temp_dir)
279
+ seed = random.randint(0, 99999) # Seed apenas para nome do arquivo
280
+
281
+ try:
282
+ chunks = self._split_latents_with_overlap(latents)
283
+ pixel_chunks = []
284
+
285
+ with torch.autocast(device_type=self.device.split(':')[0], dtype=self.runtime_autocast_dtype, enabled=(self.device == 'cuda')):
286
+ for chunk in chunks:
287
+ if chunk.shape[2] == 0: continue
288
+ pixel_chunk = vae_manager_singleton.decode(chunk.to(self.device), decode_timestep=float(self.config.get("decode_timestep", 0.05)))
289
+ pixel_chunks.append(pixel_chunk)
290
+
291
+ final_pixel_tensor = self._merge_chunks_with_overlap(pixel_chunks)
292
+ final_video_path = self._save_video_from_tensor(final_pixel_tensor, f"final_video_{seed}", seed, temp_dir, fps=fps)
293
+ return final_video_path
294
 
295
+ except Exception as e:
296
+ print(f"[ERROR] Falha ao encodar latentes para MP4: {e}")
297
+ traceback.print_exc()
298
+ raise
299
+ finally:
300
+ self._finalize()
301
+
302
+ # --------------------------------------------------------------------------
303
+ # --- Métodos Internos e Auxiliares ---
304
+ # --------------------------------------------------------------------------
305
+
306
+ def _finalize(self):
307
+ """Limpa a memória da GPU e os diretórios temporários."""
308
+ if LTXV_DEBUG:
309
+ print("[DEBUG] Finalize: iniciando limpeza...")
310
+
311
+ gc.collect()
312
+ if torch.cuda.is_available():
313
+ torch.cuda.empty_cache()
314
+ torch.cuda.ipc_collect()
315
+
316
+ # Limpa todos os diretórios temporários registrados
317
+ for d in list(self._tmp_dirs):
318
+ shutil.rmtree(d, ignore_errors=True)
319
+ self._tmp_dirs.remove(d)
320
+ if LTXV_DEBUG:
321
+ print(f"[DEBUG] Diretório temporário removido: {d}")
322
+
323
+ def _load_config(self, config_filename: str) -> Dict:
324
+ """Carrega o arquivo de configuração YAML."""
325
+ config_path = LTX_VIDEO_REPO_DIR / "configs" / config_filename
326
+ print(f"[INFO] Carregando configuração de: {config_path}")
327
+ with open(config_path, "r") as file:
328
+ return yaml.safe_load(file)
329
+
330
+ def _load_models_from_hub(self) -> Tuple[LTXMultiScalePipeline, Optional[torch.nn.Module]]:
331
+ """Baixa e cria as instâncias da pipeline e do upsampler."""
332
  t0 = time.perf_counter()
333
  LTX_REPO = "Lightricks/LTX-Video"
334
+
335
+ print("[INFO] Baixando checkpoint principal...")
336
+ self.config["checkpoint_path"] = hf_hub_download(
337
+ repo_id=LTX_REPO, filename=self.config["checkpoint_path"],
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  token=os.getenv("HF_TOKEN")
339
  )
340
+ print(f"[INFO] Checkpoint principal em: {self.config['checkpoint_path']}")
 
341
 
342
+ print("[INFO] Construindo pipeline...")
343
  pipeline = create_ltx_video_pipeline(
344
  ckpt_path=self.config["checkpoint_path"],
345
  precision=self.config["precision"],
346
  text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
347
  sampler=self.config["sampler"],
348
+ device="cpu", # Carrega em CPU primeiro
349
+ enhance_prompt=False
 
 
350
  )
351
+ print("[INFO] Pipeline construída.")
352
 
353
  latent_upsampler = None
354
  if self.config.get("spatial_upscaler_model_path"):
355
+ print("[INFO] Baixando upscaler espacial...")
356
+ self.config["spatial_upscaler_model_path"] = hf_hub_download(
357
+ repo_id=LTX_REPO, filename=self.config["spatial_upscaler_model_path"],
358
+ token=os.getenv("HF_TOKEN")
359
+ )
360
+ print(f"[INFO] Upscaler em: {self.config['spatial_upscaler_model_path']}")
361
+
362
+ print("[INFO] Construindo latent_upsampler...")
363
  latent_upsampler = create_latent_upsampler(self.config["spatial_upscaler_model_path"], device="cpu")
364
+ print("[INFO] Latent upsampler construído.")
365
+
366
+ print(f"[INFO] Carregamento de modelos concluído em {time.perf_counter()-t0:.2f}s")
367
  return pipeline, latent_upsampler
368
+
369
+ def _move_models_to_device(self):
370
+ """Move os modelos carregados para o dispositivo de computação (GPU/CPU)."""
371
+ print(f"[INFO] Movendo modelos para o dispositivo: {self.device}")
372
+ self.pipeline.to(self.device)
373
+ if self.latent_upsampler:
374
+ self.latent_upsampler.to(self.device)
375
 
376
+ def _get_precision_dtype(self) -> torch.dtype:
377
+ """Determina o dtype para autocast com base na configuração de precisão."""
378
  prec = str(self.config.get("precision", "")).lower()
 
379
  if prec in ["float8_e4m3fn", "bfloat16"]:
380
+ return torch.bfloat16
381
  elif prec == "mixed_precision":
382
+ return torch.float16
383
+ return torch.float32
 
 
 
384
 
385
  @torch.no_grad()
386
+ def _upsample_and_filter_latents(self, latents: torch.Tensor) -> torch.Tensor:
387
+ """Aplica o upsample espacial e o filtro AdaIN aos latentes."""
388
+ if not self.latent_upsampler:
389
+ raise ValueError("Latent Upsampler não está carregado para a operação de upscale.")
390
+
391
+ latents_unnormalized = un_normalize_latents(latents, self.pipeline.vae, vae_per_channel_normalize=True)
392
+ upsampled_latents_unnormalized = self.latent_upsampler(latents_unnormalized)
393
+ upsampled_latents_normalized = normalize_latents(upsampled_latents_unnormalized, self.pipeline.vae, vae_per_channel_normalize=True)
394
+
395
+ # Filtro AdaIN para manter consistência de cor/estilo com o vídeo de baixa resolução
396
+ return adain_filter_latent(latents=upsampled_latents_normalized, reference_latents=latents)
 
 
397
 
398
+ def _prepare_conditioning_tensor_from_path(self, filepath: str, height: int, width: int, padding: Tuple) -> torch.Tensor:
399
+ """Carrega uma imagem, redimensiona, aplica padding e move para o dispositivo."""
400
  tensor = load_image_to_tensor_with_resize_and_crop(filepath, height, width)
401
+ tensor = F.pad(tensor, padding)
402
  return tensor.to(self.device, dtype=self.runtime_autocast_dtype)
403
 
404
+ def _calculate_downscaled_dims(self, height: int, width: int) -> Tuple[int, int]:
405
+ """Calcula as dimensões para o primeiro passo (baixa resolução)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  height_padded = ((height - 1) // 8 + 1) * 8
407
  width_padded = ((width - 1) // 8 + 1) * 8
408
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
  downscale_factor = self.config.get("downscale_factor", 0.6666666)
410
  vae_scale_factor = self.pipeline.vae_scale_factor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
 
412
+ target_w = int(width_padded * downscale_factor)
413
+ downscaled_width = target_w - (target_w % vae_scale_factor)
414
+
415
+ target_h = int(height_padded * downscale_factor)
416
+ downscaled_height = target_h - (target_h % vae_scale_factor)
417
+
418
+ return downscaled_height, downscaled_width
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
 
420
+ def _split_latents_with_overlap(self, latents: torch.Tensor, overlap: int = 1) -> List[torch.Tensor]:
421
+ """Divide um tensor de latentes em dois chunks com sobreposição."""
422
+ total_frames = latents.shape[2]
423
+ if total_frames <= overlap:
424
+ return [latents]
425
 
426
+ mid_point = max(overlap, total_frames // 2)
427
+ chunk1 = latents[:, :, :mid_point, :, :]
428
+ # O segundo chunk começa 'overlap' frames antes para criar a sobreposição
429
+ chunk2 = latents[:, :, mid_point - overlap:, :, :]
430
+
431
+ return [c for c in [chunk1, chunk2] if c.shape[2] > 0]
432
 
433
+ def _merge_chunks_with_overlap(self, chunks: List[torch.Tensor], overlap: int = 1) -> torch.Tensor:
434
+ """Junta uma lista de chunks, removendo a sobreposição."""
435
+ if not chunks:
436
+ return torch.empty(0)
437
+ if len(chunks) == 1:
438
+ return chunks[0]
439
+
440
+ # Pega o primeiro chunk sem o frame de sobreposição final
441
+ merged_list = [chunks[0][:, :, :-overlap, :, :]]
442
+ # Adiciona os chunks restantes
443
+ merged_list.extend(chunks[1:])
444
 
445
+ return torch.cat(merged_list, dim=2)
 
 
 
 
446
 
447
+ def _save_latents_to_disk(self, latents_tensor: torch.Tensor, base_filename: str, seed: int) -> str:
448
+ """Salva um tensor de latentes em um arquivo .pt."""
449
+ latents_cpu = latents_tensor.detach().to("cpu")
450
+ tensor_path = RESULTS_DIR / f"{base_filename}_{seed}.pt"
451
+ torch.save(latents_cpu, tensor_path)
452
+ if LTXV_DEBUG:
453
+ print(f"[DEBUG] Latentes salvos em: {tensor_path}")
454
+ return str(tensor_path)
455
+
456
+ def _save_video_from_tensor(self, pixel_tensor: torch.Tensor, base_filename: str, seed: int, temp_dir: str, fps: int = int(DEFAULT_FPS)) -> str:
457
+ """Salva um tensor de pixels como um arquivo de vídeo MP4."""
458
+ temp_path = os.path.join(temp_dir, f"{base_filename}_{seed}.mp4")
459
+ video_encode_tool_singleton.save_video_from_tensor(pixel_tensor, temp_path, fps=fps)
460
 
461
+ final_path = RESULTS_DIR / f"{base_filename}_{seed}.mp4"
462
+ shutil.move(temp_path, final_path)
463
+ print(f"[INFO] Vídeo final salvo em: {final_path}")
464
+ return str(final_path)
465
 
466
+ def _register_tmp_dir(self, dir_path: str):
467
+ """Registra um diretório temporário para limpeza posterior."""
468
+ if dir_path and os.path.isdir(dir_path):
469
+ self._tmp_dirs.add(dir_path)
470
+ if LTXV_DEBUG:
471
+ print(f"[DEBUG] Diretório temporário registrado: {dir_path}")
472
+
473
+ # ==============================================================================
474
+ # 4. INSTANCIAÇÃO E PONTO DE ENTRADA (Exemplo)
475
+ # ==============================================================================
476
+ if __name__ == "__main__":
477
+ print("Criando instância do VideoService. O carregamento do modelo começará agora...")
478
+ video_generation_service = VideoService()
479
+ print("Instância do VideoService pronta para uso.")
480
 
481
+ #