Carlexxx
commited on
Commit
·
471266b
1
Parent(s):
39d7fa5
feat: Implement self-contained specialist managers
Browse files
aduc_framework/engineers/__init__.py
CHANGED
|
@@ -6,12 +6,10 @@ from .deformes2D_thinker import deformes2d_thinker_singleton
|
|
| 6 |
from .deformes3D_thinker import deformes3d_thinker_singleton
|
| 7 |
from .deformes3D import deformes3d_engine_singleton
|
| 8 |
from .deformes4D import Deformes4DEngine
|
| 9 |
-
from .deformes7D import deformes7d_engine_singleton
|
| 10 |
|
| 11 |
__all__ = [
|
| 12 |
"deformes2d_thinker_singleton",
|
| 13 |
"deformes3d_thinker_singleton",
|
| 14 |
"deformes3d_engine_singleton",
|
| 15 |
"Deformes4DEngine",
|
| 16 |
-
"deformes7d_engine_singleton",
|
| 17 |
]
|
|
|
|
| 6 |
from .deformes3D_thinker import deformes3d_thinker_singleton
|
| 7 |
from .deformes3D import deformes3d_engine_singleton
|
| 8 |
from .deformes4D import Deformes4DEngine
|
|
|
|
| 9 |
|
| 10 |
__all__ = [
|
| 11 |
"deformes2d_thinker_singleton",
|
| 12 |
"deformes3d_thinker_singleton",
|
| 13 |
"deformes3d_engine_singleton",
|
| 14 |
"Deformes4DEngine",
|
|
|
|
| 15 |
]
|
aduc_framework/engineers/deformes7D.py
DELETED
|
@@ -1,233 +0,0 @@
|
|
| 1 |
-
# aduc_framework/engineers/deformes7D.py
|
| 2 |
-
#
|
| 3 |
-
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
-
#
|
| 5 |
-
# Versão 3.2.3 (Framework-Compliant com Inicialização Explícita)
|
| 6 |
-
#
|
| 7 |
-
# Este é o motor de geração unificado. Ele intercala a criação de keyframes (3D)
|
| 8 |
-
# e fragmentos de vídeo (4D) em um único processo contínuo, potencialmente
|
| 9 |
-
# economizando recursos e melhorando a coerência.
|
| 10 |
-
|
| 11 |
-
import os
|
| 12 |
-
import time
|
| 13 |
-
import imageio
|
| 14 |
-
import numpy as np
|
| 15 |
-
import torch
|
| 16 |
-
import logging
|
| 17 |
-
from PIL import Image, ImageOps
|
| 18 |
-
import subprocess
|
| 19 |
-
import gc
|
| 20 |
-
import yaml
|
| 21 |
-
import shutil
|
| 22 |
-
from pathlib import Path
|
| 23 |
-
from typing import List, Tuple, Dict, Generator, Callable, Optional
|
| 24 |
-
|
| 25 |
-
# --- Imports Relativos Corrigidos ---
|
| 26 |
-
from ..types import LatentConditioningItem
|
| 27 |
-
from ..managers.ltx_manager import ltx_manager_singleton
|
| 28 |
-
from ..managers.latent_enhancer_manager import latent_enhancer_specialist_singleton
|
| 29 |
-
from ..managers.vae_manager import vae_manager_singleton
|
| 30 |
-
from .deformes2D_thinker import deformes2d_thinker_singleton
|
| 31 |
-
from .deformes3D_thinker import deformes3d_thinker_singleton
|
| 32 |
-
from ..managers.seedvr_manager import seedvr_manager_singleton
|
| 33 |
-
from ..managers.mmaudio_manager import mmaudio_manager_singleton
|
| 34 |
-
from ..tools.video_encode_tool import video_encode_tool_singleton
|
| 35 |
-
|
| 36 |
-
logger = logging.getLogger(__name__)
|
| 37 |
-
|
| 38 |
-
ProgressCallback = Optional[Callable[[float, str], None]]
|
| 39 |
-
|
| 40 |
-
class Deformes7DEngine:
|
| 41 |
-
"""
|
| 42 |
-
Motor unificado 3D/4D para geração contínua e intercalada de keyframes e
|
| 43 |
-
fragmentos de vídeo.
|
| 44 |
-
"""
|
| 45 |
-
def __init__(self):
|
| 46 |
-
"""O construtor é leve e não recebe argumentos."""
|
| 47 |
-
self.workspace_dir: Optional[str] = None
|
| 48 |
-
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 49 |
-
logger.info("Deformes7DEngine instanciado (não inicializado).")
|
| 50 |
-
|
| 51 |
-
def initialize(self, workspace_dir: str):
|
| 52 |
-
"""Inicializa o motor unificado com as configurações necessárias."""
|
| 53 |
-
if self.workspace_dir is not None:
|
| 54 |
-
return # Evita reinicialização
|
| 55 |
-
self.workspace_dir = workspace_dir
|
| 56 |
-
os.makedirs(self.workspace_dir, exist_ok=True)
|
| 57 |
-
logger.info(f"Deformes7D Unified Engine inicializado com workspace: {self.workspace_dir}.")
|
| 58 |
-
|
| 59 |
-
def generate_full_movie_interleaved(
|
| 60 |
-
self,
|
| 61 |
-
generation_state: Dict[str, Any],
|
| 62 |
-
progress_callback: ProgressCallback = None
|
| 63 |
-
) -> Dict[str, Any]:
|
| 64 |
-
"""
|
| 65 |
-
Gera um filme completo de forma intercalada, lendo todos os parâmetros
|
| 66 |
-
do estado de geração.
|
| 67 |
-
"""
|
| 68 |
-
if not self.workspace_dir:
|
| 69 |
-
raise RuntimeError("Deformes7DEngine não foi inicializado. Chame o método initialize() antes de usar.")
|
| 70 |
-
|
| 71 |
-
logger.info("--- DEFORMES 7D: INICIANDO PIPELINE DE RENDERIZAÇÃO INTERCALADA ---")
|
| 72 |
-
|
| 73 |
-
# 1. Extrai todos os parâmetros do estado
|
| 74 |
-
pre_prod_params = generation_state.get("parametros_geracao", {}).get("pre_producao", {})
|
| 75 |
-
prod_params = generation_state.get("parametros_geracao", {}).get("producao", {})
|
| 76 |
-
storyboard = [ato["resumo_ato"] for ato in generation_state.get("Atos", [])]
|
| 77 |
-
global_prompt = generation_state.get("Promt_geral", "")
|
| 78 |
-
initial_ref_paths = [media["caminho"] for media in generation_state.get("midias_referencia", [])]
|
| 79 |
-
|
| 80 |
-
video_resolution = pre_prod_params.get('resolution', 480)
|
| 81 |
-
seconds_per_fragment = pre_prod_params.get('duration_per_fragment', 4.0)
|
| 82 |
-
|
| 83 |
-
trim_percent = prod_params.get('trim_percent', 50)
|
| 84 |
-
handler_strength = prod_params.get('handler_strength', 0.5)
|
| 85 |
-
dest_strength = prod_params.get('destination_convergence_strength', 0.75)
|
| 86 |
-
ltx_params = {
|
| 87 |
-
"guidance_scale": prod_params.get('guidance_scale', 2.0),
|
| 88 |
-
"stg_scale": prod_params.get('stg_scale', 0.025),
|
| 89 |
-
"num_inference_steps": prod_params.get('inference_steps', 20)
|
| 90 |
-
}
|
| 91 |
-
|
| 92 |
-
# 2. Inicia o processo de geração
|
| 93 |
-
run_timestamp = int(time.time())
|
| 94 |
-
temp_video_clips_dir = os.path.join(self.workspace_dir, f"temp_clips_7D_{run_timestamp}")
|
| 95 |
-
os.makedirs(temp_video_clips_dir, exist_ok=True)
|
| 96 |
-
FPS = 24
|
| 97 |
-
FRAMES_PER_LATENT_CHUNK = 8
|
| 98 |
-
resolution_tuple = (video_resolution, video_resolution)
|
| 99 |
-
generated_keyframe_paths, generated_keyframe_latents, generated_video_fragment_paths = [], [], []
|
| 100 |
-
|
| 101 |
-
if progress_callback: progress_callback(0, "Bootstrap: Processando K0...")
|
| 102 |
-
k0_path = initial_ref_paths[0]
|
| 103 |
-
k0_pil = Image.open(k0_path).convert("RGB")
|
| 104 |
-
k0_processed_pil = self._preprocess_image(k0_pil, resolution_tuple)
|
| 105 |
-
k0_pixel_tensor = self._pil_to_pixel_tensor(k0_processed_pil)
|
| 106 |
-
k0_latent = vae_manager_singleton.encode(k0_pixel_tensor)
|
| 107 |
-
generated_keyframe_paths.append(k0_path)
|
| 108 |
-
generated_keyframe_latents.append(k0_latent)
|
| 109 |
-
|
| 110 |
-
if progress_callback: progress_callback(0.01, "Bootstrap: Gerando K1...")
|
| 111 |
-
prompt_k1 = deformes2d_thinker_singleton.get_anticipatory_keyframe_prompt(
|
| 112 |
-
global_prompt, "Cena inicial.", storyboard[0], storyboard[1], k0_path, initial_ref_paths
|
| 113 |
-
)
|
| 114 |
-
k1_path, k1_latent = self._generate_next_causal_keyframe(k0_path, initial_ref_paths, prompt_k1, resolution_tuple)
|
| 115 |
-
generated_keyframe_paths.append(k1_path)
|
| 116 |
-
generated_keyframe_latents.append(k1_latent)
|
| 117 |
-
|
| 118 |
-
story_history = ""
|
| 119 |
-
eco_latent_for_next_loop, dejavu_latent_for_next_loop = None, None
|
| 120 |
-
num_transitions = len(storyboard) - 1
|
| 121 |
-
base_4d_ltx_params = {"rescaling_scale": 0.15, "image_cond_noise_scale": 0.00, **ltx_params}
|
| 122 |
-
|
| 123 |
-
for i in range(1, num_transitions):
|
| 124 |
-
act_progress = i / num_transitions
|
| 125 |
-
if progress_callback: progress_callback(act_progress, f"Ato {i+1}/{num_transitions} (Gerando Keyframe)...")
|
| 126 |
-
|
| 127 |
-
logger.info(f"--> Etapa 3D: Gerando Keyframe K{i+1}")
|
| 128 |
-
kx_path = generated_keyframe_paths[i]
|
| 129 |
-
prompt_ky = deformes2d_thinker_singleton.get_anticipatory_keyframe_prompt(
|
| 130 |
-
global_prompt, story_history, storyboard[i], storyboard[i+1], kx_path, initial_ref_paths
|
| 131 |
-
)
|
| 132 |
-
ky_path, ky_latent = self._generate_next_causal_keyframe(kx_path, initial_ref_paths, prompt_ky, resolution_tuple)
|
| 133 |
-
generated_keyframe_paths.append(ky_path)
|
| 134 |
-
generated_keyframe_latents.append(ky_latent)
|
| 135 |
-
|
| 136 |
-
if progress_callback: progress_callback(act_progress + (0.5 / num_transitions), f"Ato {i+1}/{num_transitions} (Gerando Vídeo)...")
|
| 137 |
-
|
| 138 |
-
logger.info(f"--> Etapa 4D: Gerando Fragmento de Vídeo V{i-1}")
|
| 139 |
-
kb_path, kx_path, ky_path = generated_keyframe_paths[i-1], generated_keyframe_paths[i], generated_keyframe_paths[i+1]
|
| 140 |
-
motion_prompt = deformes3d_thinker_singleton.get_enhanced_motion_prompt(
|
| 141 |
-
global_prompt, story_history, kb_path, kx_path, ky_path,
|
| 142 |
-
storyboard[i-1], storyboard[i], storyboard[i+1]
|
| 143 |
-
)
|
| 144 |
-
story_history += f"\n- Ato {i}: {motion_prompt}"
|
| 145 |
-
total_frames_brutos = self._quantize_to_multiple(int(seconds_per_fragment * FPS), FRAMES_PER_LATENT_CHUNK)
|
| 146 |
-
frames_a_podar = self._quantize_to_multiple(int(total_frames_brutos * (trim_percent / 100)), FRAMES_PER_LATENT_CHUNK)
|
| 147 |
-
latents_a_podar = frames_a_podar // FRAMES_PER_LATENT_CHUNK
|
| 148 |
-
DEJAVU_FRAME_TARGET = frames_a_podar - 1 if frames_a_podar > 0 else 0
|
| 149 |
-
DESTINATION_FRAME_TARGET = total_frames_brutos - 1
|
| 150 |
-
conditioning_items = []
|
| 151 |
-
if eco_latent_for_next_loop is None:
|
| 152 |
-
conditioning_items.append(LatentConditioningItem(generated_keyframe_latents[i], 0, 1.0))
|
| 153 |
-
else:
|
| 154 |
-
conditioning_items.append(LatentConditioningItem(eco_latent_for_next_loop, 0, 1.0))
|
| 155 |
-
conditioning_items.append(LatentConditioningItem(dejavu_latent_for_next_loop, DEJAVU_FRAME_TARGET, handler_strength))
|
| 156 |
-
conditioning_items.append(LatentConditioningItem(ky_latent, DESTINATION_FRAME_TARGET, dest_strength))
|
| 157 |
-
|
| 158 |
-
fragment_latents_brutos, _ = ltx_manager_singleton.generate_latent_fragment(
|
| 159 |
-
height=video_resolution, width=video_resolution,
|
| 160 |
-
conditioning_items_data=conditioning_items, motion_prompt=motion_prompt,
|
| 161 |
-
video_total_frames=total_frames_brutos, video_fps=FPS, **base_4d_ltx_params
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
last_trim = fragment_latents_brutos[:, :, -(latents_a_podar+1):, :, :].clone()
|
| 165 |
-
eco_latent_for_next_loop = last_trim[:, :, :2, :, :].clone()
|
| 166 |
-
dejavu_latent_for_next_loop = last_trim[:, :, -1:, :, :].clone()
|
| 167 |
-
final_fragment_latents = fragment_latents_brutos[:, :, :-(latents_a_podar-1), :, :].clone()
|
| 168 |
-
final_fragment_latents = final_fragment_latents[:, :, 1:, :, :]
|
| 169 |
-
pixel_tensor = vae_manager_singleton.decode(final_fragment_latents)
|
| 170 |
-
fragment_path = os.path.join(temp_video_clips_dir, f"fragment_{i-1:04d}.mp4")
|
| 171 |
-
self.save_video_from_tensor(pixel_tensor, fragment_path, fps=FPS)
|
| 172 |
-
generated_video_fragment_paths.append(fragment_path)
|
| 173 |
-
logger.info(f"Fragmento de Vídeo V{i-1} salvo em {fragment_path}")
|
| 174 |
-
|
| 175 |
-
logger.info("--- Montagem Final dos Fragmentos de Vídeo ---")
|
| 176 |
-
if progress_callback: progress_callback(0.98, "Montando o filme final...")
|
| 177 |
-
final_video_path = os.path.join(self.workspace_dir, f"movie_7D_{run_timestamp}.mp4")
|
| 178 |
-
video_encode_tool_singleton.concatenate_videos(generated_video_fragment_paths, final_video_path, self.workspace_dir)
|
| 179 |
-
shutil.rmtree(temp_video_clips_dir)
|
| 180 |
-
logger.info(f"Filme completo gerado em: {final_video_path}")
|
| 181 |
-
return {"final_path": final_video_path, "all_keyframes": generated_keyframe_paths}
|
| 182 |
-
|
| 183 |
-
def _generate_next_causal_keyframe(self, base_keyframe_path: str, all_ref_paths: list,
|
| 184 |
-
prompt: str, resolution_tuple: tuple) -> Tuple[str, torch.Tensor]:
|
| 185 |
-
ltx_context_paths = [base_keyframe_path] + [p for p in all_ref_paths if p != base_keyframe_path][:3]
|
| 186 |
-
ltx_conditioning_items = []
|
| 187 |
-
weight = 1.0
|
| 188 |
-
for path in ltx_context_paths:
|
| 189 |
-
img_pil = Image.open(path).convert("RGB")
|
| 190 |
-
img_processed = self._preprocess_image(img_pil, resolution_tuple)
|
| 191 |
-
pixel_tensor = self._pil_to_pixel_tensor(img_processed)
|
| 192 |
-
latent_tensor = vae_manager_singleton.encode(pixel_tensor)
|
| 193 |
-
ltx_conditioning_items.append(LatentConditioningItem(latent_tensor, 0, weight))
|
| 194 |
-
if weight == 1.0: weight = -0.2
|
| 195 |
-
else: weight -= 0.2
|
| 196 |
-
ltx_base_params = {"guidance_scale": 3.0, "stg_scale": 0.1, "num_inference_steps": 25}
|
| 197 |
-
generated_latents, _ = ltx_manager_singleton.generate_latent_fragment(
|
| 198 |
-
height=resolution_tuple[0], width=resolution_tuple[1],
|
| 199 |
-
conditioning_items_data=ltx_conditioning_items, motion_prompt=prompt,
|
| 200 |
-
video_total_frames=48, video_fps=24, **ltx_base_params
|
| 201 |
-
)
|
| 202 |
-
final_latent = generated_latents[:, :, -1:, :, :]
|
| 203 |
-
upscaled_latent = latent_enhancer_specialist_singleton.upscale(final_latent)
|
| 204 |
-
pixel_tensor_out = vae_manager_singleton.decode(upscaled_latent)
|
| 205 |
-
timestamp = int(time.time() * 1000)
|
| 206 |
-
output_path = os.path.join(self.workspace_dir, f"keyframe_7D_{timestamp}.png")
|
| 207 |
-
self._save_image_from_tensor(pixel_tensor_out, output_path)
|
| 208 |
-
return output_path, final_latent
|
| 209 |
-
|
| 210 |
-
def _preprocess_image(self, image: Image.Image, target_resolution: tuple) -> Image.Image:
|
| 211 |
-
if image.size != target_resolution:
|
| 212 |
-
return ImageOps.fit(image, target_resolution, Image.Resampling.LANCZOS)
|
| 213 |
-
return image
|
| 214 |
-
|
| 215 |
-
def _pil_to_pixel_tensor(self, pil_image: Image.Image) -> torch.Tensor:
|
| 216 |
-
image_np = np.array(pil_image).astype(np.float32) / 255.0
|
| 217 |
-
tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0).unsqueeze(2)
|
| 218 |
-
return (tensor * 2.0) - 1.0
|
| 219 |
-
|
| 220 |
-
def _save_image_from_tensor(self, pixel_tensor: torch.Tensor, path: str):
|
| 221 |
-
tensor_chw = pixel_tensor.squeeze(0).squeeze(1)
|
| 222 |
-
tensor_hwc = tensor_chw.permute(1, 2, 0)
|
| 223 |
-
tensor_hwc = (tensor_hwc.clamp(-1, 1) + 1) / 2.0
|
| 224 |
-
image_np = (tensor_hwc.cpu().float().numpy() * 255).astype(np.uint8)
|
| 225 |
-
Image.fromarray(image_np).save(path)
|
| 226 |
-
|
| 227 |
-
def _quantize_to_multiple(self, n, m):
|
| 228 |
-
if m == 0: return n
|
| 229 |
-
quantized = int(round(n / m) * m)
|
| 230 |
-
return m if n > 0 and quantized == 0 else quantized
|
| 231 |
-
|
| 232 |
-
# --- Instanciação Singleton ---
|
| 233 |
-
deformes7d_engine_singleton = Deformes7DEngine()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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