eeuuia commited on
Commit
a90e9a9
·
verified ·
1 Parent(s): c9413de

Delete api/ltx_server_refactored_complete.py

Browse files
Files changed (1) hide show
  1. api/ltx_server_refactored_complete.py +0 -460
api/ltx_server_refactored_complete.py DELETED
@@ -1,460 +0,0 @@
1
- # FILE: api/ltx_server_refactored_complete.py
2
- # DESCRIPTION: Final orchestrator for LTX-Video generation.
3
- # This version includes the fix for the narrative generation overlap bug and
4
- # consolidates all previous refactoring and debugging improvements.
5
-
6
- import gc
7
- import json
8
- import logging
9
- import os
10
- import shutil
11
- import sys
12
- import tempfile
13
- import time
14
- from pathlib import Path
15
- from typing import Dict, List, Optional, Tuple
16
- import random
17
- import torch
18
- import yaml
19
- import numpy as np
20
- from huggingface_hub import hf_hub_download
21
-
22
- # ==============================================================================
23
- # --- SETUP E IMPORTAÇÕES DO PROJETO ---
24
- # ==============================================================================
25
-
26
- # Configuração de logging e supressão de warnings
27
- import warnings
28
- warnings.filterwarnings("ignore")
29
- logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
30
- log_level = os.environ.get("ADUC_LOG_LEVEL", "INFO").upper()
31
- logging.basicConfig(level=log_level, format='[%(levelname)s] [%(name)s] %(message)s')
32
-
33
- # --- Constantes de Configuração ---
34
- DEPS_DIR = Path("/data")
35
- LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
36
- RESULTS_DIR = Path("/app/output")
37
- DEFAULT_FPS = 24.0
38
- FRAMES_ALIGNMENT = 8
39
- LTX_REPO_ID = "Lightricks/LTX-Video"
40
-
41
- # Garante que a biblioteca LTX-Video seja importável
42
- def add_deps_to_path():
43
- repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
44
- if repo_path not in sys.path:
45
- sys.path.insert(0, repo_path)
46
- logging.info(f"[ltx_server] LTX-Video repository added to sys.path: {repo_path}")
47
-
48
- add_deps_to_path()
49
-
50
- # --- Módulos da nossa Arquitetura ---
51
- try:
52
- from api.gpu_manager import gpu_manager
53
- from managers.vae_manager import vae_manager_singleton
54
- from tools.video_encode_tool import video_encode_tool_singleton
55
- from api.ltx.ltx_utils import (
56
- build_ltx_pipeline_on_cpu,
57
- seed_everything,
58
- load_image_to_tensor_with_resize_and_crop,
59
- ConditioningItem,
60
- )
61
- from api.utils.debug_utils import log_function_io
62
- except ImportError as e:
63
- logging.critical(f"A crucial import from the local API/architecture failed. Error: {e}", exc_info=True)
64
- sys.exit(1)
65
-
66
- # ==============================================================================
67
- # --- FUNÇÕES AUXILIARES DO ORQUESTRADOR ---
68
- # ==============================================================================
69
-
70
- @log_function_io
71
- def calculate_padding(orig_h: int, orig_w: int, target_h: int, target_w: int) -> Tuple[int, int, int, int]:
72
- """Calculates symmetric padding required to meet target dimensions."""
73
- pad_h = target_h - orig_h
74
- pad_w = target_w - orig_w
75
- pad_top = pad_h // 2
76
- pad_bottom = pad_h - pad_top
77
- pad_left = pad_w // 2
78
- pad_right = pad_w - pad_left
79
- return (pad_left, pad_right, pad_top, pad_bottom)
80
-
81
- # ==============================================================================
82
- # --- CLASSE DE SERVIÇO (O ORQUESTRADOR) ---
83
- # ==============================================================================
84
-
85
- class VideoService:
86
- """
87
- Orchestrates the high-level logic of video generation, delegating low-level
88
- tasks to specialized managers and utility modules.
89
- """
90
-
91
- @log_function_io
92
- def __init__(self):
93
- t0 = time.perf_counter()
94
- logging.info("Initializing VideoService Orchestrator...")
95
- RESULTS_DIR.mkdir(parents=True, exist_ok=True)
96
-
97
- target_main_device_str = str(gpu_manager.get_ltx_device())
98
- target_vae_device_str = str(gpu_manager.get_ltx_vae_device())
99
- logging.info(f"LTX allocated to devices: Main='{target_main_device_str}', VAE='{target_vae_device_str}'")
100
-
101
- self.config = self._load_config()
102
- self._resolve_model_paths_from_cache()
103
-
104
- self.pipeline, self.latent_upsampler = build_ltx_pipeline_on_cpu(self.config)
105
-
106
- self.main_device = torch.device("cpu")
107
- self.vae_device = torch.device("cpu")
108
- self.move_to_device(main_device_str=target_main_device_str, vae_device_str=target_vae_device_str)
109
-
110
- self._apply_precision_policy()
111
- vae_manager_singleton.attach_pipeline(self.pipeline, device=self.vae_device, autocast_dtype=self.runtime_autocast_dtype)
112
- logging.info(f"VideoService ready. Startup time: {time.perf_counter()-t0:.2f}s")
113
-
114
- def _load_config(self) -> Dict:
115
- """Loads the YAML configuration file."""
116
- config_path = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
117
- logging.info(f"Loading config from: {config_path}")
118
- with open(config_path, "r") as file:
119
- return yaml.safe_load(file)
120
-
121
- def _resolve_model_paths_from_cache(self):
122
- """Finds the absolute paths to model files in the cache and updates the in-memory config."""
123
- logging.info("Resolving model paths from Hugging Face cache...")
124
- cache_dir = os.environ.get("HF_HOME")
125
- try:
126
- main_ckpt_path = hf_hub_download(repo_id=LTX_REPO_ID, filename=self.config["checkpoint_path"], cache_dir=cache_dir)
127
- self.config["checkpoint_path"] = main_ckpt_path
128
- logging.info(f" -> Main checkpoint resolved to: {main_ckpt_path}")
129
-
130
- if self.config.get("spatial_upscaler_model_path"):
131
- upscaler_path = hf_hub_download(repo_id=LTX_REPO_ID, filename=self.config["spatial_upscaler_model_path"], cache_dir=cache_dir)
132
- self.config["spatial_upscaler_model_path"] = upscaler_path
133
- logging.info(f" -> Spatial upscaler resolved to: {upscaler_path}")
134
- except Exception as e:
135
- logging.critical(f"Failed to resolve model paths. Ensure setup.py ran correctly. Error: {e}", exc_info=True)
136
- sys.exit(1)
137
-
138
- @log_function_io
139
- def move_to_device(self, main_device_str: str, vae_device_str: str):
140
- """Moves pipeline components to their designated target devices."""
141
- target_main_device = torch.device(main_device_str)
142
- target_vae_device = torch.device(vae_device_str)
143
- logging.info(f"Moving LTX models -> Main Pipeline: {target_main_device}, VAE: {target_vae_device}")
144
-
145
- self.main_device = target_main_device
146
- self.pipeline.to(self.main_device)
147
- self.vae_device = target_vae_device
148
- self.pipeline.vae.to(self.vae_device)
149
- if self.latent_upsampler: self.latent_upsampler.to(self.main_device)
150
- logging.info("LTX models successfully moved to target devices.")
151
-
152
- def move_to_cpu(self):
153
- """Moves all LTX components to CPU to free VRAM for other services."""
154
- self.move_to_device(main_device_str="cpu", vae_device_str="cpu")
155
- if torch.cuda.is_available(): torch.cuda.empty_cache()
156
-
157
- def finalize(self):
158
- """Cleans up GPU memory after a generation task."""
159
- gc.collect()
160
- if torch.cuda.is_available():
161
- torch.cuda.empty_cache()
162
- try: torch.cuda.ipc_collect();
163
- except Exception: pass
164
-
165
- # ==========================================================================
166
- # --- LÓGICA DE NEGÓCIO: ORQUESTRADOR PÚBLICO UNIFICADO ---
167
- # ==========================================================================
168
-
169
- @log_function_io
170
- def generate_low_resolution(self, prompt: str, **kwargs) -> Tuple[Optional[str], Optional[str], Optional[int]]:
171
- """
172
- [UNIFIED ORCHESTRATOR] Generates a low-resolution video from a prompt.
173
- Handles both single-line and multi-line prompts transparently.
174
- """
175
- logging.info("Starting unified low-resolution generation (random seed)...")
176
- used_seed = self._get_random_seed()
177
- seed_everything(used_seed)
178
- logging.info(f"Using randomly generated seed: {used_seed}")
179
-
180
- prompt_list = [p.strip() for p in prompt.splitlines() if p.strip()]
181
- if not prompt_list: raise ValueError("Prompt is empty or contains no valid lines.")
182
-
183
- is_narrative = len(prompt_list) > 1
184
- logging.info(f"Generation mode detected: {'Narrative' if is_narrative else 'Simple'} ({len(prompt_list)} scene(s)).")
185
-
186
- num_chunks = len(prompt_list)
187
- total_frames = self._calculate_aligned_frames(kwargs.get("duration", 4.0))
188
- frames_per_chunk = max(FRAMES_ALIGNMENT, (total_frames // num_chunks // FRAMES_ALIGNMENT) * FRAMES_ALIGNMENT)
189
-
190
- # Overlap must be N*8+1 frames. 9 is the smallest practical value.
191
- overlap_frames = 9 if is_narrative else 0
192
- if is_narrative:
193
- logging.info(f"Narrative mode: Using overlap of {overlap_frames} frames between chunks.")
194
-
195
- temp_latent_paths = []
196
- overlap_condition_item = None
197
-
198
- try:
199
- for i, chunk_prompt in enumerate(prompt_list):
200
- logging.info(f"Processing scene {i+1}/{num_chunks}: '{chunk_prompt[:50]}...'")
201
-
202
- if i < num_chunks - 1:
203
- current_frames_base = frames_per_chunk
204
- else: # Last chunk takes all remaining frames
205
- processed_frames_base = (num_chunks - 1) * frames_per_chunk
206
- current_frames_base = total_frames - processed_frames_base
207
-
208
- current_frames = current_frames_base + (overlap_frames if i > 0 else 0)
209
- # Ensure final frame count for generation is N*8+1
210
- current_frames = self._align(current_frames, alignment_rule='n*8+1')
211
-
212
- current_conditions = kwargs.get("initial_conditions", []) if i == 0 else []
213
- if overlap_condition_item:
214
- current_conditions.append(overlap_condition_item)
215
-
216
- chunk_latents = self._generate_single_chunk_low(
217
- prompt=chunk_prompt, num_frames=current_frames, seed=used_seed + i,
218
- conditioning_items=current_conditions, **kwargs
219
- )
220
- if chunk_latents is None: raise RuntimeError(f"Failed to generate latents for scene {i+1}.")
221
-
222
- if is_narrative and i < num_chunks - 1:
223
- # 1. Criar tensor overlap latente
224
- overlap_latents = chunk_latents[:, :, -overlap_frames:, :, :].clone()
225
- logging.info(f"Criado overlap latente com shape: {list(overlap_latents.shape)}")
226
-
227
- # 2. DECODIFICA o latente de volta para um tensor de PIXEL
228
- logging.info("Decodificando latente de overlap para tensor de pixel...")
229
- overlap_pixel_tensor = vae_manager_singleton.decode(
230
- overlap_latents,
231
- decode_timestep=float(self.config.get("decode_timestep", 0.05))
232
- )
233
- # O resultado de decode() está na CPU, no formato (B, C, F, H, W) e [0, 1]
234
- # Precisamos normalizá-lo para [-1, 1] que é o que o pipeline espera.
235
- overlap_pixel_tensor_normalized = (overlap_pixel_tensor * 2.0) - 1.0
236
- logging.info(f"Tensor de pixel de overlap criado com shape: {list(overlap_pixel_tensor_normalized.shape)}")
237
-
238
- # 3. Cria o ConditioningItem com o TENSOR DE PIXEL, não com o latente.
239
- overlap_condition_item = ConditioningItem(
240
- media_item=overlap_pixel_tensor_normalized,
241
- media_frame_number=0,conditioning_strength=1.0
242
- )
243
-
244
-
245
- if i > 0:
246
- chunk_latents = chunk_latents[:, :, overlap_frames:, :, :]
247
-
248
- chunk_path = RESULTS_DIR / f"temp_chunk_{i}_{used_seed}.pt"
249
- torch.save(chunk_latents.cpu(), chunk_path)
250
- temp_latent_paths.append(chunk_path)
251
-
252
- base_filename = "narrative_video" if is_narrative else "single_video"
253
- return self._finalize_generation(temp_latent_paths, base_filename, used_seed)
254
- except Exception as e:
255
- logging.error(f"Error during unified generation: {e}", exc_info=True)
256
- return None, None, None
257
- finally:
258
- for path in temp_latent_paths:
259
- if path.exists(): path.unlink()
260
- self.finalize()
261
-
262
- # ==========================================================================
263
- # --- UNIDADES DE TRABALHO E HELPERS INTERNOS ---
264
- # ==========================================================================
265
-
266
- # --- NOVA FUNÇÃO DE LOG DEDICADA ---
267
- def _log_conditioning_items(self, items: List[ConditioningItem]):
268
- """
269
- Logs detailed information about a list of ConditioningItem objects.
270
- This is a dedicated debug helper function.
271
- """
272
- # Só imprime o log se o nível de logging for DEBUG
273
- if logging.getLogger().isEnabledFor(logging.INFO):
274
- log_str = ["\n" + "="*25 + " INFO: Conditioning Items " + "="*25]
275
- if not items:
276
- log_str.append(" -> Lista de conditioning_items está vazia.")
277
- else:
278
- for i, item in enumerate(items):
279
- if hasattr(item, 'media_item') and isinstance(item.media_item, torch.Tensor):
280
- t = item.media_item
281
- log_str.append(
282
- f" -> Item [{i}]: "
283
- f"Tensor(shape={list(t.shape)}, "
284
- f"device='{t.device}', "
285
- f"dtype={t.dtype}), "
286
- f"Target Frame = {item.media_frame_number}, "
287
- f"Strength = {item.conditioning_strength:.2f}"
288
- )
289
- else:
290
- log_str.append(f" -> Item [{i}]: Não contém um tensor válido.")
291
- log_str.append("="*75 + "\n")
292
-
293
- # Usa o logger de debug para imprimir a mensagem completa
294
- logging.info("\n".join(log_str))
295
-
296
-
297
- @log_function_io
298
- def _generate_single_chunk_low(self, **kwargs) -> Optional[torch.Tensor]:
299
- """[WORKER] Calls the pipeline to generate a single chunk of latents."""
300
- height_padded, width_padded = (self._align(d) for d in (kwargs['height'], kwargs['width']))
301
- downscale_factor = self.config.get("downscale_factor", 0.6666666)
302
- vae_scale_factor = self.pipeline.vae_scale_factor
303
- downscaled_height = self._align(int(height_padded * downscale_factor), vae_scale_factor)
304
- downscaled_width = self._align(int(width_padded * downscale_factor), vae_scale_factor)
305
-
306
-
307
- # 1. Começa com a configuração padrão
308
- first_pass_config = self.config.get("first_pass", {}).copy()
309
-
310
- # 2. Aplica os overrides da UI, se existirem
311
- if kwargs.get("ltx_configs_override"):
312
- self._apply_ui_overrides(first_pass_config, kwargs.get("ltx_configs_override"))
313
-
314
- # 3. Monta o dicionário de argumentos SEM conditioning_items primeiro
315
- pipeline_kwargs = {
316
- "prompt": kwargs['prompt'],
317
- "negative_prompt": kwargs['negative_prompt'],
318
- "height": downscaled_height,
319
- "width": downscaled_width,
320
- "num_frames": kwargs['num_frames'],
321
- "frame_rate": int(DEFAULT_FPS),
322
- "generator": torch.Generator(device=self.main_device).manual_seed(kwargs['seed']),
323
- "output_type": "latent",
324
- #"conditioning_items": conditioning_items if conditioning_items else None,
325
- "media_items": None,
326
- "decode_timestep": self.config["decode_timestep"],
327
- "decode_noise_scale": self.config["decode_noise_scale"],
328
- "stochastic_sampling": self.config["stochastic_sampling"],
329
- "image_cond_noise_scale": 0.01,
330
- "is_video": True,
331
- "vae_per_channel_normalize": True,
332
- "mixed_precision": (self.config["precision"] == "mixed_precision"),
333
- "offload_to_cpu": False,
334
- "enhance_prompt": False,
335
- #"skip_layer_strategy": SkipLayerStrategy.AttentionValues,
336
- **first_pass_config
337
- }
338
-
339
- # --- Bloco de Logging para Depuração ---
340
- # 4. Loga os argumentos do pipeline (sem os tensores de condição)
341
- logging.info(f"\n[Info] Pipeline Arguments (BASE):\n {json.dumps(pipeline_kwargs, indent=2, default=str)}\n")
342
-
343
- # Loga os conditioning_items separadamente com a nossa função helper
344
- conditioning_items_list = kwargs.get('conditioning_items')
345
- self._log_conditioning_items(conditioning_items_list)
346
- # --- Fim do Bloco de Logging ---
347
-
348
- # 5. Adiciona os conditioning_items ao dicionário
349
- pipeline_kwargs['conditioning_items'] = conditioning_items_list
350
-
351
- # 6. Executa o pipeline com o dicionário completo
352
- with torch.autocast(device_type=self.main_device.type, dtype=self.runtime_autocast_dtype, enabled="cuda" in self.main_device.type):
353
- latents_raw = self.pipeline(**pipeline_kwargs).images
354
-
355
- return latents_raw.to(self.main_device)
356
-
357
-
358
- @log_function_io
359
- def _finalize_generation(self, temp_latent_paths: List[Path], base_filename: str, seed: int) -> Tuple[str, str, int]:
360
- """Consolidates latents, decodes them to video, and saves final artifacts."""
361
- logging.info("Finalizing generation: decoding latents to video.")
362
- all_tensors_cpu = [torch.load(p) for p in temp_latent_paths]
363
- final_latents = torch.cat(all_tensors_cpu, dim=2)
364
-
365
- final_latents_path = RESULTS_DIR / f"latents_{base_filename}_{seed}.pt"
366
- torch.save(final_latents, final_latents_path)
367
- logging.info(f"Final latents saved to: {final_latents_path}")
368
-
369
- pixel_tensor = vae_manager_singleton.decode(
370
- final_latents, decode_timestep=float(self.config.get("decode_timestep", 0.05))
371
- )
372
- video_path = self._save_and_log_video(pixel_tensor, f"{base_filename}_{seed}")
373
- return str(video_path), str(final_latents_path), seed
374
-
375
- @log_function_io
376
- def prepare_condition_items(self, items_list: List, height: int, width: int, num_frames: int) -> List[ConditioningItem]:
377
- """
378
- [CORRIGIDO] Prepara ConditioningItems, garantindo que o tensor final
379
- resida no dispositivo principal do pipeline (main_device).
380
- """
381
- if not items_list: return []
382
- height_padded, width_padded = self._align(height), self._align(width)
383
- padding_values = calculate_padding(height, width, height_padded, width_padded)
384
-
385
- conditioning_items = []
386
- for media_item, frame, weight in items_list:
387
- final_tensor = None
388
- if isinstance(media_item, str):
389
- # 1. Carrega a imagem. A função pode usar o VAE, então ela pode
390
- # retornar um tensor em qualquer dispositivo.
391
- tensor = load_image_to_tensor_with_resize_and_crop(media_item, height, width)
392
- # 2. Aplica padding.
393
- tensor = torch.nn.functional.pad(tensor, padding_values)
394
- # 3. GARANTE que o tensor final esteja no dispositivo principal.
395
- final_tensor = tensor.to(self.main_device, dtype=self.runtime_autocast_dtype)
396
-
397
- elif isinstance(media_item, torch.Tensor):
398
- # Se já for um tensor (ex: overlap), apenas garante que ele está no dispositivo principal.
399
- final_tensor = media_item.to(self.main_device, dtype=self.runtime_autocast_dtype)
400
- else:
401
- logging.warning(f"Unknown conditioning media type: {type(media_item)}. Skipping.")
402
- continue
403
-
404
- safe_frame = max(0, min(int(frame), num_frames - 1))
405
- conditioning_items.append(ConditioningItem(final_tensor, safe_frame, float(weight)))
406
-
407
- self._log_conditioning_items(conditioning_items)
408
- return conditioning_items
409
-
410
-
411
- def _apply_ui_overrides(self, config_dict: Dict, overrides: Dict):
412
- """Applies advanced settings from the UI to a config dictionary."""
413
- # Override step counts
414
- for key in ["num_inference_steps", "skip_initial_inference_steps", "skip_final_inference_steps"]:
415
- ui_value = overrides.get(key)
416
- if ui_value and ui_value > 0:
417
- config_dict[key] = ui_value
418
- logging.info(f"Override: '{key}' set to {ui_value} by UI.")
419
-
420
- def _save_and_log_video(self, pixel_tensor: torch.Tensor, base_filename: str) -> Path:
421
- with tempfile.TemporaryDirectory() as temp_dir:
422
- temp_path = os.path.join(temp_dir, f"{base_filename}.mp4")
423
- video_encode_tool_singleton.save_video_from_tensor(pixel_tensor, temp_path, fps=DEFAULT_FPS)
424
- final_path = RESULTS_DIR / f"{base_filename}.mp4"
425
- shutil.move(temp_path, final_path)
426
- logging.info(f"Video saved successfully to: {final_path}")
427
- return final_path
428
-
429
- def _apply_precision_policy(self):
430
- precision = str(self.config.get("precision", "bfloat16")).lower()
431
- if precision in ["float8_e4m3fn", "bfloat16"]: self.runtime_autocast_dtype = torch.bfloat16
432
- elif precision == "mixed_precision": self.runtime_autocast_dtype = torch.float16
433
- else: self.runtime_autocast_dtype = torch.float32
434
- logging.info(f"Runtime precision policy set for autocast: {self.runtime_autocast_dtype}")
435
-
436
- def _align(self, dim: int, alignment: int = FRAMES_ALIGNMENT, alignment_rule: str = 'default') -> int:
437
- """Aligns a dimension to the nearest multiple of `alignment`."""
438
- if alignment_rule == 'n*8+1':
439
- return ((dim - 1) // alignment) * alignment + 1
440
- return ((dim - 1) // alignment + 1) * alignment
441
-
442
- def _calculate_aligned_frames(self, duration_s: float, min_frames: int = 1) -> int:
443
- num_frames = int(round(duration_s * DEFAULT_FPS))
444
- # Para a duração total, sempre arredondamos para cima para o múltiplo de 8 mais próximo
445
- aligned_frames = self._align(num_frames, alignment=FRAMES_ALIGNMENT)
446
- return max(aligned_frames, min_frames)
447
-
448
- def _get_random_seed(self) -> int:
449
- """Always generates and returns a new random seed."""
450
- return random.randint(0, 2**32 - 1)
451
-
452
- # ==============================================================================
453
- # --- INSTANCIAÇÃO SINGLETON ---
454
- # ==============================================================================
455
- try:
456
- video_generation_service = VideoService()
457
- logging.info("Global VideoService orchestrator instance created successfully.")
458
- except Exception as e:
459
- logging.critical(f"Failed to initialize VideoService: {e}", exc_info=True)
460
- sys.exit(1)