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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Euia-AducSdr: Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
|
| 2 |
+
# Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
|
| 3 |
+
#
|
| 4 |
+
# Contato:
|
| 5 |
+
# Carlos Rodrigues dos Santos
|
| 6 |
+
# carlex22@gmail.com
|
| 7 |
+
# Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
|
| 8 |
+
#
|
| 9 |
+
# Repositórios e Projetos Relacionados:
|
| 10 |
+
# GitHub: https://github.com/carlex22/Aduc-sdr
|
| 11 |
+
# Hugging Face: https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
|
| 12 |
+
# Hugging Face: https://huggingface.co/spaces/Carlexxx/Novinho/
|
| 13 |
+
#
|
| 14 |
+
# Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
|
| 15 |
+
# sob os termos da Licença Pública Geral Affero da GNU como publicada pela
|
| 16 |
+
# Free Software Foundation, seja a versão 3 da Licença, ou
|
| 17 |
+
# (a seu critério) qualquer versão posterior.
|
| 18 |
+
#
|
| 19 |
+
# Este programa é distribuído na esperança de que seja útil,
|
| 20 |
+
# mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
|
| 21 |
+
# COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
|
| 22 |
+
# Licença Pública Geral Affero da GNU para mais detalhes.
|
| 23 |
+
#
|
| 24 |
+
# Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
|
| 25 |
+
# junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
|
| 26 |
+
|
| 27 |
+
# --- app.py (NOVINHO-4.2: Versão Final - Arquitetura "Memória, Caminho, Destino") ---
|
| 28 |
+
|
| 29 |
+
# --- Ato 1: A Convocação da Orquestra (Importações) ---
|
| 30 |
+
import gradio as gr
|
| 31 |
+
import torch
|
| 32 |
+
import os
|
| 33 |
+
import yaml
|
| 34 |
+
from PIL import Image, ImageOps
|
| 35 |
+
import shutil
|
| 36 |
+
import gc
|
| 37 |
+
import subprocess
|
| 38 |
+
import google.generativeai as genai
|
| 39 |
+
import numpy as np
|
| 40 |
+
import imageio
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
import huggingface_hub
|
| 43 |
+
import json
|
| 44 |
+
import time
|
| 45 |
+
|
| 46 |
+
from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
|
| 47 |
+
from dreamo_helpers import dreamo_generator_singleton
|
| 48 |
+
|
| 49 |
+
# --- Ato 2: A Preparação do Palco (Configurações) ---
|
| 50 |
+
config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
|
| 51 |
+
with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
|
| 52 |
+
|
| 53 |
+
LTX_REPO = "Lightricks/LTX-Video"
|
| 54 |
+
models_dir = "downloaded_models_gradio"
|
| 55 |
+
Path(models_dir).mkdir(parents=True, exist_ok=True)
|
| 56 |
+
WORKSPACE_DIR = "aduc_workspace"
|
| 57 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 58 |
+
|
| 59 |
+
VIDEO_FPS = 36
|
| 60 |
+
VIDEO_DURATION_SECONDS = 4
|
| 61 |
+
VIDEO_TOTAL_FRAMES = VIDEO_DURATION_SECONDS * VIDEO_FPS
|
| 62 |
+
CONVERGENCE_FRAMES = 8
|
| 63 |
+
TARGET_RESOLUTION = 720
|
| 64 |
+
|
| 65 |
+
print("Criando pipelines LTX na CPU (estado de repouso)...")
|
| 66 |
+
distilled_model_actual_path = huggingface_hub.hf_hub_download(repo_id=LTX_REPO, filename=PIPELINE_CONFIG_YAML["checkpoint_path"], local_dir=models_dir, local_dir_use_symlinks=False)
|
| 67 |
+
pipeline_instance = create_ltx_video_pipeline(
|
| 68 |
+
ckpt_path=distilled_model_actual_path,
|
| 69 |
+
precision=PIPELINE_CONFIG_YAML["precision"],
|
| 70 |
+
text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
|
| 71 |
+
sampler=PIPELINE_CONFIG_YAML["sampler"],
|
| 72 |
+
device='cpu'
|
| 73 |
+
)
|
| 74 |
+
print("Modelos LTX prontos (na CPU).")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --- Ato 3: As Partituras dos Músicos (Funções Corrigidas, Otimizadas e Documentadas) ---
|
| 78 |
+
|
| 79 |
+
def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
|
| 80 |
+
if not media_path: raise ValueError("Caminho da mídia de condicionamento não pode ser nulo.")
|
| 81 |
+
# A lógica agora só precisa lidar com imagens, simplificando o processo
|
| 82 |
+
return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
|
| 83 |
+
|
| 84 |
+
def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg, progress=gr.Progress()):
|
| 85 |
+
progress(0, desc=f"[TECPIX 5000] Filmando Cena {current_fragment_index}...");
|
| 86 |
+
output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4");
|
| 87 |
+
target_device = pipeline_instance.device
|
| 88 |
+
try:
|
| 89 |
+
conditioning_items = []
|
| 90 |
+
for (path, start_frame, strength) in conditioning_items_data:
|
| 91 |
+
tensor = load_conditioning_tensor(path, height, width)
|
| 92 |
+
conditioning_items.append(ConditioningItem(tensor.to(target_device), start_frame, strength))
|
| 93 |
+
|
| 94 |
+
n_val = round((float(VIDEO_TOTAL_FRAMES) - 1.0) / 8.0); actual_num_frames = int(n_val * 8 + 1)
|
| 95 |
+
padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
|
| 96 |
+
padding_vals = calculate_padding(height, width, padded_h, padded_w)
|
| 97 |
+
for cond_item in conditioning_items: cond_item.media_item = torch.nn.functional.pad(cond_item.media_item, padding_vals)
|
| 98 |
+
|
| 99 |
+
decode_every_val = 4
|
| 100 |
+
kwargs = { "prompt": motion_prompt, "negative_prompt": "blurry, distorted, bad quality, artifacts", "height": padded_h, "width": padded_w, "num_frames": actual_num_frames, "frame_rate": VIDEO_FPS, "generator": torch.Generator(device=target_device).manual_seed(int(seed) + current_fragment_index), "output_type": "pt", "guidance_scale": float(cfg), "timesteps": PIPELINE_CONFIG_YAML.get("first_pass", {}).get("timesteps"), "conditioning_items": conditioning_items, "decode_timestep": PIPELINE_CONFIG_YAML.get("decode_timestep"), "decode_noise_scale": PIPELINE_CONFIG_YAML.get("decode_noise_scale"), "stochastic_sampling": PIPELINE_CONFIG_YAML.get("stochastic_sampling"), "image_cond_noise_scale": 0.15, "is_video": True, "vae_per_channel_normalize": True, "mixed_precision": (PIPELINE_CONFIG_YAML.get("precision") == "mixed_precision"), "enhance_prompt": False, "decode_every": decode_every_val }
|
| 101 |
+
|
| 102 |
+
result_tensor = pipeline_instance(**kwargs).images
|
| 103 |
+
|
| 104 |
+
pad_l, pad_r, pad_t, pad_b = map(int, padding_vals); slice_h = -pad_b if pad_b > 0 else None; slice_w = -pad_r if pad_r > 0 else None
|
| 105 |
+
cropped_tensor = result_tensor[:, :, :VIDEO_TOTAL_FRAMES, pad_t:slice_h, pad_l:slice_w]; video_np = (cropped_tensor[0].permute(1, 2, 3, 0).cpu().float().numpy() * 255).astype(np.uint8)
|
| 106 |
+
|
| 107 |
+
with imageio.get_writer(output_path, fps=VIDEO_FPS, codec='libx264', quality=8) as writer:
|
| 108 |
+
for i, frame in enumerate(video_np):
|
| 109 |
+
progress(i / len(video_np), desc=f"Renderizando frame {i+1}/{len(video_np)}...");
|
| 110 |
+
writer.append_data(frame)
|
| 111 |
+
|
| 112 |
+
return output_path, actual_num_frames
|
| 113 |
+
except Exception as e:
|
| 114 |
+
raise e
|
| 115 |
+
|
| 116 |
+
def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
|
| 117 |
+
if not os.path.exists(input_path):
|
| 118 |
+
raise gr.Error(f"Erro Interno: Vídeo de entrada para corte não encontrado: {input_path}")
|
| 119 |
+
try:
|
| 120 |
+
trim_cmd = (f"ffmpeg -y -v error -i \"{input_path}\" -vf \"select='lt(n,{frames_to_keep})'\" -an \"{output_path}\"")
|
| 121 |
+
subprocess.run(trim_cmd, shell=True, check=True, capture_output=True, text=True)
|
| 122 |
+
return output_path
|
| 123 |
+
except subprocess.CalledProcessError as e:
|
| 124 |
+
error_message = f"Editor Mágico (FFmpeg) falhou ao cortar o vídeo para {frames_to_keep} frames: {e}"
|
| 125 |
+
if hasattr(e, 'stderr'): error_message += f"\nDetalhes: {e.stderr}"
|
| 126 |
+
raise gr.Error(error_message)
|
| 127 |
+
|
| 128 |
+
def extract_last_frame_as_image(video_path: str, output_image_path: str) -> str:
|
| 129 |
+
if not os.path.exists(video_path):
|
| 130 |
+
raise gr.Error(f"Erro Interno: Vídeo de entrada para extração de frame não encontrado: {video_path}")
|
| 131 |
+
try:
|
| 132 |
+
command = (f"ffmpeg -y -v error -sseof -1 -i \"{video_path}\" -update 1 -q:v 1 \"{output_image_path}\"")
|
| 133 |
+
subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
|
| 134 |
+
return output_image_path
|
| 135 |
+
except subprocess.CalledProcessError as e:
|
| 136 |
+
error_message = f"Editor Mágico (FFmpeg) falhou ao extrair o último frame: {e}"
|
| 137 |
+
if hasattr(e, 'stderr'): error_message += f"\nDetalhes: {e.stderr}"
|
| 138 |
+
raise gr.Error(error_message)
|
| 139 |
+
|
| 140 |
+
def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
|
| 141 |
+
if not image_path or not os.path.exists(image_path): return None
|
| 142 |
+
try:
|
| 143 |
+
img = Image.open(image_path).convert("RGB")
|
| 144 |
+
img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
|
| 145 |
+
output_filename = f"initial_ref_{size}x{size}.png"
|
| 146 |
+
output_path = os.path.join(WORKSPACE_DIR, output_filename)
|
| 147 |
+
img_square.save(output_path)
|
| 148 |
+
return output_path
|
| 149 |
+
except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
|
| 150 |
+
|
| 151 |
+
def get_static_scenes_storyboard(num_fragments: int, prompt: str, initial_image_path: str):
|
| 152 |
+
if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
|
| 153 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 154 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 155 |
+
prompt_file = "prompts/photographer_prompt.txt"
|
| 156 |
+
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 157 |
+
director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments))
|
| 158 |
+
model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(initial_image_path)
|
| 159 |
+
response = model.generate_content([director_prompt, img])
|
| 160 |
+
try:
|
| 161 |
+
cleaned_response = response.text.strip().replace("```json", "").replace("```", "")
|
| 162 |
+
storyboard_data = json.loads(cleaned_response)
|
| 163 |
+
return storyboard_data.get("scene_storyboard", [])
|
| 164 |
+
except Exception as e: raise gr.Error(f"O Sonhador (Gemini) falhou ao criar o roteiro: {e}. Resposta: {response.text}")
|
| 165 |
+
|
| 166 |
+
def run_keyframe_generation(storyboard, initial_ref_image_path, sequential_ref_task):
|
| 167 |
+
if not storyboard: raise gr.Error("Nenhum roteiro para gerar imagens-chave.")
|
| 168 |
+
if not initial_ref_image_path or not os.path.exists(initial_ref_image_path): raise gr.Error("A imagem de referência principal é obrigatória.")
|
| 169 |
+
log_history = ""
|
| 170 |
+
try:
|
| 171 |
+
print("Pintor (DreamO): Movendo a Câmera (LTX) para a CPU para liberar VRAM...")
|
| 172 |
+
pipeline_instance.to('cpu')
|
| 173 |
+
gc.collect()
|
| 174 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 175 |
+
print("Pintor (DreamO): VRAM liberada. Movendo o Pintor para a GPU...")
|
| 176 |
+
dreamo_generator_singleton.to_gpu()
|
| 177 |
+
with Image.open(initial_ref_image_path) as img:
|
| 178 |
+
width, height = img.size
|
| 179 |
+
width, height = (width // 32) * 32, (height // 32) * 32
|
| 180 |
+
keyframe_paths, current_ref_image_path = [], initial_ref_image_path
|
| 181 |
+
for i, prompt in enumerate(storyboard):
|
| 182 |
+
log_history += f"\nPintando Cena {i+1}/{len(storyboard)}...\n"
|
| 183 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
|
| 184 |
+
reference_items_for_dreamo = [{'image_np': np.array(Image.open(current_ref_image_path).convert("RGB")), 'task': sequential_ref_task}]
|
| 185 |
+
log_history += f" - Usando referência: {os.path.basename(current_ref_image_path)} (Tarefa: {sequential_ref_task})\n"
|
| 186 |
+
output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
|
| 187 |
+
image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=reference_items_for_dreamo, prompt=prompt, width=width, height=height)
|
| 188 |
+
image.save(output_path)
|
| 189 |
+
keyframe_paths.append(output_path)
|
| 190 |
+
current_ref_image_path = output_path
|
| 191 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
|
| 192 |
+
except Exception as e:
|
| 193 |
+
raise gr.Error(f"O Pintor (DreamO) encontrou um erro: {e}")
|
| 194 |
+
finally:
|
| 195 |
+
print("Pintor (DreamO): Trabalho concluído. Movendo o Pintor de volta para a CPU.")
|
| 196 |
+
dreamo_generator_singleton.to_cpu()
|
| 197 |
+
gc.collect()
|
| 198 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 199 |
+
log_history += "\nPintura de todos os keyframes concluída.\n"
|
| 200 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths), keyframe_images_state: keyframe_paths}
|
| 201 |
+
|
| 202 |
+
def get_single_motion_prompt(user_prompt: str, story_history: str, start_image_path: str, middle_image_path: str, end_image_path: str):
|
| 203 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 204 |
+
try:
|
| 205 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 206 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 207 |
+
start_img, middle_img, end_img = Image.open(start_image_path), Image.open(middle_image_path), Image.open(end_image_path)
|
| 208 |
+
prompt_file_path = os.path.join(os.path.dirname(__file__), "prompts", "director_motion_prompt_three_act.txt")
|
| 209 |
+
with open(prompt_file_path, "r", encoding="utf-8") as f:
|
| 210 |
+
template = f.read()
|
| 211 |
+
director_prompt = template.format(user_prompt=user_prompt, story_history=story_history)
|
| 212 |
+
model_contents = [director_prompt, "INÍCIO:", start_img, "MEIO:", middle_img, "FIM:", end_img]
|
| 213 |
+
response = model.generate_content(model_contents)
|
| 214 |
+
cleaned_text = response.text.strip()
|
| 215 |
+
if cleaned_text.startswith("```json"): cleaned_text = cleaned_text[len("```json"):].strip()
|
| 216 |
+
if cleaned_text.endswith("```"): cleaned_text = cleaned_text[:-len("```")].strip()
|
| 217 |
+
try:
|
| 218 |
+
motion_data = json.loads(cleaned_text)
|
| 219 |
+
final_prompt = motion_data.get("motion_prompt", "")
|
| 220 |
+
if not final_prompt: raise ValueError("Prompt de movimento vazio no JSON.")
|
| 221 |
+
return final_prompt
|
| 222 |
+
except (json.JSONDecodeError, ValueError):
|
| 223 |
+
return cleaned_text.replace("\"", "").replace("{", "").replace("}", "").replace("motion_prompt:", "").strip()
|
| 224 |
+
except Exception as e:
|
| 225 |
+
response_text = getattr(e, 'text', 'Nenhuma resposta de texto disponível.')
|
| 226 |
+
raise gr.Error(f"O Cineasta (Gemini) falhou ao criar o prompt de movimento de 3 atos: {e}. Resposta: {response_text}")
|
| 227 |
+
|
| 228 |
+
def run_video_production(prompt_geral, keyframe_images_state, scene_storyboard, seed, cfg, cut_frames_value, progress=gr.Progress()):
|
| 229 |
+
if not keyframe_images_state or len(keyframe_images_state) < 2:
|
| 230 |
+
raise gr.Error("Pinte pelo menos 2 keyframes na Etapa 2 para produzir as transições.")
|
| 231 |
+
log_history = "\n--- FASE 3/4: A Câmera e o Cineasta estão filmando em sequência just-in-time...\n"
|
| 232 |
+
yield {production_log_output: log_history, video_gallery_glitch: []}
|
| 233 |
+
target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 234 |
+
try:
|
| 235 |
+
print(f"Câmera (LTX): Movendo para a {target_device} para a produção em lote.")
|
| 236 |
+
pipeline_instance.to(target_device)
|
| 237 |
+
if target_device == 'cuda':
|
| 238 |
+
if hasattr(pipeline_instance, 'disable_model_cpu_offload'): pipeline_instance.disable_model_cpu_offload()
|
| 239 |
+
if hasattr(pipeline_instance, 'disable_attention_slicing'): pipeline_instance.disable_attention_slicing()
|
| 240 |
+
if hasattr(pipeline_instance.vae, 'disable_slicing'): pipeline_instance.vae.disable_slicing()
|
| 241 |
+
if hasattr(pipeline_instance.vae, 'disable_z_tiling'): pipeline_instance.vae.disable_z_tiling()
|
| 242 |
+
video_fragments, story_history = [], ""
|
| 243 |
+
previous_fragment_last_frame_path = keyframe_images_state[0]
|
| 244 |
+
with Image.open(keyframe_images_state[0]) as img: width, height = img.size
|
| 245 |
+
num_transitions = len(keyframe_images_state) - 1
|
| 246 |
+
for i in range(num_transitions):
|
| 247 |
+
start_image_path = previous_fragment_last_frame_path
|
| 248 |
+
middle_image_path = keyframe_images_state[i]
|
| 249 |
+
end_image_path = keyframe_images_state[i+1]
|
| 250 |
+
fragment_num = i + 1
|
| 251 |
+
is_last_fragment = (i == num_transitions - 1)
|
| 252 |
+
progress(i / num_transitions, desc=f"Planejando e Filmando Fragmento {fragment_num}/{num_transitions}")
|
| 253 |
+
log_history += f"\n--- FRAGMENTO {fragment_num} ---\n"
|
| 254 |
+
story_history += f"\n- Transição de '{scene_storyboard[i]}' para '{scene_storyboard[i+1]}'."
|
| 255 |
+
current_motion_prompt = get_single_motion_prompt(prompt_geral, story_history, start_image_path, middle_image_path, end_image_path)
|
| 256 |
+
log_history += f"Instrução do Cineasta (3 Atos): '{current_motion_prompt}'\n"
|
| 257 |
+
yield {production_log_output: log_history}
|
| 258 |
+
foreshadow_frame, foreshadow_strength = 54, 0.3
|
| 259 |
+
end_frame_index = VIDEO_TOTAL_FRAMES - CONVERGENCE_FRAMES
|
| 260 |
+
conditioning_items_data = [(start_image_path, 0, 1.0), (end_image_path, foreshadow_frame, foreshadow_strength), (end_image_path, end_frame_index, 1.0)]
|
| 261 |
+
full_fragment_path, frames_gerados = run_ltx_animation(fragment_num, current_motion_prompt, conditioning_items_data, width, height, seed, cfg, progress)
|
| 262 |
+
log_history += f" - Gerado: {frames_gerados} frames\n"
|
| 263 |
+
if not is_last_fragment:
|
| 264 |
+
cut_frames = int(cut_frames_value)
|
| 265 |
+
final_fragment_path = os.path.join(WORKSPACE_DIR, f"fragment_{fragment_num}_final_{cut_frames}f.mp4")
|
| 266 |
+
trim_video_to_frames(full_fragment_path, final_fragment_path, cut_frames)
|
| 267 |
+
output_frame_path = os.path.join(WORKSPACE_DIR, f"last_frame_of_frag_{fragment_num}.png")
|
| 268 |
+
previous_fragment_last_frame_path = extract_last_frame_as_image(final_fragment_path, output_frame_path)
|
| 269 |
+
log_history += f" - Cortado para: {cut_frames} frames\n"
|
| 270 |
+
log_history += f" - Memória para próxima cena: Último frame extraído\n"
|
| 271 |
+
else:
|
| 272 |
+
final_fragment_path = full_fragment_path
|
| 273 |
+
log_history += f" - Último fragmento, mantendo duração total: {frames_gerados} frames\n"
|
| 274 |
+
video_fragments.append(final_fragment_path)
|
| 275 |
+
yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
|
| 276 |
+
log_history += "\nFilmagem de todos os fragmentos de transição concluída.\n"
|
| 277 |
+
progress(1.0, desc="Produção Concluída.")
|
| 278 |
+
yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
|
| 279 |
+
finally:
|
| 280 |
+
print(f"Câmera (LTX): Produção em lote concluída. Movendo para a CPU para liberar VRAM.")
|
| 281 |
+
pipeline_instance.to('cpu')
|
| 282 |
+
gc.collect()
|
| 283 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 284 |
+
|
| 285 |
+
def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
|
| 286 |
+
if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
|
| 287 |
+
progress(0.5, desc="Montando a obra-prima final...")
|
| 288 |
+
try:
|
| 289 |
+
list_file_path, final_output_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"), os.path.join(WORKSPACE_DIR, "obra_prima_final.mp4")
|
| 290 |
+
with open(list_file_path, "w") as f:
|
| 291 |
+
for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
|
| 292 |
+
concat_cmd = f"ffmpeg -y -v error -f concat -safe 0 -i \"{list_file_path}\" -c copy \"{final_output_path}\""
|
| 293 |
+
subprocess.run(concat_cmd, shell=True, check=True, capture_output=True, text=True)
|
| 294 |
+
progress(1.0, desc="Montagem concluída!")
|
| 295 |
+
return final_output_path
|
| 296 |
+
except (subprocess.CalledProcessError, ValueError) as e:
|
| 297 |
+
error_message = f"FFmpeg falhou durante a concatenação final: {e}"
|
| 298 |
+
if hasattr(e, 'stderr'): error_message += f"\nDetalhes do erro do FFmpeg: {e.stderr}"
|
| 299 |
+
raise gr.Error(error_message)
|
| 300 |
+
|
| 301 |
+
# --- Ato 5: A Interface com o Mundo (A UI Restaurada e Aprimorada) ---
|
| 302 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 303 |
+
gr.Markdown("# NOVINHO-4.2 (Piloto de Testes - Arquitetura 'Memória, Caminho, Destino')\n*By Carlex & Gemini & DreamO*")
|
| 304 |
+
|
| 305 |
+
if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
|
| 306 |
+
os.makedirs(WORKSPACE_DIR)
|
| 307 |
+
Path("examples").mkdir(exist_ok=True)
|
| 308 |
+
|
| 309 |
+
scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
|
| 310 |
+
prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
|
| 311 |
+
|
| 312 |
+
gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (Sonhador)")
|
| 313 |
+
with gr.Row():
|
| 314 |
+
with gr.Column(scale=1):
|
| 315 |
+
prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
|
| 316 |
+
num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Cenas")
|
| 317 |
+
image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
|
| 318 |
+
director_button = gr.Button("▶️ 1. Gerar Roteiro de Cenas", variant="primary")
|
| 319 |
+
with gr.Column(scale=2): storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado")
|
| 320 |
+
|
| 321 |
+
gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (Pintor)")
|
| 322 |
+
with gr.Row():
|
| 323 |
+
with gr.Column(scale=2):
|
| 324 |
+
gr.Markdown("### Controles do Pintor (DreamO)\n**Tarefas:** `style` (estilo), `ip` (conteúdo), `id` (identidade).")
|
| 325 |
+
ref_image_inputs, ref_task_inputs = [], []
|
| 326 |
+
with gr.Group():
|
| 327 |
+
with gr.Row():
|
| 328 |
+
ref_image_inputs.append(gr.Image(label="Referência Inicial / Sequencial (Automática)", type="filepath", interactive=False))
|
| 329 |
+
ref_task_inputs.append(gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Referência"))
|
| 330 |
+
photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
|
| 331 |
+
with gr.Column(scale=1):
|
| 332 |
+
keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
|
| 333 |
+
keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
|
| 334 |
+
|
| 335 |
+
gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (Cineasta e Câmera)")
|
| 336 |
+
with gr.Row():
|
| 337 |
+
with gr.Column(scale=1):
|
| 338 |
+
with gr.Row():
|
| 339 |
+
seed_number = gr.Number(42, label="Seed")
|
| 340 |
+
cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
|
| 341 |
+
cut_frames_slider = gr.Slider(label="Duração do Fragmento (Frames)", minimum=36, maximum=VIDEO_TOTAL_FRAMES, value=90, step=1)
|
| 342 |
+
animator_button = gr.Button("▶️ 3. Produzir Cenas em Vídeo", variant="primary")
|
| 343 |
+
production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=15, interactive=False)
|
| 344 |
+
with gr.Column(scale=1): video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
|
| 345 |
+
|
| 346 |
+
gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
|
| 347 |
+
editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
|
| 348 |
+
final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
|
| 349 |
+
|
| 350 |
+
gr.Markdown(
|
| 351 |
+
"""
|
| 352 |
+
---
|
| 353 |
+
### A Arquitetura "Memória, Caminho, Destino"
|
| 354 |
+
Nossa geração de vídeo é governada por uma orquestração de IAs, onde cada fragmento (`V_i`) é criado com base em três pilares:
|
| 355 |
+
|
| 356 |
+
* **Memória (`M_(i-1)`):** O último frame do fragmento anterior. Garante a **continuidade** visual.
|
| 357 |
+
* **Caminho (`Γ_i`):** Uma instrução de movimento gerada pelo "Cineasta" (Gemini) ao analisar a Memória, o Keyframe atual e o Destino. Define a **narrativa** da transição.
|
| 358 |
+
* **Destino (`K_(i+1)`):** O próximo keyframe a ser alcançado. Define o **objetivo** da animação.
|
| 359 |
+
|
| 360 |
+
A Câmera (LTX) recebe esses três elementos para construir cada cena, resultando em um vídeo coeso e com propósito.
|
| 361 |
+
"""
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# --- Ato 6: A Regência (Lógica de Conexão dos Botões) ---
|
| 365 |
+
director_button.click(
|
| 366 |
+
fn=get_static_scenes_storyboard,
|
| 367 |
+
inputs=[num_fragments_input, prompt_input, image_input],
|
| 368 |
+
outputs=[scene_storyboard_state]
|
| 369 |
+
).success(
|
| 370 |
+
fn=lambda s, p: (s, p),
|
| 371 |
+
inputs=[scene_storyboard_state, prompt_input],
|
| 372 |
+
outputs=[storyboard_to_show, prompt_geral_state]
|
| 373 |
+
).success(
|
| 374 |
+
fn=process_image_to_square,
|
| 375 |
+
inputs=[image_input],
|
| 376 |
+
outputs=[processed_ref_path_state]
|
| 377 |
+
).success(
|
| 378 |
+
fn=lambda p: p,
|
| 379 |
+
inputs=[processed_ref_path_state],
|
| 380 |
+
outputs=[ref_image_inputs[0]]
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
photographer_button.click(
|
| 384 |
+
fn=run_keyframe_generation,
|
| 385 |
+
inputs=[scene_storyboard_state, processed_ref_path_state, ref_task_inputs[0]],
|
| 386 |
+
outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
animator_button.click(
|
| 390 |
+
fn=run_video_production,
|
| 391 |
+
inputs=[prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider, cut_frames_slider],
|
| 392 |
+
outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
editor_button.click(
|
| 396 |
+
fn=concatenate_and_trim_masterpiece,
|
| 397 |
+
inputs=[fragment_list_state],
|
| 398 |
+
outputs=[final_video_output]
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
if __name__ == "__main__":
|
| 402 |
+
demo.queue().launch(server_name="0.0.0.0", share=True)
|