Eueuiaa commited on
Commit
a1a3fb9
·
verified ·
1 Parent(s): b174530

Create ltx_server_refactored.py

Browse files
Files changed (1) hide show
  1. api/ltx_server_refactored.py +452 -0
api/ltx_server_refactored.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ltx_server_refactored.py — VideoService (Modular Version)
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
+ def run_setup():
44
+ setup_script_path = "setup.py"
45
+ if not os.path.exists(setup_script_path):
46
+ print("[DEBUG] 'setup.py' não encontrado. Pulando clonagem de dependências.")
47
+ return
48
+ try:
49
+ print("[DEBUG] Executando setup.py para dependências...")
50
+ subprocess.run([sys.executable, setup_script_path], check=True)
51
+ print("[DEBUG] Setup concluído com sucesso.")
52
+ except subprocess.CalledProcessError as e:
53
+ print(f"[DEBUG] ERRO no setup.py (code {e.returncode}). Abortando.")
54
+ sys.exit(1)
55
+
56
+ if not LTX_VIDEO_REPO_DIR.exists():
57
+ print(f"[DEBUG] Repositório não encontrado em {LTX_VIDEO_REPO_DIR}. Rodando setup...")
58
+ run_setup()
59
+
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
+
66
+ def _query_gpu_processes_via_nvml(device_index: int) -> List[Dict]:
67
+ try:
68
+ import psutil
69
+ import pynvml as nvml
70
+ nvml.nvmlInit()
71
+ handle = nvml.nvmlDeviceGetHandleByIndex(device_index)
72
+ try:
73
+ procs = nvml.nvmlDeviceGetComputeRunningProcesses_v3(handle)
74
+ except Exception:
75
+ procs = nvml.nvmlDeviceGetComputeRunningProcesses(handle)
76
+ results = []
77
+ for p in procs:
78
+ pid = int(p.pid)
79
+ used_mb = None
80
+ try:
81
+ if getattr(p, "usedGpuMemory", None) is not None and p.usedGpuMemory not in (0,):
82
+ used_mb = max(0, int(p.usedGpuMemory) // (1024 * 1024))
83
+ except Exception:
84
+ used_mb = None
85
+ name = "unknown"
86
+ user = "unknown"
87
+ try:
88
+ import psutil
89
+ pr = psutil.Process(pid)
90
+ name = pr.name()
91
+ user = pr.username()
92
+ except Exception:
93
+ pass
94
+ results.append({"pid": pid, "name": name, "user": user, "used_mb": used_mb})
95
+ nvml.nvmlShutdown()
96
+ return results
97
+ except Exception:
98
+ return []
99
+
100
+ def _query_gpu_processes_via_nvidiasmi(device_index: int) -> List[Dict]:
101
+ cmd = f"nvidia-smi -i {device_index} --query-compute-apps=pid,process_name,used_memory --format=csv,noheader,nounits"
102
+ try:
103
+ out = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT, text=True, timeout=2.0)
104
+ except Exception:
105
+ return []
106
+ results = []
107
+ for line in out.strip().splitlines():
108
+ parts = [p.strip() for p in line.split(",")]
109
+ if len(parts) >= 3:
110
+ try:
111
+ pid = int(parts[0]); name = parts[1]; used_mb = int(parts[2])
112
+ user = "unknown"
113
+ try:
114
+ import psutil
115
+ pr = psutil.Process(pid)
116
+ user = pr.username()
117
+ except Exception:
118
+ pass
119
+ results.append({"pid": pid, "name": name, "user": user, "used_mb": used_mb})
120
+ except Exception:
121
+ continue
122
+ return results
123
+
124
+ def calculate_padding(orig_h, orig_w, target_h, target_w):
125
+ pad_h = target_h - orig_h
126
+ pad_w = target_w - orig_w
127
+ pad_top = pad_h // 2
128
+ pad_bottom = pad_h - pad_top
129
+ pad_left = pad_w // 2
130
+ pad_right = pad_w - pad_left
131
+ return (pad_left, pad_right, pad_top, pad_bottom)
132
+
133
+ def calculate_new_dimensions(orig_w, orig_h, divisor=8):
134
+ if orig_w == 0 or orig_h == 0:
135
+ return 512, 512
136
+ if orig_w >= orig_h:
137
+ aspect_ratio = orig_w / orig_h
138
+ new_h = 512
139
+ new_w = new_h * aspect_ratio
140
+ else:
141
+ aspect_ratio = orig_h / orig_w
142
+ new_w = 512
143
+ new_h = new_w * aspect_ratio
144
+ final_w = int(round(new_w / divisor)) * divisor
145
+ final_h = int(round(new_h / divisor)) * divisor
146
+ final_w = max(divisor, final_w)
147
+ final_h = max(divisor, final_h)
148
+ print(f"[Dimension Calc] Original: {orig_w}x{orig_h} -> Calculado: {new_w:.0f}x{new_h:.0f} -> Final (divisível por {divisor}): {final_w}x{final_h}")
149
+ return final_h, final_w
150
+
151
+ def _gpu_process_table(processes: List[Dict], current_pid: int) -> str:
152
+ if not processes:
153
+ return " - Processos ativos: (nenhum)\n"
154
+ processes = sorted(processes, key=lambda x: (x.get("used_mb") or 0), reverse=True)
155
+ lines = [" - Processos ativos (PID | USER | NAME | VRAM MB):"]
156
+ for p in processes:
157
+ star = "*" if p["pid"] == current_pid else " "
158
+ used_str = str(p["used_mb"]) if p.get("used_mb") is not None else "N/A"
159
+ lines.append(f" {star} {p['pid']} | {p['user']} | {p['name']} | {used_str}")
160
+ return "\n".join(lines) + "\n"
161
+
162
+ def log_tensor_info(tensor, name="Tensor"):
163
+ if not isinstance(tensor, torch.Tensor):
164
+ print(f"\n[INFO] '{name}' não é tensor.")
165
+ return
166
+ print(f"\n--- Tensor: {name} ---")
167
+ print(f" - Shape: {tuple(tensor.shape)}")
168
+ print(f" - Dtype: {tensor.dtype}")
169
+ print(f" - Device: {tensor.device}")
170
+ if tensor.numel() > 0:
171
+ try:
172
+ print(f" - Min: {tensor.min().item():.4f} Max: {tensor.max().item():.4f} Mean: {tensor.mean().item():.4f}")
173
+ except Exception:
174
+ pass
175
+ print("------------------------------------------\n")
176
+
177
+ add_deps_to_path()
178
+ from ltx_video.pipelines.pipeline_ltx_video import ConditioningItem, LTXMultiScalePipeline
179
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
180
+ from ltx_video.models.autoencoders.vae_encode import un_normalize_latents, normalize_latents
181
+ from ltx_video.pipelines.pipeline_ltx_video import adain_filter_latent
182
+ from api.ltx.inference import (
183
+ create_ltx_video_pipeline,
184
+ create_latent_upsampler,
185
+ load_image_to_tensor_with_resize_and_crop,
186
+ seed_everething,
187
+ )
188
+
189
+ class VideoService:
190
+ def __init__(self):
191
+ t0 = time.perf_counter()
192
+ print("[DEBUG] Inicializando VideoService...")
193
+ self.debug = os.getenv("LTXV_DEBUG", "1") == "1"
194
+ self.frame_log_every = int(os.getenv("LTXV_FRAME_LOG_EVERY", "8"))
195
+ self.config = self._load_config()
196
+ print(f"[DEBUG] Config carregada (precision={self.config.get('precision')}, sampler={self.config.get('sampler')})")
197
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
198
+ print(f"[DEBUG] Device selecionado: {self.device}")
199
+ self.last_memory_reserved_mb = 0.0
200
+ self._tmp_dirs = set(); self._tmp_files = set(); self._last_outputs = []
201
+
202
+ self.pipeline, self.latent_upsampler = self._load_models()
203
+ print(f"[DEBUG] Pipeline e Upsampler carregados. Upsampler ativo? {bool(self.latent_upsampler)}")
204
+
205
+ print(f"[DEBUG] Movendo modelos para {self.device}...")
206
+ self.pipeline.to(self.device)
207
+ if self.latent_upsampler:
208
+ self.latent_upsampler.to(self.device)
209
+
210
+ self._apply_precision_policy()
211
+ print(f"[DEBUG] runtime_autocast_dtype = {getattr(self, 'runtime_autocast_dtype', None)}")
212
+
213
+ vae_manager_singleton.attach_pipeline(
214
+ self.pipeline,
215
+ device=self.device,
216
+ autocast_dtype=self.runtime_autocast_dtype
217
+ )
218
+ print(f"[DEBUG] VAE manager conectado: has_vae={hasattr(self.pipeline, 'vae')} device={self.device}")
219
+
220
+ if self.device == "cuda":
221
+ torch.cuda.empty_cache()
222
+ self._log_gpu_memory("Após carregar modelos")
223
+
224
+ print(f"[DEBUG] VideoService pronto. boot_time={time.perf_counter()-t0:.3f}s")
225
+
226
+ def _log_gpu_memory(self, stage_name: str):
227
+ if self.device != "cuda":
228
+ return
229
+ device_index = torch.cuda.current_device() if torch.cuda.is_available() else 0
230
+ current_reserved_b = torch.cuda.memory_reserved(device_index)
231
+ current_reserved_mb = current_reserved_b / (1024 ** 2)
232
+ total_memory_b = torch.cuda.get_device_properties(device_index).total_memory
233
+ total_memory_mb = total_memory_b / (1024 ** 2)
234
+ peak_reserved_mb = torch.cuda.max_memory_reserved(device_index) / (1024 ** 2)
235
+ delta_mb = current_reserved_mb - getattr(self, "last_memory_reserved_mb", 0.0)
236
+ processes = _query_gpu_processes_via_nvml(device_index) or _query_gpu_processes_via_nvidiasmi(device_index)
237
+ print(f"\n--- [LOG GPU] {stage_name} (cuda:{device_index}) ---")
238
+ print(f" - Reservado: {current_reserved_mb:.2f} MB / {total_memory_mb:.2f} MB (Δ={delta_mb:+.2f} MB)")
239
+ if peak_reserved_mb > getattr(self, "last_memory_reserved_mb", 0.0):
240
+ print(f" - Pico reservado (nesta fase): {peak_reserved_mb:.2f} MB")
241
+ print(_gpu_process_table(processes, os.getpid()), end="")
242
+ print("--------------------------------------------------\n")
243
+ self.last_memory_reserved_mb = current_reserved_mb
244
+
245
+ def _register_tmp_dir(self, d: str):
246
+ if d and os.path.isdir(d):
247
+ self._tmp_dirs.add(d); print(f"[DEBUG] Registrado tmp dir: {d}")
248
+
249
+ def _register_tmp_file(self, f: str):
250
+ if f and os.path.exists(f):
251
+ self._tmp_files.add(f); print(f"[DEBUG] Registrado tmp file: {f}")
252
+
253
+ def finalize(self, keep_paths=None, extra_paths=None, clear_gpu=True):
254
+ print("[DEBUG] Finalize: iniciando limpeza...")
255
+ keep = set(keep_paths or []); extras = set(extra_paths or [])
256
+ removed_files = 0
257
+ for f in list(self._tmp_files | extras):
258
+ try:
259
+ if f not in keep and os.path.isfile(f):
260
+ os.remove(f); removed_files += 1; print(f"[DEBUG] Removido arquivo tmp: {f}")
261
+ except Exception as e:
262
+ print(f"[DEBUG] Falha removendo arquivo {f}: {e}")
263
+ finally:
264
+ self._tmp_files.discard(f)
265
+ removed_dirs = 0
266
+ for d in list(self._tmp_dirs):
267
+ try:
268
+ if d not in keep and os.path.isdir(d):
269
+ shutil.rmtree(d, ignore_errors=True); removed_dirs += 1; print(f"[DEBUG] Removido diretório tmp: {d}")
270
+ except Exception as e:
271
+ print(f"[DEBUG] Falha removendo diretório {d}: {e}")
272
+ finally:
273
+ self._tmp_dirs.discard(d)
274
+ print(f"[DEBUG] Finalize: arquivos removidos={removed_files}, dirs removidos={removed_dirs}")
275
+ gc.collect()
276
+ try:
277
+ if clear_gpu and torch.cuda.is_available():
278
+ torch.cuda.empty_cache()
279
+ try:
280
+ torch.cuda.ipc_collect()
281
+ except Exception:
282
+ pass
283
+ except Exception as e:
284
+ print(f"[DEBUG] Finalize: limpeza GPU falhou: {e}")
285
+ try:
286
+ self._log_gpu_memory("Após finalize")
287
+ except Exception as e:
288
+ print(f"[DEBUG] Log GPU pós-finalize falhou: {e}")
289
+
290
+ def _load_config(self):
291
+ base = LTX_VIDEO_REPO_DIR / "configs"
292
+ config_path = base / "ltxv-13b-0.9.8-distilled-fp8.yaml"
293
+ print(f"[DEBUG] Carregando config: {config_path}")
294
+ with open(config_path, "r") as file:
295
+ return yaml.safe_load(file)
296
+
297
+ def _load_models(self):
298
+ t0 = time.perf_counter()
299
+ LTX_REPO = "Lightricks/LTX-Video"
300
+ print("[DEBUG] Baixando checkpoint principal...")
301
+ distilled_model_path = hf_hub_download(repo_id=LTX_REPO, filename=self.config["checkpoint_path"])
302
+ self.config["checkpoint_path"] = distilled_model_path
303
+ print(f"[DEBUG] Checkpoint em: {distilled_model_path}")
304
+
305
+ print("[DEBUG] Baixando upscaler espacial...")
306
+ spatial_upscaler_path = hf_hub_download(repo_id=LTX_REPO, filename=self.config["spatial_upscaler_model_path"])
307
+ self.config["spatial_upscaler_model_path"] = spatial_upscaler_path
308
+ print(f"[DEBUG] Upscaler em: {spatial_upscaler_path}")
309
+
310
+ print("[DEBUG] Construindo pipeline...")
311
+ pipeline = create_ltx_video_pipeline(
312
+ ckpt_path=self.config["checkpoint_path"],
313
+ precision=self.config["precision"],
314
+ text_encoder_model_name_or_path=self.config["text_encoder_model_name_or_path"],
315
+ sampler=self.config["sampler"], device="cpu", enhance_prompt=False,
316
+ prompt_enhancer_image_caption_model_name_or_path=self.config["prompt_enhancer_image_caption_model_name_or_path"],
317
+ prompt_enhancer_llm_model_name_or_path=self.config["prompt_enhancer_llm_model_name_or_path"],
318
+ )
319
+ print("[DEBUG] Pipeline pronto.")
320
+
321
+ latent_upsampler = None
322
+ if self.config.get("spatial_upscaler_model_path"):
323
+ print("[DEBUG] Construindo latent_upsampler...")
324
+ latent_upsampler = create_latent_upsampler(self.config["spatial_upscaler_model_path"], device="cpu")
325
+ print("[DEBUG] Upsampler pronto.")
326
+ print(f"[DEBUG] _load_models() tempo total={time.perf_counter()-t0:.3f}s")
327
+ return pipeline, latent_upsampler
328
+
329
+ @torch.no_grad()
330
+ def _upsample_latents_internal(self, latents: torch.Tensor) -> torch.Tensor:
331
+ if not self.latent_upsampler:
332
+ raise ValueError("Latent Upsampler não está carregado.")
333
+ self.latent_upsampler.to(self.device)
334
+ self.pipeline.vae.to(self.device)
335
+ print(f"[DEBUG-UPSAMPLE] Shape de entrada: {tuple(latents.shape)}")
336
+ latents_unnormalized = un_normalize_latents(latents, self.pipeline.vae, vae_per_channel_normalize=True)
337
+ upsampled_latents = self.latent_upsampler(latents_unnormalized)
338
+ upsampled_latents_normalized = normalize_latents(upsampled_latents, self.pipeline.vae, vae_per_channel_normalize=True)
339
+ print(f"[DEBUG-UPSAMPLE] Shape de saída: {tuple(upsampled_latents_normalized.shape)}")
340
+ return upsampled_latents_normalized
341
+
342
+ def _apply_precision_policy(self):
343
+ prec = str(self.config.get("precision", "")).lower()
344
+ self.runtime_autocast_dtype = torch.float32
345
+ print(f"[DEBUG] Aplicando política de precisão: {prec}")
346
+ if prec in ["float8_e4m3fn", "bfloat16"]:
347
+ self.runtime_autocast_dtype = torch.bfloat16
348
+ elif prec == "mixed_precision":
349
+ self.runtime_autocast_dtype = torch.float16
350
+
351
+ def _prepare_conditioning_tensor(self, filepath, height, width, padding_values):
352
+ print(f"[DEBUG] Carregando condicionamento: {filepath}")
353
+ tensor = load_image_to_tensor_with_resize_and_crop(filepath, height, width)
354
+ tensor = torch.nn.functional.pad(tensor, padding_values)
355
+ out = tensor.to(self.device, dtype=self.runtime_autocast_dtype)
356
+ print(f"[DEBUG] Cond shape={tuple(out.shape)} dtype={out.dtype} device={out.device}")
357
+ return out
358
+
359
+ def _concat_mp4s_no_reencode(self, mp4_list: List[str], out_path: str):
360
+ if not mp4_list:
361
+ raise ValueError("A lista de MP4s para concatenar está vazia.")
362
+ if len(mp4_list) == 1:
363
+ shutil.move(mp4_list[0], out_path)
364
+ print(f"[DEBUG] Apenas um vídeo, movido para: {out_path}")
365
+ return
366
+
367
+ with tempfile.NamedTemporaryFile("w", delete=False, suffix=".txt") as f:
368
+ for mp4 in mp4_list:
369
+ f.write(f"file '{os.path.abspath(mp4)}'\n")
370
+ list_path = f.name
371
+
372
+ cmd = f"ffmpeg -y -f concat -safe 0 -i {list_path} -c copy {out_path}"
373
+ print(f"[DEBUG] Concat: {cmd}")
374
+
375
+ try:
376
+ subprocess.check_call(shlex.split(cmd))
377
+ finally:
378
+ os.remove(list_path)
379
+
380
+ def _save_and_log_video(self, pixel_tensor, base_filename, fps, temp_dir, results_dir, used_seed, progress_callback=None):
381
+ """Função auxiliar para salvar um tensor de pixels em um arquivo MP4."""
382
+ output_path = os.path.join(temp_dir, f"{base_filename}_{used_seed}.mp4")
383
+
384
+ video_encode_tool_singleton.save_video_from_tensor(
385
+ pixel_tensor, output_path, fps=fps, progress_callback=progress_callback
386
+ )
387
+
388
+ final_path = os.path.join(results_dir, f"{base_filename}_{used_seed}.mp4")
389
+ shutil.move(output_path, final_path)
390
+ print(f"[DEBUG] Vídeo salvo em: {final_path}")
391
+ return final_path
392
+
393
+ # ==============================================================================
394
+ # --- NOVAS FUNÇÕES MODULARES ---
395
+ # ==============================================================================
396
+
397
+ def prepare_condition_items(self, items_list: List, height: int, width: int, num_frames: int):
398
+ """
399
+ Prepara a lista de tensores de condicionamento a partir de uma lista de imagens ou tensores.
400
+ Formato da lista de entrada: [[media_path_ou_tensor, frame_alvo, peso], ...]
401
+ """
402
+ if not items_list:
403
+ return []
404
+
405
+ height_padded = ((height - 1) // 8 + 1) * 8
406
+ width_padded = ((width - 1) // 8 + 1) * 8
407
+ padding_values = calculate_padding(height, width, height_padded, width_padded)
408
+
409
+ conditioning_items = []
410
+ print("\n--- Preparando Itens de Condicionamento ---")
411
+ for item in items_list:
412
+ media, frame, weight = item
413
+
414
+ if isinstance(media, str):
415
+ print(f" - Carregando imagem: {media} para o frame {frame}")
416
+ tensor = self._prepare_conditioning_tensor(media, height, width, padding_values)
417
+ elif isinstance(media, torch.Tensor):
418
+ print(f" - Usando tensor fornecido para o frame {frame}")
419
+ tensor = media.to(self.device, dtype=self.runtime_autocast_dtype)
420
+ else:
421
+ warnings.warn(f"Tipo de item desconhecido: {type(media)}. Ignorando.")
422
+ continue
423
+
424
+ safe_frame = max(0, min(int(frame), num_frames - 1))
425
+ conditioning_items.append(ConditioningItem(tensor, safe_frame, float(weight)))
426
+
427
+ print(f"Total de itens de condicionamento preparados: {len(conditioning_items)}")
428
+ return conditioning_items
429
+
430
+ def generate_low(self, prompt, negative_prompt, height, width, duration, guidance_scale, seed, conditioning_items=None):
431
+ """
432
+ Gera um vídeo em baixa resolução (primeiro passe).
433
+ Retorna: (caminho_do_video_mp4, caminho_do_tensor_cpu, seed_usado)
434
+ """
435
+ print("\n--- INICIANDO ETAPA 1: GERAÇÃO EM BAIXA RESOLUÇÃO ---")
436
+ self._log_gpu_memory("Início da Geração Low-Res")
437
+
438
+ used_seed = random.randint(0, 2**32 - 1) if seed is None else int(seed)
439
+ seed_everething(used_seed)
440
+
441
+ FPS = 24.0
442
+ target_frames = round(duration * FPS)
443
+ actual_num_frames = max(9, int(round((target_frames - 1) / 8.0) * 8 + 1))
444
+
445
+ height_padded = ((height - 1) // 8 + 1) * 8
446
+ width_padded = ((width - 1) // 8 + 1) * 8
447
+ generator = torch.Generator(device=self.device).manual_seed(used_seed)
448
+
449
+ temp_dir = tempfile.mkdtemp(prefix="ltxv_low_"); self._register_tmp_dir(temp_dir)
450
+ results_dir = "/app/output"; os.makedirs(results_dir, exist_ok=True)
451
+
452
+ downscale_factor = self