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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.7: Arquitetura Otimizada com Handoff Cinético) ---
|
| 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, ExifTags
|
| 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 = 24
|
| 60 |
+
VIDEO_DURATION_SECONDS = 4
|
| 61 |
+
VIDEO_TOTAL_FRAMES = VIDEO_DURATION_SECONDS * VIDEO_FPS
|
| 62 |
+
TARGET_RESOLUTION = 720
|
| 63 |
+
|
| 64 |
+
print("Criando pipelines LTX na CPU (estado de repouso)...")
|
| 65 |
+
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)
|
| 66 |
+
pipeline_instance = create_ltx_video_pipeline(
|
| 67 |
+
ckpt_path=distilled_model_actual_path,
|
| 68 |
+
precision=PIPELINE_CONFIG_YAML["precision"],
|
| 69 |
+
text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
|
| 70 |
+
sampler=PIPELINE_CONFIG_YAML["sampler"],
|
| 71 |
+
device='cpu'
|
| 72 |
+
)
|
| 73 |
+
print("Modelos LTX prontos (na CPU).")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
|
| 77 |
+
|
| 78 |
+
# --- Funções da ETAPA 1 (Roteiro) - Otimizadas para uma única chamada de IA ---
|
| 79 |
+
def robust_json_parser(raw_text: str) -> dict:
|
| 80 |
+
"""Um parser robusto que encontra e decodifica o primeiro objeto JSON válido em uma string."""
|
| 81 |
+
try:
|
| 82 |
+
start_index = raw_text.find('{')
|
| 83 |
+
end_index = raw_text.rfind('}')
|
| 84 |
+
if start_index != -1 and end_index != -1 and end_index > start_index:
|
| 85 |
+
json_str = raw_text[start_index : end_index + 1]
|
| 86 |
+
return json.loads(json_str)
|
| 87 |
+
else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
|
| 88 |
+
except json.JSONDecodeError as e:
|
| 89 |
+
raise ValueError(f"Falha ao decodificar JSON: {e}")
|
| 90 |
+
|
| 91 |
+
def extract_image_exif(image_path: str) -> str:
|
| 92 |
+
"""Extrai metadados EXIF de uma imagem e os formata como uma string."""
|
| 93 |
+
try:
|
| 94 |
+
img = Image.open(image_path); exif_data = img._getexif()
|
| 95 |
+
if not exif_data: return "No EXIF metadata found."
|
| 96 |
+
exif = { ExifTags.TAGS[k]: v for k, v in exif_data.items() if k in ExifTags.TAGS }
|
| 97 |
+
relevant_tags = ['DateTimeOriginal', 'Model', 'LensModel', 'FNumber', 'ExposureTime', 'ISOSpeedRatings', 'FocalLength']
|
| 98 |
+
metadata_str = ", ".join(f"{key}: {exif[key]}" for key in relevant_tags if key in exif)
|
| 99 |
+
return metadata_str if metadata_str else "No relevant EXIF metadata found."
|
| 100 |
+
except Exception: return "Could not read EXIF data."
|
| 101 |
+
|
| 102 |
+
def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
|
| 103 |
+
"""Orquestra a geração do roteiro em UMA ÚNICA ETAPA, combinando análise de visão e criação de roteiro."""
|
| 104 |
+
if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
|
| 105 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 106 |
+
|
| 107 |
+
exif_metadata = extract_image_exif(initial_image_path)
|
| 108 |
+
prompt_file = "prompts/unified_storyboard_prompt.txt"
|
| 109 |
+
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 110 |
+
director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata=exif_metadata)
|
| 111 |
+
|
| 112 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 113 |
+
model = genai.GenerativeModel('gemini-pro-vision')
|
| 114 |
+
img = Image.open(initial_image_path)
|
| 115 |
+
print("Gerando roteiro com análise de visão integrada...")
|
| 116 |
+
response = model.generate_content([director_prompt, img])
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
storyboard_data = robust_json_parser(response.text)
|
| 120 |
+
storyboard = storyboard_data.get("scene_storyboard", [])
|
| 121 |
+
if not storyboard or len(storyboard) != int(num_fragments):
|
| 122 |
+
raise ValueError(f"A IA não gerou o número correto de cenas. Esperado: {num_fragments}, Recebido: {len(storyboard)}")
|
| 123 |
+
return storyboard
|
| 124 |
+
except Exception as e:
|
| 125 |
+
raise gr.Error(f"O Roteirista (Gemini) falhou ao criar o roteiro: {e}. Resposta recebida: {response.text}")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# --- Funções da ETAPA 2 (Keyframes) ---
|
| 129 |
+
def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
|
| 130 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 131 |
+
prompt_file = "prompts/img2img_evolution_prompt.txt"
|
| 132 |
+
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 133 |
+
director_prompt = template.format(target_scene_description=target_scene_description)
|
| 134 |
+
model = genai.GenerativeModel('gemini-pro-vision'); img = Image.open(previous_image_path)
|
| 135 |
+
response = model.generate_content([director_prompt, "Previous Image:", img])
|
| 136 |
+
return response.text.strip().replace("\"", "")
|
| 137 |
+
|
| 138 |
+
def run_keyframe_generation(storyboard, initial_ref_image_path, sequential_ref_task, progress=gr.Progress()):
|
| 139 |
+
if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
|
| 140 |
+
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.")
|
| 141 |
+
log_history = ""
|
| 142 |
+
try:
|
| 143 |
+
pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
|
| 144 |
+
dreamo_generator_singleton.to_gpu()
|
| 145 |
+
with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
|
| 146 |
+
keyframe_paths, current_ref_image_path = [initial_ref_image_path], initial_ref_image_path
|
| 147 |
+
for i, scene_description in enumerate(storyboard):
|
| 148 |
+
progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
|
| 149 |
+
log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
|
| 150 |
+
dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
|
| 151 |
+
log_history += f" - Roteiro: '{scene_description}'\n - Base: {os.path.basename(current_ref_image_path)}\n - Prompt do D.A.: \"{dreamo_prompt}\"\n"
|
| 152 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
|
| 153 |
+
reference_items = [{'image_np': np.array(Image.open(current_ref_image_path).convert("RGB")), 'task': sequential_ref_task}]
|
| 154 |
+
output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
|
| 155 |
+
image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=reference_items, prompt=dreamo_prompt, width=width, height=height)
|
| 156 |
+
image.save(output_path)
|
| 157 |
+
keyframe_paths.append(output_path)
|
| 158 |
+
current_ref_image_path = output_path
|
| 159 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
|
| 160 |
+
except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
|
| 161 |
+
finally:
|
| 162 |
+
dreamo_generator_singleton.to_cpu(); gc.collect(); torch.cuda.empty_cache()
|
| 163 |
+
log_history += "\nPintura de todos os keyframes concluída.\n"
|
| 164 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths), keyframe_images_state: keyframe_paths}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# --- Funções da ETAPA 3 (Produção de Vídeo) ---
|
| 168 |
+
def get_dynamic_motion_prompt(user_prompt: str, story_history: str, memory_image_path: str, path_image_path: str, destination_image_path: str, path_scene_desc: str, dest_scene_desc: str):
|
| 169 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 170 |
+
try:
|
| 171 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 172 |
+
model = genai.GenerativeModel('gemini-pro-vision')
|
| 173 |
+
prompt_file = "prompts/dynamic_motion_prompt.txt"
|
| 174 |
+
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 175 |
+
cinematographer_prompt = template.format(user_prompt=user_prompt, story_history=story_history, midpoint_scene_description=path_scene_desc, destination_scene_description=dest_scene_desc)
|
| 176 |
+
mem_img, path_img, dest_img = Image.open(memory_image_path), Image.open(path_image_path), Image.open(destination_image_path)
|
| 177 |
+
model_contents = ["START Image (Memory):", mem_img, "MIDPOINT Image (Path):", path_img, "DESTINATION Image (Destination):", dest_img, cinematographer_prompt]
|
| 178 |
+
response = model.generate_content(model_contents)
|
| 179 |
+
return response.text.strip()
|
| 180 |
+
except Exception as e:
|
| 181 |
+
raise gr.Error(f"O Cineasta de IA (Gemini) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
|
| 182 |
+
|
| 183 |
+
def run_video_production(prompt_geral, keyframe_images_state, scene_storyboard, seed, cfg, cut_frames_value, progress=gr.Progress()):
|
| 184 |
+
if not keyframe_images_state or len(keyframe_images_state) < 2: raise gr.Error("Pinte pelo menos um keyframe (para um total de 2+ imagens) na Etapa 2.")
|
| 185 |
+
log_history = "\n--- FASE 3/4: Iniciando Produção com 'Handoff Cinético'...\n"
|
| 186 |
+
yield {production_log_output: log_history, video_gallery_glitch: []}
|
| 187 |
+
|
| 188 |
+
MID_COND_FRAME, MID_COND_STRENGTH = 54, 0.5
|
| 189 |
+
END_COND_FRAME = VIDEO_TOTAL_FRAMES - 8
|
| 190 |
+
|
| 191 |
+
target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 192 |
+
try:
|
| 193 |
+
pipeline_instance.to(target_device)
|
| 194 |
+
video_fragments, story_history = [], ""
|
| 195 |
+
kinetic_memory_path = keyframe_images_state[0]
|
| 196 |
+
with Image.open(keyframe_images_state[0]) as img: width, height = img.size
|
| 197 |
+
|
| 198 |
+
num_transitions = len(keyframe_images_state) - 1
|
| 199 |
+
for i in range(num_transitions):
|
| 200 |
+
fragment_num = i + 1
|
| 201 |
+
progress(i / num_transitions, desc=f"Filmando Fragmento {fragment_num}/{num_transitions}")
|
| 202 |
+
|
| 203 |
+
memory_path, path_path, destination_path = kinetic_memory_path, keyframe_images_state[i], keyframe_images_state[i+1]
|
| 204 |
+
path_scene_desc = scene_storyboard[i]
|
| 205 |
+
dest_scene_desc = scene_storyboard[i+1] if (i+1) < len(scene_storyboard) else "Final scene"
|
| 206 |
+
|
| 207 |
+
log_history += f"\n--- FRAGMENTO {fragment_num} ---\n - Memória Cinética: {os.path.basename(memory_path)}\n - Caminho: {os.path.basename(path_path)}\n - Destino: {os.path.basename(destination_path)}\n"
|
| 208 |
+
current_motion_prompt = get_dynamic_motion_prompt(prompt_geral, story_history, memory_path, path_path, destination_path, path_scene_desc, dest_scene_desc)
|
| 209 |
+
story_history += f"\n- Ato {fragment_num}: {current_motion_prompt}"
|
| 210 |
+
log_history += f" - Instrução do Cineasta: '{current_motion_prompt}'\n"; yield {production_log_output: log_history}
|
| 211 |
+
|
| 212 |
+
if i == 0:
|
| 213 |
+
conditioning_items_data = [(memory_path, 0, 1.0), (destination_path, END_COND_FRAME, 1.0)]
|
| 214 |
+
else:
|
| 215 |
+
conditioning_items_data = [(memory_path, 0, 1.0), (path_path, MID_COND_FRAME, MID_COND_STRENGTH), (destination_path, END_COND_FRAME, 1.0)]
|
| 216 |
+
|
| 217 |
+
full_fragment_path, _ = run_ltx_animation(fragment_num, current_motion_prompt, conditioning_items_data, width, height, seed, cfg, progress)
|
| 218 |
+
|
| 219 |
+
is_last_fragment = (i == num_transitions - 1)
|
| 220 |
+
if not is_last_fragment:
|
| 221 |
+
trimmed_fragment_path = os.path.join(WORKSPACE_DIR, f"fragment_{fragment_num}_trimmed.mp4")
|
| 222 |
+
trim_video_to_frames(full_fragment_path, trimmed_fragment_path, int(cut_frames_value))
|
| 223 |
+
eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_from_frag_{fragment_num}.png")
|
| 224 |
+
kinetic_memory_path = extract_last_frame_as_image(trimmed_fragment_path, eco_output_path)
|
| 225 |
+
video_fragments.append(trimmed_fragment_path)
|
| 226 |
+
log_history += f" - Gerado e cortado. Novo Eco Dinâmico: {os.path.basename(kinetic_memory_path)}\n"
|
| 227 |
+
else:
|
| 228 |
+
video_fragments.append(full_fragment_path)
|
| 229 |
+
log_history += " - Último fragmento gerado, mantendo a duração total.\n"
|
| 230 |
+
yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
|
| 231 |
+
|
| 232 |
+
progress(1.0, desc="Produção Concluída.")
|
| 233 |
+
yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
|
| 234 |
+
finally:
|
| 235 |
+
pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
|
| 236 |
+
|
| 237 |
+
# --- Funções Utilitárias e de Pós-Produção ---
|
| 238 |
+
def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
|
| 239 |
+
if not image_path or not os.path.exists(image_path): return None
|
| 240 |
+
try:
|
| 241 |
+
img = Image.open(image_path).convert("RGB"); img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
|
| 242 |
+
output_path = os.path.join(WORKSPACE_DIR, f"initial_ref_{size}x{size}.png"); img_square.save(output_path)
|
| 243 |
+
return output_path
|
| 244 |
+
except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
|
| 245 |
+
|
| 246 |
+
def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
|
| 247 |
+
return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
|
| 248 |
+
|
| 249 |
+
def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg, progress=gr.Progress()):
|
| 250 |
+
progress(0, desc=f"[Câmera LTX] Filmando Cena {current_fragment_index}...");
|
| 251 |
+
output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4"); target_device = pipeline_instance.device
|
| 252 |
+
conditioning_items = [ConditioningItem(load_conditioning_tensor(p, height, width).to(target_device), s, t) for p, s, t in conditioning_items_data]
|
| 253 |
+
actual_num_frames = int(round((float(VIDEO_TOTAL_FRAMES) - 1.0) / 8.0) * 8 + 1)
|
| 254 |
+
padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
|
| 255 |
+
padding_vals = calculate_padding(height, width, padded_h, padded_w)
|
| 256 |
+
for item in conditioning_items: item.media_item = torch.nn.functional.pad(item.media_item, padding_vals)
|
| 257 |
+
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": 4}
|
| 258 |
+
result_tensor = pipeline_instance(**kwargs).images
|
| 259 |
+
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
|
| 260 |
+
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)
|
| 261 |
+
with imageio.get_writer(output_path, fps=VIDEO_FPS, codec='libx264', quality=8) as writer:
|
| 262 |
+
for i, frame in enumerate(video_np): writer.append_data(frame)
|
| 263 |
+
return output_path, actual_num_frames
|
| 264 |
+
|
| 265 |
+
def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
|
| 266 |
+
try:
|
| 267 |
+
subprocess.run(f"ffmpeg -y -v error -i \"{input_path}\" -vf \"select='lt(n,{frames_to_keep})'\" -an \"{output_path}\"", shell=True, check=True, text=True)
|
| 268 |
+
return output_path
|
| 269 |
+
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao cortar vídeo: {e.stderr}")
|
| 270 |
+
|
| 271 |
+
def extract_last_frame_as_image(video_path: str, output_image_path: str) -> str:
|
| 272 |
+
try:
|
| 273 |
+
subprocess.run(f"ffmpeg -y -v error -sseof -1 -i \"{video_path}\" -update 1 -q:v 1 \"{output_image_path}\"", shell=True, check=True, text=True)
|
| 274 |
+
return output_image_path
|
| 275 |
+
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao extrair último frame: {e.stderr}")
|
| 276 |
+
|
| 277 |
+
def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
|
| 278 |
+
if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
|
| 279 |
+
progress(0.5, desc="Montando a obra-prima final...");
|
| 280 |
+
try:
|
| 281 |
+
list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
|
| 282 |
+
with open(list_file_path, "w") as f:
|
| 283 |
+
for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
|
| 284 |
+
subprocess.run(f"ffmpeg -y -v error -f concat -safe 0 -i \"{list_file_path}\" -c copy \"{final_output_path}\"", shell=True, check=True, text=True)
|
| 285 |
+
progress(1.0, desc="Montagem concluída!")
|
| 286 |
+
return final_output_path
|
| 287 |
+
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
|
| 288 |
+
|
| 289 |
+
# --- Ato 5: A Interface com o Mundo (UI) ---
|
| 290 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 291 |
+
gr.Markdown("# NOVINHO-4.7 (Arquitetura Otimizada com Handoff Cinético)\n*By Carlex & Gemini & DreamO*")
|
| 292 |
+
|
| 293 |
+
if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
|
| 294 |
+
os.makedirs(WORKSPACE_DIR); Path("prompts").mkdir(exist_ok=True)
|
| 295 |
+
|
| 296 |
+
scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
|
| 297 |
+
prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
|
| 298 |
+
|
| 299 |
+
gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
|
| 300 |
+
with gr.Row():
|
| 301 |
+
with gr.Column(scale=1):
|
| 302 |
+
prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
|
| 303 |
+
num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Atos (Keyframes)")
|
| 304 |
+
image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
|
| 305 |
+
director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
|
| 306 |
+
with gr.Column(scale=2): storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado (em Inglês)")
|
| 307 |
+
|
| 308 |
+
gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
|
| 309 |
+
with gr.Row():
|
| 310 |
+
with gr.Column(scale=2):
|
| 311 |
+
gr.Markdown("O Diretor de Arte (IA) gerará prompts dinamicamente para cada Keyframe.")
|
| 312 |
+
with gr.Group():
|
| 313 |
+
with gr.Row():
|
| 314 |
+
ref_image_inputs_auto = gr.Image(label="Referência Sequencial (Automática)", type="filepath", interactive=False)
|
| 315 |
+
ref_task_input = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Referência")
|
| 316 |
+
photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
|
| 317 |
+
with gr.Column(scale=1):
|
| 318 |
+
keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
|
| 319 |
+
keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
|
| 320 |
+
|
| 321 |
+
gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
|
| 322 |
+
with gr.Row():
|
| 323 |
+
with gr.Column(scale=1):
|
| 324 |
+
with gr.Row(): seed_number = gr.Number(42, label="Seed"); cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
|
| 325 |
+
cut_frames_slider = gr.Slider(label="Duração do Fragmento (Frames)", minimum=36, maximum=VIDEO_TOTAL_FRAMES, value=72, step=1)
|
| 326 |
+
animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
|
| 327 |
+
production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=15, interactive=False)
|
| 328 |
+
with gr.Column(scale=1): video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
|
| 329 |
+
|
| 330 |
+
gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (IA Editor)")
|
| 331 |
+
editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
|
| 332 |
+
final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
|
| 333 |
+
|
| 334 |
+
gr.Markdown(
|
| 335 |
+
"""
|
| 336 |
+
---
|
| 337 |
+
### A Arquitetura: Handoff Cinético
|
| 338 |
+
Nossa arquitetura é inspirada no conceito de "Handoff" da engenharia, como em uma corrida de revezamento. Cada fragmento de vídeo passa o "bastão" para o próximo de forma fluida, garantindo um movimento contínuo e ininterrupto.
|
| 339 |
+
|
| 340 |
+
* **O Bastão (O `Eco`):** Em vez de terminar em uma imagem estática, cada fragmento é cortado enquanto ainda está em movimento. O último frame deste clipe cortado, o `Eco`, carrega a "energia cinética" da cena.
|
| 341 |
+
|
| 342 |
+
* **O Handoff (A Geração):** O próximo fragmento é forçado a começar a partir deste `Eco` dinâmico. Isso garante a herança da "física" do movimento, iluminação e composição da cena anterior.
|
| 343 |
+
|
| 344 |
+
* **A Sincronização (O Cineasta de IA):** Para cada Handoff, o Cineasta de IA (`Γ`) analisa o ponto de partida (`Eco`), o caminho (`Keyframe` anterior) e o destino (`Keyframe` futuro) para criar uma instrução de movimento precisa, sincronizando a transição.
|
| 345 |
+
|
| 346 |
+
O resultado é um vídeo que flui como um único plano-sequência, em vez de uma série de clipes colados.
|
| 347 |
+
"""
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
director_button.click(fn=run_storyboard_generation, inputs=[num_fragments_input, prompt_input, image_input], outputs=[scene_storyboard_state]).success(fn=lambda s, p: (s, p), inputs=[scene_storyboard_state, prompt_input], outputs=[storyboard_to_show, prompt_geral_state]).success(fn=process_image_to_square, inputs=[image_input], outputs=[processed_ref_path_state]).success(fn=lambda p: p, inputs=[processed_ref_path_state], outputs=[ref_image_inputs_auto])
|
| 351 |
+
photographer_button.click(fn=run_keyframe_generation, inputs=[scene_storyboard_state, processed_ref_path_state, ref_task_input], outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state])
|
| 352 |
+
animator_button.click(fn=run_video_production, inputs=[prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider, cut_frames_slider], outputs=[production_log_output, video_gallery_glitch, fragment_list_state])
|
| 353 |
+
editor_button.click(fn=concatenate_and_trim_masterpiece, inputs=[fragment_list_state], outputs=[final_video_output])
|
| 354 |
+
|
| 355 |
+
if __name__ == "__main__":
|
| 356 |
+
demo.queue().launch(server_name="0.0.0.0", share=True)
|