Spaces:
Runtime error
Runtime error
Delete app.5.4.py
Browse files- app.5.4.py +0 -356
app.5.4.py
DELETED
|
@@ -1,356 +0,0 @@
|
|
| 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 |
-
# --- app.py (NOVIM-5.5: O Fator Humano) ---
|
| 20 |
-
|
| 21 |
-
# --- Ato 1: A Convocação da Orquestra (Importações) ---
|
| 22 |
-
import gradio as gr
|
| 23 |
-
import torch
|
| 24 |
-
import os
|
| 25 |
-
import yaml
|
| 26 |
-
from PIL import Image, ImageOps, ExifTags
|
| 27 |
-
import shutil
|
| 28 |
-
import gc
|
| 29 |
-
import subprocess
|
| 30 |
-
import google.generativeai as genai
|
| 31 |
-
import numpy as np
|
| 32 |
-
import imageio
|
| 33 |
-
from pathlib import Path
|
| 34 |
-
import huggingface_hub
|
| 35 |
-
import json
|
| 36 |
-
import time
|
| 37 |
-
|
| 38 |
-
from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
|
| 39 |
-
from dreamo_helpers import dreamo_generator_singleton
|
| 40 |
-
|
| 41 |
-
# --- Ato 2: A Preparação do Palco (Configurações) ---
|
| 42 |
-
config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
|
| 43 |
-
with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
|
| 44 |
-
|
| 45 |
-
LTX_REPO = "Lightricks/LTX-Video"
|
| 46 |
-
models_dir = "downloaded_models_gradio"
|
| 47 |
-
Path(models_dir).mkdir(parents=True, exist_ok=True)
|
| 48 |
-
WORKSPACE_DIR = "aduc_workspace"
|
| 49 |
-
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 50 |
-
|
| 51 |
-
VIDEO_FPS = 24
|
| 52 |
-
TARGET_RESOLUTION = 420
|
| 53 |
-
MAX_KEYFRAMES_UI = 10 # Limite de abas de keyframe na UI
|
| 54 |
-
|
| 55 |
-
print("Criando pipelines LTX na CPU (estado de repouso)...")
|
| 56 |
-
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)
|
| 57 |
-
pipeline_instance = create_ltx_video_pipeline(
|
| 58 |
-
ckpt_path=distilled_model_actual_path,
|
| 59 |
-
precision=PIPELINE_CONFIG_YAML["precision"],
|
| 60 |
-
text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
|
| 61 |
-
sampler=PIPELINE_CONFIG_YAML["sampler"],
|
| 62 |
-
device='cpu'
|
| 63 |
-
)
|
| 64 |
-
print("Modelos LTX prontos (na CPU).")
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
# --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
|
| 68 |
-
|
| 69 |
-
def robust_json_parser(raw_text: str) -> dict:
|
| 70 |
-
try:
|
| 71 |
-
start_index = raw_text.find('{'); end_index = raw_text.rfind('}')
|
| 72 |
-
if start_index != -1 and end_index != -1 and end_index > start_index:
|
| 73 |
-
json_str = raw_text[start_index : end_index + 1]; return json.loads(json_str)
|
| 74 |
-
else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
|
| 75 |
-
except json.JSONDecodeError as e: raise ValueError(f"Falha ao decodificar JSON: {e}")
|
| 76 |
-
|
| 77 |
-
def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
|
| 78 |
-
if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
|
| 79 |
-
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 80 |
-
prompt_file = "prompts/unified_storyboard_prompt.txt"
|
| 81 |
-
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 82 |
-
director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata="")
|
| 83 |
-
genai.configure(api_key=GEMINI_API_KEY)
|
| 84 |
-
model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(initial_image_path)
|
| 85 |
-
response = model.generate_content([director_prompt, img])
|
| 86 |
-
try:
|
| 87 |
-
storyboard_data = robust_json_parser(response.text)
|
| 88 |
-
storyboard = storyboard_data.get("scene_storyboard", [])
|
| 89 |
-
if not storyboard or len(storyboard) != int(num_fragments): raise ValueError(f"A IA não gerou o número correto de cenas. Esperado: {num_fragments}, Recebido: {len(storyboard)}")
|
| 90 |
-
return storyboard
|
| 91 |
-
except Exception as e: raise gr.Error(f"O Roteirista (Gemini) falhou: {e}. Resposta: {response.text}")
|
| 92 |
-
|
| 93 |
-
def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
|
| 94 |
-
genai.configure(api_key=GEMINI_API_KEY)
|
| 95 |
-
prompt_file = "prompts/img2img_evolution_prompt.txt"
|
| 96 |
-
with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
|
| 97 |
-
director_prompt = template.format(target_scene_description=target_scene_description)
|
| 98 |
-
model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(previous_image_path)
|
| 99 |
-
response = model.generate_content([director_prompt, "Previous Image:", img])
|
| 100 |
-
return response.text.strip().replace("\"", "")
|
| 101 |
-
|
| 102 |
-
def run_keyframe_generation(storyboard, ref_images_tasks, progress=gr.Progress()):
|
| 103 |
-
if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
|
| 104 |
-
initial_ref_image_path = ref_images_tasks[0]['image']
|
| 105 |
-
if not initial_ref_image_path or not os.path.exists(initial_ref_image_path): raise gr.Error("A imagem de referência principal (à esquerda) é obrigatória.")
|
| 106 |
-
log_history = ""; keyframe_paths = []
|
| 107 |
-
try:
|
| 108 |
-
pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
|
| 109 |
-
dreamo_generator_singleton.to_gpu()
|
| 110 |
-
with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
|
| 111 |
-
current_ref_image_path = initial_ref_image_path
|
| 112 |
-
for i, scene_description in enumerate(storyboard):
|
| 113 |
-
progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
|
| 114 |
-
log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
|
| 115 |
-
dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
|
| 116 |
-
reference_items = []
|
| 117 |
-
for item in ref_images_tasks:
|
| 118 |
-
if item['image'] and os.path.exists(item['image']):
|
| 119 |
-
reference_items.append({'image_np': np.array(Image.open(item['image']).convert("RGB")), 'task': item['task']})
|
| 120 |
-
log_history += f" - Roteiro: '{scene_description}'\n - Usando {len(reference_items)} referências visuais.\n - Prompt do D.A.: \"{dreamo_prompt}\"\n"
|
| 121 |
-
yield {keyframe_log_output: gr.update(value=log_history)}
|
| 122 |
-
output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
|
| 123 |
-
image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=reference_items, prompt=dreamo_prompt, width=width, height=height)
|
| 124 |
-
image.save(output_path)
|
| 125 |
-
keyframe_paths.append(output_path); current_ref_image_path = output_path
|
| 126 |
-
except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
|
| 127 |
-
finally: dreamo_generator_singleton.to_cpu(); gc.collect(); torch.cuda.empty_cache()
|
| 128 |
-
log_history += "\nPintura de todos os keyframes concluída.\n"
|
| 129 |
-
yield {keyframe_log_output: gr.update(value=log_history), keyframe_images_state: keyframe_paths}
|
| 130 |
-
|
| 131 |
-
def get_motion_prompt(user_prompt, start_path, end_path, scene_desc):
|
| 132 |
-
return f"A smooth, cinematic transition from the start image towards the end image, focusing on: {scene_desc}"
|
| 133 |
-
|
| 134 |
-
def run_video_production(
|
| 135 |
-
video_duration_seconds, video_fps, end_cond_strength,
|
| 136 |
-
prompt_geral, keyframe_paths_from_ui, scene_storyboard, cfg,
|
| 137 |
-
progress=gr.Progress()
|
| 138 |
-
):
|
| 139 |
-
valid_keyframes = [p for p in keyframe_paths_from_ui if p is not None and os.path.exists(p)]
|
| 140 |
-
if not valid_keyframes or len(valid_keyframes) < 2: raise gr.Error("São necessários pelo menos 2 keyframes válidos para produzir um vídeo.")
|
| 141 |
-
|
| 142 |
-
log_history = "\n--- FASE 3: Iniciando Produção...\n"
|
| 143 |
-
yield {production_log_output: log_history, video_gallery_glitch: []}
|
| 144 |
-
|
| 145 |
-
video_total_frames = int(video_duration_seconds * video_fps)
|
| 146 |
-
seed = int(time.time())
|
| 147 |
-
try:
|
| 148 |
-
pipeline_instance.to('cuda')
|
| 149 |
-
video_fragments = []; kinetic_memory_path = valid_keyframes[0]
|
| 150 |
-
with Image.open(kinetic_memory_path) as img: width, height = img.size
|
| 151 |
-
|
| 152 |
-
for i in range(len(valid_keyframes) - 1):
|
| 153 |
-
fragment_num = i + 1
|
| 154 |
-
progress(i / (len(valid_keyframes) - 1), desc=f"Filmando Fragmento {fragment_num}")
|
| 155 |
-
|
| 156 |
-
start_path = kinetic_memory_path
|
| 157 |
-
destination_path = valid_keyframes[i+1]
|
| 158 |
-
|
| 159 |
-
motion_prompt = get_motion_prompt(prompt_geral, start_path, destination_path, scene_storyboard[i])
|
| 160 |
-
|
| 161 |
-
conditioning_items_data = [(start_path, 0, 1.0), (destination_path, video_total_frames - 1, end_cond_strength)]
|
| 162 |
-
|
| 163 |
-
fragment_path, _ = run_ltx_animation(
|
| 164 |
-
current_fragment_index=fragment_num, motion_prompt=motion_prompt,
|
| 165 |
-
conditioning_items_data=conditioning_items_data, width=width, height=height,
|
| 166 |
-
seed=seed, cfg=cfg, progress=progress,
|
| 167 |
-
video_total_frames=video_total_frames, video_fps=video_fps, use_attention_slicing=True, num_inference_steps=30
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
video_fragments.append(fragment_path)
|
| 171 |
-
eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_from_frag_{fragment_num}.png")
|
| 172 |
-
kinetic_memory_path = extract_last_frame_as_image(fragment_path, eco_output_path)
|
| 173 |
-
|
| 174 |
-
log_history += f"Fragmento {fragment_num} concluído.\n"
|
| 175 |
-
yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
|
| 176 |
-
|
| 177 |
-
yield {production_log_output: log_history + "\nProdução concluída.", video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
|
| 178 |
-
finally:
|
| 179 |
-
pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
|
| 180 |
-
|
| 181 |
-
def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
|
| 182 |
-
if not image_path: return None
|
| 183 |
-
try:
|
| 184 |
-
img = Image.open(image_path).convert("RGB"); img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
|
| 185 |
-
output_path = os.path.join(WORKSPACE_DIR, f"initial_ref_{size}x{size}.png"); img_square.save(output_path)
|
| 186 |
-
return output_path
|
| 187 |
-
except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
|
| 188 |
-
|
| 189 |
-
def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
|
| 190 |
-
return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
|
| 191 |
-
|
| 192 |
-
def run_ltx_animation(
|
| 193 |
-
current_fragment_index, motion_prompt, conditioning_items_data,
|
| 194 |
-
width, height, seed, cfg, progress,
|
| 195 |
-
video_total_frames, video_fps, use_attention_slicing, num_inference_steps
|
| 196 |
-
):
|
| 197 |
-
progress(0, desc=f"[Câmera LTX] Filmando Cena {current_fragment_index}...");
|
| 198 |
-
output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4"); target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 199 |
-
try:
|
| 200 |
-
if use_attention_slicing: pipeline_instance.enable_attention_slicing()
|
| 201 |
-
conditioning_items = [ConditioningItem(load_conditioning_tensor(p, height, width).to(target_device), s, t) for p, s, t in conditioning_items_data]
|
| 202 |
-
actual_num_frames = int(round((float(video_total_frames) - 1.0) / 8.0) * 8 + 1)
|
| 203 |
-
padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
|
| 204 |
-
padding_vals = calculate_padding(height, width, padded_h, padded_w)
|
| 205 |
-
for item in conditioning_items: item.media_item = torch.nn.functional.pad(item.media_item, padding_vals)
|
| 206 |
-
|
| 207 |
-
first_pass_config = PIPELINE_CONFIG_YAML.get("first_pass", {}).copy()
|
| 208 |
-
first_pass_config['num_inference_steps'] = int(num_inference_steps)
|
| 209 |
-
|
| 210 |
-
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": first_pass_config.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, "num_inference_steps": int(num_inference_steps)}
|
| 211 |
-
|
| 212 |
-
result_tensor = pipeline_instance(**kwargs).images
|
| 213 |
-
|
| 214 |
-
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
|
| 215 |
-
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)
|
| 216 |
-
with imageio.get_writer(output_path, fps=video_fps, codec='libx264', quality=8) as writer:
|
| 217 |
-
for i, frame in enumerate(video_np): writer.append_data(frame)
|
| 218 |
-
return output_path, actual_num_frames
|
| 219 |
-
finally:
|
| 220 |
-
if use_attention_slicing: pipeline_instance.disable_attention_slicing()
|
| 221 |
-
|
| 222 |
-
def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
|
| 223 |
-
try:
|
| 224 |
-
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)
|
| 225 |
-
return output_path
|
| 226 |
-
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao cortar vídeo: {e.stderr}")
|
| 227 |
-
|
| 228 |
-
def extract_last_frame_as_image(video_path: str, output_image_path: str) -> str:
|
| 229 |
-
try:
|
| 230 |
-
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)
|
| 231 |
-
return output_image_path
|
| 232 |
-
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao extrair último frame: {e.stderr}")
|
| 233 |
-
|
| 234 |
-
def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
|
| 235 |
-
if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
|
| 236 |
-
progress(0.5, desc="Montando a obra-prima final...");
|
| 237 |
-
try:
|
| 238 |
-
list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
|
| 239 |
-
with open(list_file_path, "w") as f:
|
| 240 |
-
for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
|
| 241 |
-
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)
|
| 242 |
-
progress(1.0, desc="Montagem concluída!")
|
| 243 |
-
return final_output_path
|
| 244 |
-
except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
|
| 245 |
-
|
| 246 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 247 |
-
gr.Markdown("# NOVIM-5.5 (O Fator Humano)\n*By Carlex & Gemini & DreamO*")
|
| 248 |
-
if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
|
| 249 |
-
os.makedirs(WORKSPACE_DIR)
|
| 250 |
-
|
| 251 |
-
scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
|
| 252 |
-
prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
|
| 253 |
-
|
| 254 |
-
gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
|
| 255 |
-
with gr.Row():
|
| 256 |
-
with gr.Column(scale=1):
|
| 257 |
-
prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
|
| 258 |
-
num_fragments_input = gr.Slider(2, MAX_KEYFRAMES_UI, 4, step=1, label="Número de Atos (Keyframes)")
|
| 259 |
-
image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
|
| 260 |
-
director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
|
| 261 |
-
with gr.Column(scale=2):
|
| 262 |
-
storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado")
|
| 263 |
-
|
| 264 |
-
gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
|
| 265 |
-
with gr.Row():
|
| 266 |
-
with gr.Column(scale=2):
|
| 267 |
-
with gr.Row():
|
| 268 |
-
ref1_image = gr.Image(label="Referência Principal (Conteúdo/ID)", type="filepath")
|
| 269 |
-
ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Ref. Principal")
|
| 270 |
-
with gr.Row():
|
| 271 |
-
ref2_image = gr.Image(label="Referência Secundária (Opcional)", type="filepath")
|
| 272 |
-
ref2_task = gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa da Ref. Secundária")
|
| 273 |
-
photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
|
| 274 |
-
keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=10, interactive=False)
|
| 275 |
-
with gr.Column(scale=1):
|
| 276 |
-
gr.Markdown("### Painel de Edição de Keyframes")
|
| 277 |
-
keyframe_ui_slots = []
|
| 278 |
-
keyframe_ui_tabs_visibility = []
|
| 279 |
-
with gr.Tabs() as keyframe_tabs:
|
| 280 |
-
for i in range(MAX_KEYFRAMES_UI):
|
| 281 |
-
with gr.TabItem(f"Keyframe {i+1}", visible=(i<2)) as keyframe_tab:
|
| 282 |
-
keyframe_ui_slots.append(gr.Image(label=f"Conteúdo do Keyframe {i+1}", type="filepath", interactive=True))
|
| 283 |
-
keyframe_ui_tabs_visibility.append(keyframe_tab)
|
| 284 |
-
|
| 285 |
-
gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
|
| 286 |
-
with gr.Row():
|
| 287 |
-
with gr.Column(scale=1):
|
| 288 |
-
cfg_slider = gr.Slider(1.0, 10.0, 7.5, step=0.1, label="CFG")
|
| 289 |
-
end_cond_strength_slider = gr.Slider(label="Força de Convergência do Destino", minimum=0.1, maximum=1.0, value=1.0, step=0.05)
|
| 290 |
-
with gr.Accordion("Controles Avançados de Timing", open=False):
|
| 291 |
-
video_duration_slider = gr.Slider(label="Duração da Cena (segundos)", minimum=2.0, maximum=10.0, value=4.0, step=0.5)
|
| 292 |
-
video_fps_slider = gr.Slider(label="FPS do Vídeo", minimum=12, maximum=36, value=VIDEO_FPS, step=1)
|
| 293 |
-
animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
|
| 294 |
-
production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
|
| 295 |
-
with gr.Column(scale=1):
|
| 296 |
-
video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
|
| 297 |
-
|
| 298 |
-
gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
|
| 299 |
-
editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
|
| 300 |
-
final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
|
| 301 |
-
|
| 302 |
-
def process_and_update_storyboard(num_fragments, prompt, image_path):
|
| 303 |
-
processed_path = process_image_to_square(image_path)
|
| 304 |
-
if not processed_path: raise gr.Error("A imagem de referência é inválida.")
|
| 305 |
-
storyboard = run_storyboard_generation(num_fragments, prompt, processed_path)
|
| 306 |
-
tab_updates = [gr.update(visible=(i < num_fragments)) for i in range(MAX_KEYFRAMES_UI)]
|
| 307 |
-
return storyboard, prompt, processed_path, storyboard, processed_path, *tab_updates
|
| 308 |
-
|
| 309 |
-
director_button.click(
|
| 310 |
-
fn=process_and_update_storyboard,
|
| 311 |
-
inputs=[num_fragments_input, prompt_input, image_input],
|
| 312 |
-
outputs=[scene_storyboard_state, prompt_geral_state, processed_ref_path_state, storyboard_to_show, ref1_image] + keyframe_ui_tabs_visibility
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
def run_keyframe_generation_wrapper(storyboard, ref1_img, ref1_tsk, ref2_img, ref2_tsk, progress=gr.Progress()):
|
| 316 |
-
ref_data = [{'image': ref1_img, 'task': ref1_tsk}, {'image': ref2_img, 'task': ref2_tsk}]
|
| 317 |
-
final_update = {}
|
| 318 |
-
for update in run_keyframe_generation(storyboard, ref_data, progress):
|
| 319 |
-
final_update = update
|
| 320 |
-
final_paths = final_update.get('keyframe_images_state', [])
|
| 321 |
-
updates = [gr.update(value=final_paths[i] if i < len(final_paths) else None) for i in range(MAX_KEYFRAMES_UI)]
|
| 322 |
-
return final_update.get('keyframe_log_output', ''), final_paths, *updates
|
| 323 |
-
|
| 324 |
-
photographer_button.click(
|
| 325 |
-
fn=run_keyframe_generation_wrapper,
|
| 326 |
-
inputs=[scene_storyboard_state, ref1_image, ref1_task, ref2_image, ref2_task],
|
| 327 |
-
outputs=[keyframe_log_output, keyframe_images_state] + keyframe_ui_slots
|
| 328 |
-
)
|
| 329 |
-
|
| 330 |
-
# A lista de inputs para a produção de vídeo agora coleta os keyframes das abas
|
| 331 |
-
video_prod_inputs = [
|
| 332 |
-
video_duration_slider, video_fps_slider, end_cond_strength_slider,
|
| 333 |
-
prompt_geral_state,
|
| 334 |
-
scene_storyboard_state, cfg_slider
|
| 335 |
-
] + keyframe_ui_slots
|
| 336 |
-
|
| 337 |
-
# A função wrapper é necessária para coletar os valores dos slots de keyframe
|
| 338 |
-
def run_video_production_wrapper(duration, fps, strength, prompt, storyboard, cfg, *keyframes, progress=gr.Progress()):
|
| 339 |
-
# Filtra os keyframes que não são None
|
| 340 |
-
valid_keyframes = [k for k in keyframes if k]
|
| 341 |
-
yield from run_video_production(duration, fps, strength, prompt, valid_keyframes, storyboard, cfg, progress)
|
| 342 |
-
|
| 343 |
-
animator_button.click(
|
| 344 |
-
fn=run_video_production_wrapper,
|
| 345 |
-
inputs=video_prod_inputs,
|
| 346 |
-
outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
|
| 347 |
-
)
|
| 348 |
-
|
| 349 |
-
editor_button.click(
|
| 350 |
-
fn=concatenate_and_trim_masterpiece,
|
| 351 |
-
inputs=[fragment_list_state],
|
| 352 |
-
outputs=[final_video_output]
|
| 353 |
-
)
|
| 354 |
-
|
| 355 |
-
if __name__ == "__main__":
|
| 356 |
-
demo.queue().launch(server_name="0.0.0.0", share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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