eeuuia commited on
Commit
a7e6912
·
verified ·
1 Parent(s): 495c1de

Upload 4 files

Browse files
api/ltx/ltx_aduc_manager.py CHANGED
@@ -27,24 +27,12 @@ LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
27
  LTX_REPO_ID = "Lightricks/LTX-Video"
28
  CACHE_DIR = os.environ.get("HF_HOME")
29
 
30
-
31
- def add_deps_to_path():
32
- """
33
- Adiciona o diretório do repositório LTX ao sys.path para garantir que suas
34
- bibliotecas possam ser importadas.
35
- """
36
- repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
37
- if repo_path not in sys.path:
38
- sys.path.insert(0, repo_path)
39
- logging.info(f"[ltx_utils] LTX-Video repository added to sys.path: {repo_path}")
40
-
41
- # Executa a função imediatamente para configurar o ambiente antes de qualquer importação.
42
- add_deps_to_path()
43
-
44
  # --- Importações da biblioteca LTX-Video ---
45
- from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
46
- from ltx_video.models.autoencoders.vae_encode import vae_encode, latent_to_pixel_coords
47
-
 
 
48
 
49
  # ==============================================================================
50
  # --- DEFINIÇÃO DOS DATACLASSES DE CONDICIONAMENTO ADUC-SDR ---
@@ -142,22 +130,19 @@ class LTXWorker:
142
  self.vae_device = torch.device(vae_device_str)
143
  self.config = config
144
  self.pipeline: LTXVideoPipeline = None
145
-
146
  self._load_and_patch_pipeline()
147
 
148
  def _load_and_patch_pipeline(self):
149
  logging.info(f"[LTXWorker-{self.main_device}] Carregando pipeline LTX para a CPU...")
150
  self.pipeline, _ = build_ltx_pipeline_on_cpu(self.config)
151
-
152
  logging.info(f"[LTXWorker-{self.main_device}] Movendo pipeline para GPUs (Main: {self.main_device}, VAE: {self.vae_device})...")
153
  self.pipeline.to(self.main_device)
154
  self.pipeline.vae.to(self.vae_device)
155
-
156
  logging.info(f"[LTXWorker-{self.main_device}] Aplicando patch ADUC-SDR na função 'prepare_conditioning'...")
157
  self.pipeline.prepare_conditioning = _aduc_prepare_conditioning_patch.__get__(self.pipeline, LTXVideoPipeline)
158
  logging.info(f"[LTXWorker-{self.main_device}] ✅ Pipeline 'quente', corrigido e pronto para uso.")
159
 
160
- class LTXPoolManager:
161
  _instance = None
162
  _lock = threading.Lock()
163
 
@@ -172,15 +157,11 @@ class LTXPoolManager:
172
  if self._initialized: return
173
  with self._lock:
174
  if self._initialized: return
175
-
176
  logging.info("⚙️ Inicializando LTXPoolManager Singleton...")
177
  self.config = self._load_config()
178
-
179
  main_device_str = str(gpu_manager.get_ltx_device())
180
  vae_device_str = str(gpu_manager.get_ltx_vae_device())
181
-
182
  self.worker = LTXWorker(main_device_str, vae_device_str, self.config)
183
-
184
  self._initialized = True
185
  logging.info("✅ LTXPoolManager pronto.")
186
 
@@ -190,11 +171,9 @@ class LTXPoolManager:
190
  with open(config_path, "r") as file:
191
  return yaml.safe_load(file)
192
 
193
-
194
-
195
  def get_pipeline(self) -> LTXVideoPipeline:
196
  """Retorna a instância do pipeline, já carregada e corrigida."""
197
  return self.worker.pipeline
198
 
199
  # --- Instância Singleton Global ---
200
- ltx_pool_manager = LTXPoolManager()
 
27
  LTX_REPO_ID = "Lightricks/LTX-Video"
28
  CACHE_DIR = os.environ.get("HF_HOME")
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # --- Importações da biblioteca LTX-Video ---
31
+ repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
32
+ if repo_path not in sys.path:
33
+ sys.path.insert(0, repo_path)
34
+ from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
35
+ from ltx_video.models.autoencoders.vae_encode import vae_encode, latent_to_pixel_coords
36
 
37
  # ==============================================================================
38
  # --- DEFINIÇÃO DOS DATACLASSES DE CONDICIONAMENTO ADUC-SDR ---
 
130
  self.vae_device = torch.device(vae_device_str)
131
  self.config = config
132
  self.pipeline: LTXVideoPipeline = None
 
133
  self._load_and_patch_pipeline()
134
 
135
  def _load_and_patch_pipeline(self):
136
  logging.info(f"[LTXWorker-{self.main_device}] Carregando pipeline LTX para a CPU...")
137
  self.pipeline, _ = build_ltx_pipeline_on_cpu(self.config)
 
138
  logging.info(f"[LTXWorker-{self.main_device}] Movendo pipeline para GPUs (Main: {self.main_device}, VAE: {self.vae_device})...")
139
  self.pipeline.to(self.main_device)
140
  self.pipeline.vae.to(self.vae_device)
 
141
  logging.info(f"[LTXWorker-{self.main_device}] Aplicando patch ADUC-SDR na função 'prepare_conditioning'...")
142
  self.pipeline.prepare_conditioning = _aduc_prepare_conditioning_patch.__get__(self.pipeline, LTXVideoPipeline)
143
  logging.info(f"[LTXWorker-{self.main_device}] ✅ Pipeline 'quente', corrigido e pronto para uso.")
144
 
145
+ class LtxAducManager:
146
  _instance = None
147
  _lock = threading.Lock()
148
 
 
157
  if self._initialized: return
158
  with self._lock:
159
  if self._initialized: return
 
160
  logging.info("⚙️ Inicializando LTXPoolManager Singleton...")
161
  self.config = self._load_config()
 
162
  main_device_str = str(gpu_manager.get_ltx_device())
163
  vae_device_str = str(gpu_manager.get_ltx_vae_device())
 
164
  self.worker = LTXWorker(main_device_str, vae_device_str, self.config)
 
165
  self._initialized = True
166
  logging.info("✅ LTXPoolManager pronto.")
167
 
 
171
  with open(config_path, "r") as file:
172
  return yaml.safe_load(file)
173
 
 
 
174
  def get_pipeline(self) -> LTXVideoPipeline:
175
  """Retorna a instância do pipeline, já carregada e corrigida."""
176
  return self.worker.pipeline
177
 
178
  # --- Instância Singleton Global ---
179
+ ltx_aduc_manager = LtxAducManager()
api/ltx/ltx_aduc_pipeline.py CHANGED
@@ -18,6 +18,13 @@ import torch
18
  import yaml
19
  import numpy as np
20
  from PIL import Image
 
 
 
 
 
 
 
21
 
22
  # ==============================================================================
23
  # --- SETUP E IMPORTAÇÕES DO PROJETO ---
@@ -27,7 +34,7 @@ from PIL import Image
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 ---
@@ -37,29 +44,16 @@ RESULTS_DIR = Path("/app/output")
37
  DEFAULT_FPS = 24.0
38
  FRAMES_ALIGNMENT = 8
39
 
40
- from api.ltx.ltx_utils import seed_everything
41
- from utils.debug_utils import log_function_io
42
-
43
-
44
  # Garante que a biblioteca LTX-Video seja importável
45
- def add_deps_to_path():
46
- repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
47
- if repo_path not in sys.path:
48
- sys.path.insert(0, repo_path)
49
- add_deps_to_path()
50
-
51
- # --- Módulos da nossa Arquitetura ---
52
- from managers.gpu_manager import gpu_manager
53
- from api.ltx.ltx_aduc_manager import ltx_pool_manager, LatentConditioningItem
54
- from api.ltx.vae_aduc_pipeline import vae_server_singleton
55
- from tools.video_encode_tool import video_encode_tool_singleton
56
-
57
 
58
  # ==============================================================================
59
  # --- CLASSE DE SERVIÇO (O ORQUESTRADOR) ---
60
  # ==============================================================================
61
 
62
- class VideoService:
63
  """
64
  Orchestrates the high-level logic of video generation, delegating all
65
  low-level tasks to specialized managers and utility modules.
@@ -70,13 +64,13 @@ class VideoService:
70
  t0 = time.time()
71
  logging.info("Initializing VideoService Orchestrator...")
72
 
73
- if ltx_pool_manager is None or vae_server_singleton is None:
74
  raise RuntimeError("A required manager (LTX or VAE) failed to initialize. Aborting.")
75
 
76
- self.pipeline = ltx_pool_manager.get_pipeline()
77
  self.main_device = self.pipeline.device
78
  self.vae_device = self.pipeline.vae.device
79
- self.config = ltx_pool_manager.config
80
 
81
  self._apply_precision_policy()
82
  logging.info(f"VideoService ready. Using Main: {self.main_device}, VAE: {self.vae_device}. Startup time: {time.time() - t0:.2f}s")
@@ -121,7 +115,7 @@ class VideoService:
121
  initial_conditions = []
122
  if initial_media_items:
123
  logging.info("Delegating to VaeServer to prepare initial conditioning items...")
124
- initial_conditions = vae_server_singleton.generate_conditioning_items(
125
  media_items=[item[0] for item in initial_media_items],
126
  target_frames=[item[1] for item in initial_media_items],
127
  strengths=[item[2] for item in initial_media_items],
@@ -278,7 +272,7 @@ class VideoService:
278
  torch.save(final_latents, final_latents_path)
279
  logging.info(f"Final latents saved to: {final_latents_path}")
280
 
281
- pixel_tensor = vae_server_singleton.decode_to_pixels(
282
  final_latents, decode_timestep=float(self.config.get("decode_timestep", 0.05))
283
  )
284
  video_path = self._save_and_log_video(pixel_tensor, f"{base_filename}_{seed}")
@@ -293,7 +287,6 @@ class VideoService:
293
  config_dict[key] = ui_value
294
  logging.info(f"Override: '{key}' set to {ui_value} by UI.")
295
 
296
-
297
  def _save_and_log_video(self, pixel_tensor: torch.Tensor, base_filename: str) -> Path:
298
  with tempfile.TemporaryDirectory() as temp_dir:
299
  temp_path = os.path.join(temp_dir, f"{base_filename}.mp4")
@@ -326,5 +319,5 @@ class VideoService:
326
  # ==============================================================================
327
  # --- INSTANCIAÇÃO SINGLETON ---
328
  # ==============================================================================
329
- video_generation_service = VideoService()
330
- logging.info("Global VideoService orchestrator instance created successfully.")
 
18
  import yaml
19
  import numpy as np
20
  from PIL import Image
21
+ from api.ltx.ltx_utils import seed_everything
22
+ from utils.debug_utils import log_function_io
23
+ from managers.gpu_manager import gpu_manager
24
+ from api.ltx.ltx_aduc_manager import ltx_aduc_manager, LatentConditioningItem
25
+ from api.ltx.vae_aduc_pipeline import vae_aduc_pipeline
26
+ from tools.video_encode_tool import video_encode_tool_singleton
27
+
28
 
29
  # ==============================================================================
30
  # --- SETUP E IMPORTAÇÕES DO PROJETO ---
 
34
  import warnings
35
  warnings.filterwarnings("ignore")
36
  logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
37
+ log_level = logging.DEBUG
38
  logging.basicConfig(level=log_level, format='[%(levelname)s] [%(name)s] %(message)s')
39
 
40
  # --- Constantes de Configuração ---
 
44
  DEFAULT_FPS = 24.0
45
  FRAMES_ALIGNMENT = 8
46
 
 
 
 
 
47
  # Garante que a biblioteca LTX-Video seja importável
48
+ repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
49
+ if repo_path not in sys.path:
50
+ sys.path.insert(0, repo_path)
 
 
 
 
 
 
 
 
 
51
 
52
  # ==============================================================================
53
  # --- CLASSE DE SERVIÇO (O ORQUESTRADOR) ---
54
  # ==============================================================================
55
 
56
+ class LtxAducPipeline:
57
  """
58
  Orchestrates the high-level logic of video generation, delegating all
59
  low-level tasks to specialized managers and utility modules.
 
64
  t0 = time.time()
65
  logging.info("Initializing VideoService Orchestrator...")
66
 
67
+ if ltx_aduc_manager is None or vae_aduc_pipeline is None:
68
  raise RuntimeError("A required manager (LTX or VAE) failed to initialize. Aborting.")
69
 
70
+ self.pipeline = ltx_aduc_manager.get_pipeline()
71
  self.main_device = self.pipeline.device
72
  self.vae_device = self.pipeline.vae.device
73
+ self.config = ltx_aduc_manager.config
74
 
75
  self._apply_precision_policy()
76
  logging.info(f"VideoService ready. Using Main: {self.main_device}, VAE: {self.vae_device}. Startup time: {time.time() - t0:.2f}s")
 
115
  initial_conditions = []
116
  if initial_media_items:
117
  logging.info("Delegating to VaeServer to prepare initial conditioning items...")
118
+ initial_conditions = vae_aduc_pipeline.generate_conditioning_items(
119
  media_items=[item[0] for item in initial_media_items],
120
  target_frames=[item[1] for item in initial_media_items],
121
  strengths=[item[2] for item in initial_media_items],
 
272
  torch.save(final_latents, final_latents_path)
273
  logging.info(f"Final latents saved to: {final_latents_path}")
274
 
275
+ pixel_tensor = vae_aduc_pipeline.decode_to_pixels(
276
  final_latents, decode_timestep=float(self.config.get("decode_timestep", 0.05))
277
  )
278
  video_path = self._save_and_log_video(pixel_tensor, f"{base_filename}_{seed}")
 
287
  config_dict[key] = ui_value
288
  logging.info(f"Override: '{key}' set to {ui_value} by UI.")
289
 
 
290
  def _save_and_log_video(self, pixel_tensor: torch.Tensor, base_filename: str) -> Path:
291
  with tempfile.TemporaryDirectory() as temp_dir:
292
  temp_path = os.path.join(temp_dir, f"{base_filename}.mp4")
 
319
  # ==============================================================================
320
  # --- INSTANCIAÇÃO SINGLETON ---
321
  # ==============================================================================
322
+ ltx_aduc_pipeline = LtxAducPipeline()
323
+ logging.info("Global VideoService orchestrator instance created successfully.")
api/ltx/ltx_utils.py CHANGED
@@ -11,7 +11,6 @@ import sys
11
  from pathlib import Path
12
  from typing import Dict, Optional, Tuple, Union
13
  from huggingface_hub import hf_hub_download
14
-
15
  import numpy as np
16
  import torch
17
  import torchvision.transforms.functional as TVF
@@ -28,24 +27,13 @@ LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
28
  LTX_REPO_ID = "Lightricks/LTX-Video"
29
  CACHE_DIR = os.environ.get("HF_HOME")
30
 
31
- def add_deps_to_path():
32
- """
33
- Adiciona o diretório do repositório LTX ao sys.path para garantir que suas
34
- bibliotecas possam ser importadas.
35
- """
36
- repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
37
- if repo_path not in sys.path:
38
- sys.path.insert(0, repo_path)
39
- logging.info(f"[ltx_utils] LTX-Video repository added to sys.path: {repo_path}")
40
-
41
- # Executa a função imediatamente para configurar o ambiente antes de qualquer importação.
42
- add_deps_to_path()
43
-
44
-
45
  # ==============================================================================
46
  # --- IMPORTAÇÕES DA BIBLIOTECA LTX-VIDEO (Após configuração do path) ---
47
  # ==============================================================================
48
- try:
 
 
 
49
  from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
50
  from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
51
  from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
@@ -53,9 +41,6 @@ try:
53
  from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
54
  from ltx_video.schedulers.rf import RectifiedFlowScheduler
55
  import ltx_video.pipelines.crf_compressor as crf_compressor
56
- except ImportError as e:
57
- raise ImportError(f"Could not import from LTX-Video library even after setting sys.path. Check repo integrity at '{LTX_VIDEO_REPO_DIR}'. Error: {e}")
58
-
59
 
60
  # ==============================================================================
61
  # --- FUNÇÕES DE CONSTRUÇÃO DE MODELO E PIPELINE ---
@@ -121,7 +106,6 @@ def build_ltx_pipeline_on_cpu(config: Dict) -> Tuple[LTXVideoPipeline, Optional[
121
  logging.info(f"LTX pipeline built on CPU in {time.perf_counter() - t0:.2f}s")
122
  return pipeline, latent_upsampler
123
 
124
-
125
  # ==============================================================================
126
  # --- FUNÇÕES AUXILIARES (Seed, Preparação de Imagem) ---
127
  # ==============================================================================
 
11
  from pathlib import Path
12
  from typing import Dict, Optional, Tuple, Union
13
  from huggingface_hub import hf_hub_download
 
14
  import numpy as np
15
  import torch
16
  import torchvision.transforms.functional as TVF
 
27
  LTX_REPO_ID = "Lightricks/LTX-Video"
28
  CACHE_DIR = os.environ.get("HF_HOME")
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # ==============================================================================
31
  # --- IMPORTAÇÕES DA BIBLIOTECA LTX-VIDEO (Após configuração do path) ---
32
  # ==============================================================================
33
+
34
+ repo_path = str(LTX_VIDEO_REPO_DIR.resolve())
35
+ if repo_path not in sys.path:
36
+ sys.path.insert(0, repo_path)
37
  from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
38
  from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
39
  from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
 
41
  from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
42
  from ltx_video.schedulers.rf import RectifiedFlowScheduler
43
  import ltx_video.pipelines.crf_compressor as crf_compressor
 
 
 
44
 
45
  # ==============================================================================
46
  # --- FUNÇÕES DE CONSTRUÇÃO DE MODELO E PIPELINE ---
 
106
  logging.info(f"LTX pipeline built on CPU in {time.perf_counter() - t0:.2f}s")
107
  return pipeline, latent_upsampler
108
 
 
109
  # ==============================================================================
110
  # --- FUNÇÕES AUXILIARES (Seed, Preparação de Imagem) ---
111
  # ==============================================================================
api/ltx/vae_aduc_pipeline.py CHANGED
@@ -14,28 +14,26 @@ import yaml
14
  import torch
15
  import numpy as np
16
  from PIL import Image
 
 
 
17
 
18
  # ==============================================================================
19
  # --- IMPORTAÇÕES DA ARQUITETURA E DO LTX ---
20
  # ==============================================================================
21
- from api.ltx.ltx_aduc_manager import LatentConditioningItem
22
- from managers.gpu_manager import gpu_manager
23
- from api.ltx.ltx_aduc_manager import ltx_pool_manager
24
 
25
  # Adiciona o path para as bibliotecas do LTX
26
-
27
  LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
28
  if str(LTX_VIDEO_REPO_DIR.resolve()) not in sys.path:
29
  sys.path.insert(0, str(LTX_VIDEO_REPO_DIR.resolve()))
30
-
31
- from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
32
- from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
33
 
34
  # ==============================================================================
35
  # --- CLASSE DO SERVIÇO VAE ---
36
  # ==============================================================================
37
 
38
- class VaeServer:
39
  _instance = None
40
  _lock = threading.Lock()
41
 
@@ -60,10 +58,10 @@ class VaeServer:
60
  # 2. Obter o modelo VAE já carregado pelo LTXPoolManager
61
  # Isso garante consistência e evita carregar o modelo duas vezes.
62
  try:
63
- from api.ltx.ltx_aduc_manager import ltx_pool_manager
64
- if ltx_pool_manager is None or ltx_pool_manager.get_pipeline() is None:
65
  raise RuntimeError("LTXPoolManager is not initialized yet. VaeServer must be initialized after.")
66
- self.vae = ltx_pool_manager.get_pipeline().vae
67
  except Exception as e:
68
  logging.critical(f"Failed to get VAE from LTXPoolManager. Error: {e}", exc_info=True)
69
  raise
@@ -150,5 +148,4 @@ class VaeServer:
150
  finally:
151
  self._cleanup_gpu()
152
 
153
-
154
- vae_server_singleton = VaeServer()
 
14
  import torch
15
  import numpy as np
16
  from PIL import Image
17
+ from api.ltx.ltx_aduc_manager import LatentConditioningItem
18
+ from managers.gpu_manager import gpu_manager
19
+ from api.ltx.ltx_aduc_manager import ltx_aduc_manager
20
 
21
  # ==============================================================================
22
  # --- IMPORTAÇÕES DA ARQUITETURA E DO LTX ---
23
  # ==============================================================================
 
 
 
24
 
25
  # Adiciona o path para as bibliotecas do LTX
 
26
  LTX_VIDEO_REPO_DIR = Path("/data/LTX-Video")
27
  if str(LTX_VIDEO_REPO_DIR.resolve()) not in sys.path:
28
  sys.path.insert(0, str(LTX_VIDEO_REPO_DIR.resolve()))
29
+ from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
30
+ from ltx_video.models.autoencoders.vae_encode import vae_encode, vae_decode
 
31
 
32
  # ==============================================================================
33
  # --- CLASSE DO SERVIÇO VAE ---
34
  # ==============================================================================
35
 
36
+ class VaeAducPipeline:
37
  _instance = None
38
  _lock = threading.Lock()
39
 
 
58
  # 2. Obter o modelo VAE já carregado pelo LTXPoolManager
59
  # Isso garante consistência e evita carregar o modelo duas vezes.
60
  try:
61
+ from api.ltx.ltx_aduc_manager import ltx_aduc_manager
62
+ if ltx_aduc_manager is None or ltx_aduc_manager.get_pipeline() is None:
63
  raise RuntimeError("LTXPoolManager is not initialized yet. VaeServer must be initialized after.")
64
+ self.vae = ltx_aduc_manager.get_pipeline().vae
65
  except Exception as e:
66
  logging.critical(f"Failed to get VAE from LTXPoolManager. Error: {e}", exc_info=True)
67
  raise
 
148
  finally:
149
  self._cleanup_gpu()
150
 
151
+ vae_aduc_pipeline = VaeAducPipeline()