Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
#
|
| 3 |
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
-
# Versão
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
import yaml
|
|
@@ -10,14 +10,13 @@ import logging
|
|
| 10 |
import os
|
| 11 |
import sys
|
| 12 |
import shutil
|
| 13 |
-
import time
|
| 14 |
-
import json
|
| 15 |
|
| 16 |
# --- 1. IMPORTAÇÃO DO FRAMEWORK E CONFIGURAÇÃO ---
|
| 17 |
import aduc_framework
|
| 18 |
from aduc_framework.types import PreProductionParams, ProductionParams
|
| 19 |
|
| 20 |
-
# Configuração de Tema Cinemático
|
|
|
|
| 21 |
cinematic_theme = gr.themes.Base(
|
| 22 |
primary_hue=gr.themes.colors.indigo,
|
| 23 |
secondary_hue=gr.themes.colors.purple,
|
|
@@ -35,6 +34,7 @@ cinematic_theme = gr.themes.Base(
|
|
| 35 |
)
|
| 36 |
|
| 37 |
# Configuração de Logging
|
|
|
|
| 38 |
LOG_FILE_PATH = "aduc_log.txt"
|
| 39 |
if os.path.exists(LOG_FILE_PATH): os.remove(LOG_FILE_PATH)
|
| 40 |
log_format = '%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s] - %(message)s'
|
|
@@ -57,6 +57,7 @@ try:
|
|
| 57 |
logger.info("Interface Gradio inicializada e conectada ao Aduc Framework.")
|
| 58 |
except Exception as e:
|
| 59 |
logger.critical(f"ERRO CRÍTICO durante a inicialização: {e}", exc_info=True)
|
|
|
|
| 60 |
with gr.Blocks() as demo:
|
| 61 |
gr.Markdown("# ERRO CRÍTICO NA INICIALIZAÇÃO")
|
| 62 |
gr.Markdown("Não foi possível iniciar o Aduc Framework. Verifique os logs para mais detalhes.")
|
|
@@ -65,28 +66,79 @@ except Exception as e:
|
|
| 65 |
exit()
|
| 66 |
|
| 67 |
# --- 2. FUNÇÕES WRAPPER (UI <-> FRAMEWORK) ---
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
target_resolution = int(resolution_str.split('x')[0])
|
|
|
|
|
|
|
| 71 |
ref_paths = [aduc.process_image_for_story(f.name, target_resolution, f"ref_processed_{i}.png") for i, f in enumerate(ref_files)]
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
yield {
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
keyframe_gallery: gr.update(value=update.get("final_keyframes", [])),
|
| 79 |
}
|
| 80 |
-
final_result = update
|
| 81 |
-
yield {
|
| 82 |
-
generation_state_holder: final_result.get("updated_state"),
|
| 83 |
-
step3_accordion: gr.update(visible=True, open=True)
|
| 84 |
-
}
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
yield {final_video_output: gr.update(value=None, visible=True, label="🎬 Produzindo seu filme...")}
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
final_video_path, latent_paths, updated_state = aduc.task_produce_original_movie(params=production_params, progress_callback=progress)
|
|
|
|
| 90 |
yield {
|
| 91 |
final_video_output: gr.update(value=final_video_path, label="✅ Filme Original Master"),
|
| 92 |
step4_accordion: gr.update(visible=True, open=True),
|
|
@@ -95,54 +147,44 @@ def run_original_production_wrapper(current_state_dict, trim_percent, handler_st
|
|
| 95 |
generation_state_holder: updated_state.model_dump(),
|
| 96 |
}
|
| 97 |
|
| 98 |
-
|
| 99 |
-
if not source_video or not latent_paths: raise gr.Error("Fonte de vídeo ou latentes originais não encontrados para o Upscaler.")
|
| 100 |
-
yield {final_video_output: gr.update(label="Pós-Produção: Upscaler Latente...")}
|
| 101 |
-
final_path = source_video
|
| 102 |
-
for update in aduc.task_run_latent_upscaler(latent_paths, int(chunk_size), progress):
|
| 103 |
-
if "final_path" in update: final_path = update['final_path']
|
| 104 |
-
yield {final_video_output: gr.update(value=final_path, label="✅ Upscale Latente Concluído"), current_source_video_state: final_path}
|
| 105 |
-
|
| 106 |
-
def run_hd_wrapper(source_video, steps, global_prompt, progress=gr.Progress()):
|
| 107 |
-
if not source_video: raise gr.Error("Fonte de vídeo não encontrada para a Masterização HD.")
|
| 108 |
-
yield {final_video_output: gr.update(label="Pós-Produção: Masterização HD...")}
|
| 109 |
-
final_path = source_video
|
| 110 |
-
for update in aduc.task_run_hd_mastering(source_video, int(steps), global_prompt, progress):
|
| 111 |
-
if "final_path" in update: final_path = update['final_path']
|
| 112 |
-
yield {final_video_output: gr.update(value=final_path, label="✅ Masterização HD Concluída"), current_source_video_state: final_path}
|
| 113 |
-
|
| 114 |
-
def run_audio_wrapper(source_video, audio_prompt, global_prompt, progress=gr.Progress()):
|
| 115 |
-
if not source_video: raise gr.Error("Fonte de vídeo não encontrada para a Geração de Áudio.")
|
| 116 |
-
yield {final_video_output: gr.update(label="Pós-Produção: Geração de Áudio...")}
|
| 117 |
-
final_audio_prompt = audio_prompt if audio_prompt and audio_prompt.strip() else global_prompt
|
| 118 |
-
final_path = source_video
|
| 119 |
-
for update in aduc.task_run_audio_generation(source_video, final_audio_prompt, progress):
|
| 120 |
-
if "final_path" in update: final_path = update['final_path']
|
| 121 |
-
yield {final_video_output: gr.update(value=final_path, label="✅ Filme Final com Áudio")}
|
| 122 |
|
| 123 |
def get_log_content():
|
| 124 |
try:
|
| 125 |
-
with open(LOG_FILE_PATH, "r", encoding="utf-8") as f:
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
|
| 128 |
# --- 3. DEFINIÇÃO DA UI ---
|
| 129 |
with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
|
|
|
|
| 130 |
generation_state_holder = gr.State(value={})
|
| 131 |
original_latents_paths_state = gr.State(value=[])
|
| 132 |
current_source_video_state = gr.State(value=None)
|
|
|
|
|
|
|
| 133 |
gr.Markdown("<h1>ADUC-SDR 🎬 - O Diretor de Cinema IA</h1>")
|
| 134 |
gr.Markdown("<p>Crie um filme completo com vídeo e áudio, orquestrado por uma equipe de IAs especialistas.</p>")
|
| 135 |
-
|
|
|
|
|
|
|
| 136 |
prompt_input = gr.Textbox(label="Ideia Geral do Filme", value="Um leão majestoso caminha pela savana, senta-se e ruge para o sol poente.")
|
| 137 |
with gr.Row():
|
| 138 |
-
lang_selector = gr.Radio(["🇧🇷", "🇺🇸", "🇨🇳"], value="🇧🇷", label="Idioma / Language")
|
| 139 |
resolution_selector = gr.Radio(["512x512", "768x768", "1024x1024"], value="512x512", label="Resolução Base")
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
with gr.Accordion("Etapa 2: Produção do Vídeo Original", open=False, visible=False) as step3_accordion:
|
|
|
|
| 146 |
trim_percent_slider = gr.Slider(minimum=10, maximum=90, value=50, step=5, label="Poda Causal (%)")
|
| 147 |
handler_strength = gr.Slider(label="Força do Déjà-Vu", minimum=0.0, maximum=1.0, value=0.5, step=0.05)
|
| 148 |
dest_strength = gr.Slider(label="Força da Âncora Final", minimum=0.0, maximum=1.0, value=0.75, step=0.05)
|
|
@@ -150,7 +192,10 @@ with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
|
|
| 150 |
stg_scale_slider = gr.Slider(minimum=0.0, maximum=1.0, value=0.025, step=0.005, label="Escala STG")
|
| 151 |
inference_steps_slider = gr.Slider(minimum=10, maximum=50, value=20, step=1, label="Passos de Inferência")
|
| 152 |
produce_original_button = gr.Button("🎬 Produzir Vídeo Original", variant="primary")
|
|
|
|
|
|
|
| 153 |
with gr.Accordion("Etapa 3: Pós-Produção (Opcional)", open=False, visible=False) as step4_accordion:
|
|
|
|
| 154 |
gr.Markdown("Aplique melhorias ao filme. Cada etapa usa o resultado da anterior como fonte.")
|
| 155 |
with gr.Accordion("A. Upscaler Latente 2x", open=True):
|
| 156 |
upscaler_chunk_size_slider = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Fragmentos por Lote")
|
|
@@ -161,28 +206,67 @@ with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
|
|
| 161 |
with gr.Accordion("C. Geração de Áudio", open=True):
|
| 162 |
audio_prompt_input = gr.Textbox(label="Prompt de Áudio Detalhado (Opcional)", lines=2, placeholder="Descreva os sons, efeitos e música.")
|
| 163 |
run_audio_button = gr.Button("Gerar Áudio", variant="secondary")
|
|
|
|
|
|
|
| 164 |
final_video_output = gr.Video(label="Filme Final (Resultado da Última Etapa)", visible=False, interactive=False)
|
| 165 |
-
with gr.Accordion("
|
| 166 |
-
keyframe_gallery = gr.Gallery(label="Keyframes Gerados", visible=True, object_fit="contain", height="auto"
|
| 167 |
-
with gr.Accordion("
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
# --- 5. INICIALIZAÇÃO DA APLICAÇÃO ---
|
| 184 |
if __name__ == "__main__":
|
| 185 |
-
if os.path.exists(WORKSPACE_DIR):
|
|
|
|
| 186 |
os.makedirs(WORKSPACE_DIR)
|
|
|
|
| 187 |
logger.info("Aplicação Gradio iniciada. Lançando interface...")
|
| 188 |
demo.queue().launch()
|
|
|
|
| 2 |
#
|
| 3 |
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
#
|
| 5 |
+
# Versão 7.0.0 (Reactive UI & Planner-Composer Architecture)
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
import yaml
|
|
|
|
| 10 |
import os
|
| 11 |
import sys
|
| 12 |
import shutil
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# --- 1. IMPORTAÇÃO DO FRAMEWORK E CONFIGURAÇÃO ---
|
| 15 |
import aduc_framework
|
| 16 |
from aduc_framework.types import PreProductionParams, ProductionParams
|
| 17 |
|
| 18 |
+
# Configuração de Tema Cinemático (cinematic_theme)
|
| 19 |
+
# (O código do tema permanece o mesmo, omitido para brevidade, mas deve estar aqui)
|
| 20 |
cinematic_theme = gr.themes.Base(
|
| 21 |
primary_hue=gr.themes.colors.indigo,
|
| 22 |
secondary_hue=gr.themes.colors.purple,
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
# Configuração de Logging
|
| 37 |
+
# (O código de logging permanece o mesmo, omitido para brevidade, mas deve estar aqui)
|
| 38 |
LOG_FILE_PATH = "aduc_log.txt"
|
| 39 |
if os.path.exists(LOG_FILE_PATH): os.remove(LOG_FILE_PATH)
|
| 40 |
log_format = '%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s] - %(message)s'
|
|
|
|
| 57 |
logger.info("Interface Gradio inicializada e conectada ao Aduc Framework.")
|
| 58 |
except Exception as e:
|
| 59 |
logger.critical(f"ERRO CRÍTICO durante a inicialização: {e}", exc_info=True)
|
| 60 |
+
# Bloco de erro do Gradio, se a inicialização falhar
|
| 61 |
with gr.Blocks() as demo:
|
| 62 |
gr.Markdown("# ERRO CRÍTICO NA INICIALIZAÇÃO")
|
| 63 |
gr.Markdown("Não foi possível iniciar o Aduc Framework. Verifique os logs para mais detalhes.")
|
|
|
|
| 66 |
exit()
|
| 67 |
|
| 68 |
# --- 2. FUNÇÕES WRAPPER (UI <-> FRAMEWORK) ---
|
| 69 |
+
|
| 70 |
+
def run_pre_production_wrapper(prompt, num_scenes, ref_files, resolution_str, duration_per_fragment, progress=gr.Progress(track_tqdm=True)):
|
| 71 |
+
"""
|
| 72 |
+
Wrapper reativo para a fase de pré-produção.
|
| 73 |
+
Captura os eventos do Composer e atualiza a UI em tempo real.
|
| 74 |
+
"""
|
| 75 |
+
if not ref_files:
|
| 76 |
+
raise gr.Error("Por favor, forneça pelo menos uma imagem de referência.")
|
| 77 |
+
|
| 78 |
target_resolution = int(resolution_str.split('x')[0])
|
| 79 |
+
|
| 80 |
+
# Processa as imagens de referência
|
| 81 |
ref_paths = [aduc.process_image_for_story(f.name, target_resolution, f"ref_processed_{i}.png") for i, f in enumerate(ref_files)]
|
| 82 |
+
|
| 83 |
+
params = PreProductionParams(
|
| 84 |
+
prompt=prompt,
|
| 85 |
+
num_scenes=int(num_scenes),
|
| 86 |
+
ref_paths=ref_paths,
|
| 87 |
+
resolution=target_resolution,
|
| 88 |
+
duration_per_fragment=duration_per_fragment
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
log_history = ""
|
| 92 |
+
# Loop principal que consome o gerador do orquestrador
|
| 93 |
+
for update in aduc.task_pre_production(params, progress_callback=progress):
|
| 94 |
+
status = update.get("status")
|
| 95 |
+
message = update.get("message", "")
|
| 96 |
+
|
| 97 |
+
# Constrói o histórico de logs para a UI
|
| 98 |
+
log_entry = f"[{status.upper()}] {message}\n"
|
| 99 |
+
log_history += log_entry
|
| 100 |
+
|
| 101 |
+
# Gera o dicionário de atualização para os componentes da UI
|
| 102 |
yield {
|
| 103 |
+
log_display_realtime: log_history,
|
| 104 |
+
dna_display: update.get("dna_snapshot", gr.skip()),
|
|
|
|
| 105 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
if status == "error":
|
| 108 |
+
raise gr.Error(f"Ocorreu um erro no backend: {message}")
|
| 109 |
+
|
| 110 |
+
if status == "pre_production_complete":
|
| 111 |
+
# Quando a pré-produção termina, habilita os próximos passos
|
| 112 |
+
yield {
|
| 113 |
+
log_display_realtime: log_history,
|
| 114 |
+
dna_display: update.get("dna_snapshot"),
|
| 115 |
+
keyframe_gallery: gr.update(value=update.get("keyframe_gallery", [])),
|
| 116 |
+
step3_accordion: gr.update(visible=True, open=True)
|
| 117 |
+
}
|
| 118 |
+
# O gerador termina aqui para a pré-produção
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def run_production_wrapper(current_state_dict, trim_percent, handler_strength, dest_strength, guidance_scale, stg_scale, steps, progress=gr.Progress(track_tqdm=True)):
|
| 123 |
+
"""Wrapper para a geração do vídeo principal."""
|
| 124 |
yield {final_video_output: gr.update(value=None, visible=True, label="🎬 Produzindo seu filme...")}
|
| 125 |
+
|
| 126 |
+
# Esta função no orquestrador não é um gerador, então a chamamos diretamente.
|
| 127 |
+
# Precisaremos do estado atual (DNA) que foi salvo no `generation_state_holder`.
|
| 128 |
+
# AducDirector precisará de um método para carregar este estado.
|
| 129 |
+
# Por agora, vamos simular passando o dicionário.
|
| 130 |
+
# aduc.director.load_state_from_dict(current_state_dict) # Idealmente
|
| 131 |
+
|
| 132 |
+
production_params = ProductionParams(
|
| 133 |
+
trim_percent=int(trim_percent), handler_strength=handler_strength,
|
| 134 |
+
destination_convergence_strength=dest_strength, guidance_scale=guidance_scale,
|
| 135 |
+
stg_scale=stg_scale, inference_steps=int(steps)
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Assumindo que o `task_produce_original_movie` usa o estado já no `aduc.director`
|
| 139 |
+
# (que foi atualizado pela pré-produção)
|
| 140 |
final_video_path, latent_paths, updated_state = aduc.task_produce_original_movie(params=production_params, progress_callback=progress)
|
| 141 |
+
|
| 142 |
yield {
|
| 143 |
final_video_output: gr.update(value=final_video_path, label="✅ Filme Original Master"),
|
| 144 |
step4_accordion: gr.update(visible=True, open=True),
|
|
|
|
| 147 |
generation_state_holder: updated_state.model_dump(),
|
| 148 |
}
|
| 149 |
|
| 150 |
+
# ... (Os wrappers de pós-produção permanecem os mesmos, pois já usam geradores) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
def get_log_content():
|
| 153 |
try:
|
| 154 |
+
with open(LOG_FILE_PATH, "r", encoding="utf-8") as f:
|
| 155 |
+
return f.read()
|
| 156 |
+
except FileNotFoundError:
|
| 157 |
+
return "Arquivo de log ainda não criado."
|
| 158 |
|
| 159 |
# --- 3. DEFINIÇÃO DA UI ---
|
| 160 |
with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
|
| 161 |
+
# Componentes de Estado
|
| 162 |
generation_state_holder = gr.State(value={})
|
| 163 |
original_latents_paths_state = gr.State(value=[])
|
| 164 |
current_source_video_state = gr.State(value=None)
|
| 165 |
+
|
| 166 |
+
# Título
|
| 167 |
gr.Markdown("<h1>ADUC-SDR 🎬 - O Diretor de Cinema IA</h1>")
|
| 168 |
gr.Markdown("<p>Crie um filme completo com vídeo e áudio, orquestrado por uma equipe de IAs especialistas.</p>")
|
| 169 |
+
|
| 170 |
+
# Etapa 1: Pré-Produção
|
| 171 |
+
with gr.Accordion("Etapa 1: Planejamento (Pré-Produção)", open=True) as step1_accordion:
|
| 172 |
prompt_input = gr.Textbox(label="Ideia Geral do Filme", value="Um leão majestoso caminha pela savana, senta-se e ruge para o sol poente.")
|
| 173 |
with gr.Row():
|
|
|
|
| 174 |
resolution_selector = gr.Radio(["512x512", "768x768", "1024x1024"], value="512x512", label="Resolução Base")
|
| 175 |
+
num_scenes_slider = gr.Slider(minimum=2, maximum=10, value=3, step=1, label="Número de Cenas do Filme")
|
| 176 |
+
ref_image_input = gr.File(label="Imagens de Referência (Material Bibliográfico)", file_count="multiple", file_types=["image"])
|
| 177 |
+
duration_per_fragment_slider = gr.Slider(label="Duração Máxima de cada Ato (s)", minimum=2.0, maximum=10.0, value=4.0, step=0.1)
|
| 178 |
+
start_planning_button = gr.Button("Iniciar Planejamento de Pré-Produção", variant="primary")
|
| 179 |
+
|
| 180 |
+
# Accordion para mostrar o progresso do planejamento em tempo real
|
| 181 |
+
with gr.Accordion("🧠 Diário do Planejador (Pré-Produção em Tempo Real)", open=False) as planning_log_accordion:
|
| 182 |
+
log_display_realtime = gr.Textbox(label="Log da Conversa com IA", lines=15, interactive=False, autoscroll=True)
|
| 183 |
+
dna_display = gr.JSON(label="DNA da Produção (em construção)")
|
| 184 |
+
|
| 185 |
+
# Etapa 2: Produção
|
| 186 |
with gr.Accordion("Etapa 2: Produção do Vídeo Original", open=False, visible=False) as step3_accordion:
|
| 187 |
+
# ... (Sliders de produção permanecem os mesmos) ...
|
| 188 |
trim_percent_slider = gr.Slider(minimum=10, maximum=90, value=50, step=5, label="Poda Causal (%)")
|
| 189 |
handler_strength = gr.Slider(label="Força do Déjà-Vu", minimum=0.0, maximum=1.0, value=0.5, step=0.05)
|
| 190 |
dest_strength = gr.Slider(label="Força da Âncora Final", minimum=0.0, maximum=1.0, value=0.75, step=0.05)
|
|
|
|
| 192 |
stg_scale_slider = gr.Slider(minimum=0.0, maximum=1.0, value=0.025, step=0.005, label="Escala STG")
|
| 193 |
inference_steps_slider = gr.Slider(minimum=10, maximum=50, value=20, step=1, label="Passos de Inferência")
|
| 194 |
produce_original_button = gr.Button("🎬 Produzir Vídeo Original", variant="primary")
|
| 195 |
+
|
| 196 |
+
# Etapa 3: Pós-Produção
|
| 197 |
with gr.Accordion("Etapa 3: Pós-Produção (Opcional)", open=False, visible=False) as step4_accordion:
|
| 198 |
+
# ... (Componentes de pós-produção permanecem os mesmos) ...
|
| 199 |
gr.Markdown("Aplique melhorias ao filme. Cada etapa usa o resultado da anterior como fonte.")
|
| 200 |
with gr.Accordion("A. Upscaler Latente 2x", open=True):
|
| 201 |
upscaler_chunk_size_slider = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Fragmentos por Lote")
|
|
|
|
| 206 |
with gr.Accordion("C. Geração de Áudio", open=True):
|
| 207 |
audio_prompt_input = gr.Textbox(label="Prompt de Áudio Detalhado (Opcional)", lines=2, placeholder="Descreva os sons, efeitos e música.")
|
| 208 |
run_audio_button = gr.Button("Gerar Áudio", variant="secondary")
|
| 209 |
+
|
| 210 |
+
# Saídas Finais e Logs
|
| 211 |
final_video_output = gr.Video(label="Filme Final (Resultado da Última Etapa)", visible=False, interactive=False)
|
| 212 |
+
with gr.Accordion("🖼️ Galeria de Keyframes (Referência)", open=False) as keyframes_accordion:
|
| 213 |
+
keyframe_gallery = gr.Gallery(label="Keyframes Gerados", visible=True, object_fit="contain", height="auto")
|
| 214 |
+
with gr.Accordion("📝 Log de Sessão (Completo)", open=False) as log_accordion:
|
| 215 |
+
log_display_full = gr.Textbox(label="Log da Sessão", lines=20, interactive=False, autoscroll=True)
|
| 216 |
+
update_log_button = gr.Button("Atualizar Log Completo")
|
| 217 |
+
|
| 218 |
+
# --- 4. CONEXÕES DE EVENTOS ---
|
| 219 |
+
|
| 220 |
+
# Conexão principal para a pré-produção reativa
|
| 221 |
+
start_planning_button.click(
|
| 222 |
+
fn=lambda: gr.update(open=True), outputs=[planning_log_accordion] # Abre o accordion de log
|
| 223 |
+
).then(
|
| 224 |
+
fn=run_pre_production_wrapper,
|
| 225 |
+
inputs=[prompt_input, num_scenes_slider, ref_image_input, resolution_selector, duration_per_fragment_slider],
|
| 226 |
+
outputs=[log_display_realtime, dna_display, keyframe_gallery, step3_accordion]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Conexões para as etapas seguintes
|
| 230 |
+
produce_original_button.click(
|
| 231 |
+
fn=run_production_wrapper,
|
| 232 |
+
inputs=[generation_state_holder, trim_percent_slider, handler_strength, dest_strength, guidance_scale_slider, stg_scale_slider, inference_steps_slider],
|
| 233 |
+
outputs=[final_video_output, step4_accordion, original_latents_paths_state, current_source_video_state, generation_state_holder]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
run_upscaler_button.click(
|
| 237 |
+
fn=aduc.task_run_latent_upscaler, # Chamando diretamente se já for um gerador
|
| 238 |
+
inputs=[original_latents_paths_state, upscaler_chunk_size_slider],
|
| 239 |
+
outputs=[final_video_output] # Assumindo que o wrapper não é mais necessário
|
| 240 |
+
).then(
|
| 241 |
+
fn=lambda video_path: video_path, inputs=[final_video_output], outputs=[current_source_video_state]
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
run_hd_button.click(
|
| 245 |
+
fn=aduc.task_run_hd_mastering,
|
| 246 |
+
inputs=[current_source_video_state, hd_steps_slider, prompt_input],
|
| 247 |
+
outputs=[final_video_output]
|
| 248 |
+
).then(
|
| 249 |
+
fn=lambda video_path: video_path, inputs=[final_video_output], outputs=[current_source_video_state]
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
run_audio_button.click(
|
| 253 |
+
fn=aduc.task_run_audio_generation,
|
| 254 |
+
inputs=[current_source_video_state, audio_prompt_input, prompt_input],
|
| 255 |
+
outputs=[final_video_output]
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Conexão para atualizar o log completo
|
| 259 |
+
update_log_button.click(fn=get_log_content, inputs=[], outputs=[log_display_full])
|
| 260 |
+
|
| 261 |
+
# Atualiza o state holder com o DNA final quando a pré-produção termina
|
| 262 |
+
dna_display.change(fn=lambda data: data, inputs=dna_display, outputs=generation_state_holder)
|
| 263 |
+
|
| 264 |
|
| 265 |
# --- 5. INICIALIZAÇÃO DA APLICAÇÃO ---
|
| 266 |
if __name__ == "__main__":
|
| 267 |
+
if os.path.exists(WORKSPACE_DIR):
|
| 268 |
+
shutil.rmtree(WORKSPACE_DIR)
|
| 269 |
os.makedirs(WORKSPACE_DIR)
|
| 270 |
+
|
| 271 |
logger.info("Aplicação Gradio iniciada. Lançando interface...")
|
| 272 |
demo.queue().launch()
|