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 1 |
+
# FILE: api/ltx_aduc_orchestrator.py
|
| 2 |
+
# DESCRIPTION: The main workflow orchestrator for the ADUC-SDR LTX suite.
|
| 3 |
+
# It acts as the primary entry point for the UI, coordinating the specialized
|
| 4 |
+
# LTX and VAE clients to execute a complete video generation pipeline from prompt to MP4.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
import time
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from typing import Optional, Dict
|
| 10 |
+
|
| 11 |
+
# O Orquestrador importa os CLIENTES especialistas que ele vai coordenar.
|
| 12 |
+
# Estes clientes são responsáveis por submeter os trabalhos ao pool de workers.
|
| 13 |
+
from api.ltx.ltx_aduc_pipeline import ltx_aduc_pipeline
|
| 14 |
+
from api.ltx.vae_aduc_pipeline import vae_aduc_pipeline
|
| 15 |
+
|
| 16 |
+
# O Orquestrador importa as FERRAMENTAS de que precisa para as tarefas finais.
|
| 17 |
+
from tools.video_encode_tool import video_encode_tool_singleton
|
| 18 |
+
|
| 19 |
+
# ==============================================================================
|
| 20 |
+
# --- A CLASSE ORQUESTRADORA (Cérebro do Workflow) ---
|
| 21 |
+
# ==============================================================================
|
| 22 |
+
|
| 23 |
+
class LtxAducOrchestrator:
|
| 24 |
+
"""
|
| 25 |
+
Orquestra o fluxo de trabalho completo de geração de vídeo,
|
| 26 |
+
coordenando os clientes LTX e VAE. É o ponto de entrada principal para a UI.
|
| 27 |
+
"""
|
| 28 |
+
def __init__(self):
|
| 29 |
+
"""
|
| 30 |
+
Inicializa o orquestrador. A inicialização é leve, pois os modelos
|
| 31 |
+
pesados são gerenciados pelo LTXAducManager em segundo plano.
|
| 32 |
+
"""
|
| 33 |
+
self.output_dir = "/app/output" # Diretório padrão para salvar os vídeos
|
| 34 |
+
logging.info("✅ LTX ADUC Orchestrator initialized and ready.")
|
| 35 |
+
|
| 36 |
+
def __call__(
|
| 37 |
+
self,
|
| 38 |
+
prompt: str,
|
| 39 |
+
initial_image: Optional[Image.Image] = None,
|
| 40 |
+
height: int = 432,
|
| 41 |
+
width: int = 768,
|
| 42 |
+
duration_in_seconds: float = 4.0,
|
| 43 |
+
ltx_configs: Optional[Dict] = None,
|
| 44 |
+
output_filename_base: str = "ltx_aduc_video"
|
| 45 |
+
) -> Optional[str]:
|
| 46 |
+
"""
|
| 47 |
+
Ponto de entrada principal do Orquestrador. Executa o pipeline completo.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
prompt (str): O prompt de texto completo. Cada nova linha é tratada como uma cena.
|
| 51 |
+
initial_image (Optional[Image.Image]): Uma imagem PIL para condicionar a primeira cena.
|
| 52 |
+
height (int): Altura do vídeo final.
|
| 53 |
+
width (int): Largura do vídeo final.
|
| 54 |
+
duration_in_seconds (float): Duração total desejada do vídeo.
|
| 55 |
+
ltx_configs (Optional[Dict]): Configurações avançadas para a geração LTX (steps, guidance, etc.).
|
| 56 |
+
output_filename_base (str): O nome base para o arquivo de vídeo final.
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
Optional[str]: O caminho do arquivo de vídeo .mp4 gerado, ou None em caso de falha.
|
| 60 |
+
"""
|
| 61 |
+
t0 = time.time()
|
| 62 |
+
logging.info(f"Orchestrator starting new job for prompt: '{prompt.splitlines()[0]}...'")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# =================================================================
|
| 66 |
+
# --- ETAPA 1: PREPARAÇÃO DO INPUT ---
|
| 67 |
+
# =================================================================
|
| 68 |
+
# Converte a string do prompt em uma lista de cenas.
|
| 69 |
+
prompt_list = [line.strip() for line in prompt.splitlines() if line.strip()]
|
| 70 |
+
if not prompt_list:
|
| 71 |
+
raise ValueError("O prompt está vazio ou não contém linhas válidas.")
|
| 72 |
+
|
| 73 |
+
# Prepara o item de condicionamento inicial, se uma imagem for fornecida.
|
| 74 |
+
initial_conditioning_items = []
|
| 75 |
+
if initial_image:
|
| 76 |
+
logging.info("Preparing initial conditioning item via VAE client...")
|
| 77 |
+
# Define os parâmetros: aplicar no frame 0 com força total (1.0).
|
| 78 |
+
conditioning_params = [(0, 1.0)]
|
| 79 |
+
# Chama o cliente VAE para fazer o trabalho pesado de conversão de imagem para LatentConditioningItem.
|
| 80 |
+
initial_conditioning_items = vae_aduc_pipeline(
|
| 81 |
+
media=[initial_image],
|
| 82 |
+
task='create_conditioning_items',
|
| 83 |
+
target_resolution=(height, width),
|
| 84 |
+
conditioning_params=conditioning_params
|
| 85 |
+
)
|
| 86 |
+
logging.info(f"Successfully created {len(initial_conditioning_items)} conditioning item(s).")
|
| 87 |
+
|
| 88 |
+
# =================================================================
|
| 89 |
+
# --- ETAPA 2: GERAÇÃO DO VÍDEO LATENTE ---
|
| 90 |
+
# =================================================================
|
| 91 |
+
logging.info("Submitting job to LTX client for latent video generation...")
|
| 92 |
+
# Chama o cliente LTX para gerar o tensor latente completo.
|
| 93 |
+
final_latents, used_seed = ltx_aduc_pipeline(
|
| 94 |
+
prompt_list=prompt_list,
|
| 95 |
+
initial_conditioning_items=initial_conditioning_items,
|
| 96 |
+
height=height,
|
| 97 |
+
width=width,
|
| 98 |
+
duration_in_seconds=duration_in_seconds,
|
| 99 |
+
ltx_configs=ltx_configs
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if final_latents is None:
|
| 103 |
+
raise RuntimeError("LTX client failed to generate a latent tensor.")
|
| 104 |
+
logging.info(f"LTX client returned latent tensor with shape: {final_latents.shape}")
|
| 105 |
+
|
| 106 |
+
# =================================================================
|
| 107 |
+
# --- ETAPA 3: DECODIFICAÇÃO DO LATENTE PARA PIXELS ---
|
| 108 |
+
# =================================================================
|
| 109 |
+
logging.info("Submitting job to VAE client for latent-to-pixel decoding...")
|
| 110 |
+
# Chama o cliente VAE para converter o resultado em um vídeo visível (tensor de pixels).
|
| 111 |
+
pixel_tensor = vae_aduc_pipeline(
|
| 112 |
+
media=final_latents,
|
| 113 |
+
task='decode'
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if pixel_tensor is None:
|
| 117 |
+
raise RuntimeError("VAE client failed to decode the latent tensor.")
|
| 118 |
+
logging.info(f"VAE client returned pixel tensor with shape: {pixel_tensor.shape}")
|
| 119 |
+
|
| 120 |
+
# =================================================================
|
| 121 |
+
# --- ETAPA 4: CODIFICAÇÃO PARA ARQUIVO DE VÍDEO MP4 ---
|
| 122 |
+
# =================================================================
|
| 123 |
+
video_filename = f"{output_filename_base}_{int(time.time())}_{used_seed}.mp4"
|
| 124 |
+
output_path = f"{self.output_dir}/{video_filename}"
|
| 125 |
+
|
| 126 |
+
logging.info(f"Submitting job to VideoEncodeTool to save final MP4 to: {output_path}")
|
| 127 |
+
# Usa a ferramenta de vídeo para salvar o tensor de pixels no arquivo final.
|
| 128 |
+
video_encode_tool_singleton.save_video_from_tensor(
|
| 129 |
+
pixel_5d=pixel_tensor,
|
| 130 |
+
path=output_path,
|
| 131 |
+
fps=24
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
total_time = time.time() - t0
|
| 135 |
+
logging.info(f"🚀🚀🚀 Orchestrator job complete! Video saved to {output_path}. Total time: {total_time:.2f}s")
|
| 136 |
+
|
| 137 |
+
return output_path
|
| 138 |
+
|
| 139 |
+
except Exception:
|
| 140 |
+
logging.error("ORCHESTRATOR FAILED! A critical error occurred during the workflow.", exc_info=True)
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
# ==============================================================================
|
| 144 |
+
# --- INSTÂNCIA SINGLETON DO ORQUESTRADOR ---
|
| 145 |
+
# Este é o ponto de entrada principal que a UI (app.py) irá chamar.
|
| 146 |
+
# ==============================================================================
|
| 147 |
+
try:
|
| 148 |
+
ltx_aduc_orchestrator = LtxAducOrchestrator()
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logging.critical("CRITICAL: Failed to initialize the LtxAducOrchestrator.", exc_info=True)
|
| 151 |
+
ltx_aduc_orchestrator = None
|