Spaces:
Paused
Paused
Update app.py
#2
by
eeuuia
- opened
app.py
CHANGED
|
@@ -1,14 +1,13 @@
|
|
| 1 |
# FILE: app.py
|
| 2 |
# DESCRIPTION: Final Gradio web interface for the ADUC-SDR Video Suite.
|
| 3 |
-
# Features
|
| 4 |
-
# and detailed debug logging.
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import traceback
|
| 8 |
import sys
|
| 9 |
import os
|
| 10 |
import logging
|
| 11 |
-
import random
|
| 12 |
|
| 13 |
# ==============================================================================
|
| 14 |
# --- IMPORTAÇÃO DOS SERVIÇOS DE BACKEND E UTILS ---
|
|
@@ -22,25 +21,19 @@ try:
|
|
| 22 |
from api.utils.debug_utils import log_function_io
|
| 23 |
|
| 24 |
# Serviço especialista para upscaling de resolução (SeedVR)
|
| 25 |
-
from api.seedvr_server import
|
| 26 |
-
seedvr_inference_server = SeedVRServer()
|
| 27 |
|
| 28 |
logging.info("All backend services (LTX, SeedVR) and debug utils imported successfully.")
|
| 29 |
|
| 30 |
except ImportError as e:
|
| 31 |
-
|
| 32 |
-
def log_function_io(func):
|
| 33 |
-
return func
|
| 34 |
logging.warning(f"Could not import a module, debug logger might be disabled. SeedVR might be unavailable. Details: {e}")
|
| 35 |
-
# Se o serviço LTX principal falhar, é um erro fatal
|
| 36 |
if 'video_generation_service' not in locals():
|
| 37 |
logging.critical(f"FATAL: Main LTX service failed to import.", exc_info=True)
|
| 38 |
sys.exit(1)
|
| 39 |
-
# Se apenas o SeedVR falhar, a aplicação pode continuar com ele desativado
|
| 40 |
if 'seedvr_inference_server' not in locals():
|
| 41 |
seedvr_inference_server = None
|
| 42 |
logging.warning("SeedVR server could not be initialized. The SeedVR upscaling tab will be disabled.")
|
| 43 |
-
|
| 44 |
except Exception as e:
|
| 45 |
logging.critical(f"FATAL ERROR: An unexpected error occurred during backend initialization. Details: {e}", exc_info=True)
|
| 46 |
sys.exit(1)
|
|
@@ -53,6 +46,7 @@ except Exception as e:
|
|
| 53 |
def run_generate_base_video(
|
| 54 |
generation_mode: str, prompt: str, neg_prompt: str, start_img: str,
|
| 55 |
height: int, width: int, duration: float,
|
|
|
|
| 56 |
fp_num_inference_steps: int, fp_skip_initial_steps: int, fp_skip_final_steps: int,
|
| 57 |
progress=gr.Progress(track_tqdm=True)
|
| 58 |
) -> tuple:
|
|
@@ -69,6 +63,9 @@ def run_generate_base_video(
|
|
| 69 |
)
|
| 70 |
|
| 71 |
ltx_configs = {
|
|
|
|
|
|
|
|
|
|
| 72 |
"num_inference_steps": fp_num_inference_steps,
|
| 73 |
"skip_initial_inference_steps": fp_skip_initial_steps,
|
| 74 |
"skip_final_inference_steps": fp_skip_final_steps,
|
|
@@ -114,7 +111,6 @@ def run_ltx_refinement(state: dict, prompt: str, neg_prompt: str, progress=gr.Pr
|
|
| 114 |
logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
|
| 115 |
raise gr.Error(error_message)
|
| 116 |
|
| 117 |
-
|
| 118 |
@log_function_io
|
| 119 |
def run_seedvr_upscaling(state: dict, seed: int, resolution: int, batch_size: int, fps: int, progress=gr.Progress(track_tqdm=True)) -> tuple:
|
| 120 |
"""Wrapper para o upscale de resolução SeedVR."""
|
|
@@ -146,38 +142,33 @@ def run_seedvr_upscaling(state: dict, seed: int, resolution: int, batch_size: in
|
|
| 146 |
|
| 147 |
def build_ui():
|
| 148 |
"""Constrói a interface completa do Gradio."""
|
| 149 |
-
|
| 150 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
|
| 151 |
app_state = gr.State(value={"low_res_video": None, "low_res_latents": None, "used_seed": None})
|
| 152 |
ui_components = {}
|
| 153 |
-
|
| 154 |
gr.Markdown("# ADUC-SDR Video Suite - LTX & SeedVR Workflow", elem_id="main-title")
|
| 155 |
-
|
| 156 |
with gr.Row():
|
| 157 |
-
with gr.Column(scale=1):
|
| 158 |
-
_build_generation_controls(ui_components)
|
| 159 |
with gr.Column(scale=1):
|
| 160 |
gr.Markdown("### Etapa 1: Vídeo Base Gerado")
|
| 161 |
ui_components['low_res_video_output'] = gr.Video(label="O resultado aparecerá aqui", interactive=False)
|
| 162 |
-
ui_components['used_seed_display'] = gr.Textbox(
|
| 163 |
-
|
| 164 |
_build_postprod_controls(ui_components)
|
| 165 |
-
_register_event_handlers(app_state)
|
| 166 |
-
|
| 167 |
return demo
|
| 168 |
|
| 169 |
def _build_generation_controls(ui: dict):
|
| 170 |
"""Constrói os componentes da UI para a Etapa 1: Geração."""
|
| 171 |
gr.Markdown("### Configurações de Geração")
|
|
|
|
| 172 |
ui['prompt'] = gr.Textbox(label="Prompt(s)", value="Um leão majestoso caminha pela savana\nEle sobe em uma grande pedra e olha o horizonte", lines=4)
|
| 173 |
-
ui['neg_prompt'] = gr.Textbox(
|
| 174 |
ui['start_image'] = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload"])
|
| 175 |
|
| 176 |
with gr.Accordion("Parâmetros Principais", open=True):
|
| 177 |
ui['duration'] = gr.Slider(label="Duração Total (s)", value=4, step=1, minimum=1, maximum=30)
|
| 178 |
with gr.Row():
|
| 179 |
-
ui['height'] = gr.Slider(label="Height", value=
|
| 180 |
-
ui['width'] = gr.Slider(label="Width", value=
|
| 181 |
|
| 182 |
with gr.Accordion("Opções Avançadas LTX", open=False):
|
| 183 |
gr.Markdown("#### Configurações de Passos de Inferência (First Pass)")
|
|
@@ -185,8 +176,14 @@ def _build_generation_controls(ui: dict):
|
|
| 185 |
ui['fp_num_inference_steps'] = gr.Slider(label="Número de Passos", minimum=0, maximum=100, step=1, value=20, info="Padrão LTX: 20.")
|
| 186 |
ui['fp_skip_initial_steps'] = gr.Slider(label="Pular Passos Iniciais", minimum=0, maximum=100, step=1, value=0)
|
| 187 |
ui['fp_skip_final_steps'] = gr.Slider(label="Pular Passos Finais", minimum=0, maximum=100, step=1, value=0)
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
ui['generate_low_btn'] = gr.Button("1. Gerar Vídeo Base", variant="primary")
|
| 191 |
|
| 192 |
def _build_postprod_controls(ui: dict):
|
|
@@ -205,8 +202,7 @@ def _build_postprod_controls(ui: dict):
|
|
| 205 |
with gr.TabItem("✨ Upscaler de Resolução (SeedVR)"):
|
| 206 |
is_seedvr_available = seedvr_inference_server is not None
|
| 207 |
if not is_seedvr_available:
|
| 208 |
-
gr.Markdown("🔴 **AVISO: O serviço SeedVR não está disponível
|
| 209 |
-
|
| 210 |
with gr.Row():
|
| 211 |
with gr.Column(scale=1):
|
| 212 |
ui['seedvr_seed'] = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
|
|
@@ -220,29 +216,30 @@ def _build_postprod_controls(ui: dict):
|
|
| 220 |
|
| 221 |
def _register_event_handlers(app_state: gr.State, ui: dict):
|
| 222 |
"""Registra todos os manipuladores de eventos do Gradio."""
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
|
|
|
|
| 225 |
def update_seed_display(state):
|
| 226 |
return state.get("used_seed", "N/A")
|
| 227 |
|
| 228 |
gen_inputs = [
|
| 229 |
ui['generation_mode'], ui['prompt'], ui['neg_prompt'], ui['start_image'],
|
| 230 |
ui['height'], ui['width'], ui['duration'],
|
|
|
|
| 231 |
ui['fp_num_inference_steps'], ui['fp_skip_initial_steps'], ui['fp_skip_final_steps'],
|
| 232 |
]
|
| 233 |
gen_outputs = [ui['low_res_video_output'], app_state, ui['post_prod_group']]
|
| 234 |
|
| 235 |
-
(
|
| 236 |
-
|
| 237 |
-
.click(fn=run_generate_base_video, inputs=gen_inputs, outputs=gen_outputs)
|
| 238 |
-
.then(fn=update_seed_display, inputs=[app_state], outputs=[ui['used_seed_display']])
|
| 239 |
-
)
|
| 240 |
|
| 241 |
refine_inputs = [app_state, ui['prompt'], ui['neg_prompt']]
|
| 242 |
refine_outputs = [ui['ltx_refined_video_output'], app_state]
|
| 243 |
ui['ltx_refine_btn'].click(fn=run_ltx_refinement, inputs=refine_inputs, outputs=refine_outputs)
|
| 244 |
|
| 245 |
-
if 'run_seedvr_btn' in ui:
|
| 246 |
seedvr_inputs = [app_state, ui['seedvr_seed'], ui['seedvr_resolution'], ui['seedvr_batch_size'], ui['seedvr_fps']]
|
| 247 |
seedvr_outputs = [ui['seedvr_video_output'], ui['seedvr_status_box']]
|
| 248 |
ui['run_seedvr_btn'].click(fn=run_seedvr_upscaling, inputs=seedvr_inputs, outputs=seedvr_outputs)
|
|
|
|
| 1 |
# FILE: app.py
|
| 2 |
# DESCRIPTION: Final Gradio web interface for the ADUC-SDR Video Suite.
|
| 3 |
+
# Features dimension sliders locked to multiples of 8, a unified LTX workflow,
|
| 4 |
+
# advanced controls, integrated SeedVR upscaling, and detailed debug logging.
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import traceback
|
| 8 |
import sys
|
| 9 |
import os
|
| 10 |
import logging
|
|
|
|
| 11 |
|
| 12 |
# ==============================================================================
|
| 13 |
# --- IMPORTAÇÃO DOS SERVIÇOS DE BACKEND E UTILS ---
|
|
|
|
| 21 |
from api.utils.debug_utils import log_function_io
|
| 22 |
|
| 23 |
# Serviço especialista para upscaling de resolução (SeedVR)
|
| 24 |
+
from api.seedvr_server import seedvr_server_singleton as seedvr_inference_server
|
|
|
|
| 25 |
|
| 26 |
logging.info("All backend services (LTX, SeedVR) and debug utils imported successfully.")
|
| 27 |
|
| 28 |
except ImportError as e:
|
| 29 |
+
def log_function_io(func): return func
|
|
|
|
|
|
|
| 30 |
logging.warning(f"Could not import a module, debug logger might be disabled. SeedVR might be unavailable. Details: {e}")
|
|
|
|
| 31 |
if 'video_generation_service' not in locals():
|
| 32 |
logging.critical(f"FATAL: Main LTX service failed to import.", exc_info=True)
|
| 33 |
sys.exit(1)
|
|
|
|
| 34 |
if 'seedvr_inference_server' not in locals():
|
| 35 |
seedvr_inference_server = None
|
| 36 |
logging.warning("SeedVR server could not be initialized. The SeedVR upscaling tab will be disabled.")
|
|
|
|
| 37 |
except Exception as e:
|
| 38 |
logging.critical(f"FATAL ERROR: An unexpected error occurred during backend initialization. Details: {e}", exc_info=True)
|
| 39 |
sys.exit(1)
|
|
|
|
| 46 |
def run_generate_base_video(
|
| 47 |
generation_mode: str, prompt: str, neg_prompt: str, start_img: str,
|
| 48 |
height: int, width: int, duration: float,
|
| 49 |
+
fp_guidance_preset: str, fp_guidance_scale_list: str, fp_stg_scale_list: str,
|
| 50 |
fp_num_inference_steps: int, fp_skip_initial_steps: int, fp_skip_final_steps: int,
|
| 51 |
progress=gr.Progress(track_tqdm=True)
|
| 52 |
) -> tuple:
|
|
|
|
| 63 |
)
|
| 64 |
|
| 65 |
ltx_configs = {
|
| 66 |
+
"guidance_preset": fp_guidance_preset,
|
| 67 |
+
"guidance_scale_list": fp_guidance_scale_list,
|
| 68 |
+
"stg_scale_list": fp_stg_scale_list,
|
| 69 |
"num_inference_steps": fp_num_inference_steps,
|
| 70 |
"skip_initial_inference_steps": fp_skip_initial_steps,
|
| 71 |
"skip_final_inference_steps": fp_skip_final_steps,
|
|
|
|
| 111 |
logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
|
| 112 |
raise gr.Error(error_message)
|
| 113 |
|
|
|
|
| 114 |
@log_function_io
|
| 115 |
def run_seedvr_upscaling(state: dict, seed: int, resolution: int, batch_size: int, fps: int, progress=gr.Progress(track_tqdm=True)) -> tuple:
|
| 116 |
"""Wrapper para o upscale de resolução SeedVR."""
|
|
|
|
| 142 |
|
| 143 |
def build_ui():
|
| 144 |
"""Constrói a interface completa do Gradio."""
|
|
|
|
| 145 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
|
| 146 |
app_state = gr.State(value={"low_res_video": None, "low_res_latents": None, "used_seed": None})
|
| 147 |
ui_components = {}
|
|
|
|
| 148 |
gr.Markdown("# ADUC-SDR Video Suite - LTX & SeedVR Workflow", elem_id="main-title")
|
|
|
|
| 149 |
with gr.Row():
|
| 150 |
+
with gr.Column(scale=1): _build_generation_controls(ui_components)
|
|
|
|
| 151 |
with gr.Column(scale=1):
|
| 152 |
gr.Markdown("### Etapa 1: Vídeo Base Gerado")
|
| 153 |
ui_components['low_res_video_output'] = gr.Video(label="O resultado aparecerá aqui", interactive=False)
|
| 154 |
+
ui_components['used_seed_display'] = gr.Textbox(label="Seed Utilizada", interactive=False)
|
|
|
|
| 155 |
_build_postprod_controls(ui_components)
|
| 156 |
+
_register_event_handlers(app_state, ui_components)
|
|
|
|
| 157 |
return demo
|
| 158 |
|
| 159 |
def _build_generation_controls(ui: dict):
|
| 160 |
"""Constrói os componentes da UI para a Etapa 1: Geração."""
|
| 161 |
gr.Markdown("### Configurações de Geração")
|
| 162 |
+
ui['generation_mode'] = gr.Radio(label="Modo de Geração", choices=["Simples (Prompt Único)", "Narrativa (Múltiplos Prompts)"], value="Narrativa (Múltiplos Prompts)", info="Simples para uma ação contínua, Narrativa para uma sequência (uma cena por linha).")
|
| 163 |
ui['prompt'] = gr.Textbox(label="Prompt(s)", value="Um leão majestoso caminha pela savana\nEle sobe em uma grande pedra e olha o horizonte", lines=4)
|
| 164 |
+
ui['neg_prompt'] = gr.Textbox(label="Negative Prompt", value="blurry, low quality, bad anatomy, deformed", lines=2)
|
| 165 |
ui['start_image'] = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload"])
|
| 166 |
|
| 167 |
with gr.Accordion("Parâmetros Principais", open=True):
|
| 168 |
ui['duration'] = gr.Slider(label="Duração Total (s)", value=4, step=1, minimum=1, maximum=30)
|
| 169 |
with gr.Row():
|
| 170 |
+
ui['height'] = gr.Slider(label="Height", value=432, step=8, minimum=256, maximum=1024)
|
| 171 |
+
ui['width'] = gr.Slider(label="Width", value=768, step=8, minimum=256, maximum=1024)
|
| 172 |
|
| 173 |
with gr.Accordion("Opções Avançadas LTX", open=False):
|
| 174 |
gr.Markdown("#### Configurações de Passos de Inferência (First Pass)")
|
|
|
|
| 176 |
ui['fp_num_inference_steps'] = gr.Slider(label="Número de Passos", minimum=0, maximum=100, step=1, value=20, info="Padrão LTX: 20.")
|
| 177 |
ui['fp_skip_initial_steps'] = gr.Slider(label="Pular Passos Iniciais", minimum=0, maximum=100, step=1, value=0)
|
| 178 |
ui['fp_skip_final_steps'] = gr.Slider(label="Pular Passos Finais", minimum=0, maximum=100, step=1, value=0)
|
| 179 |
+
with gr.Tabs():
|
| 180 |
+
with gr.TabItem("Configurações de Guiagem (First Pass)"):
|
| 181 |
+
ui['fp_guidance_preset'] = gr.Dropdown(label="Preset de Guiagem", choices=["Padrão (Recomendado)", "Agressivo", "Suave", "Customizado"], value="Padrão (Recomendado)", info="Controla o comportamento da guiagem durante a difusão.")
|
| 182 |
+
with gr.Group(visible=False) as ui['custom_guidance_group']:
|
| 183 |
+
gr.Markdown("⚠️ Edite as listas em formato JSON. Ex: `[1.0, 2.5, 3.0]`")
|
| 184 |
+
ui['fp_guidance_scale_list'] = gr.Textbox(label="Lista de Guidance Scale", value="[1, 1, 6, 8, 6, 1, 1]")
|
| 185 |
+
ui['fp_stg_scale_list'] = gr.Textbox(label="Lista de STG Scale (Movimento)", value="[0, 0, 4, 4, 4, 2, 1]")
|
| 186 |
+
|
| 187 |
ui['generate_low_btn'] = gr.Button("1. Gerar Vídeo Base", variant="primary")
|
| 188 |
|
| 189 |
def _build_postprod_controls(ui: dict):
|
|
|
|
| 202 |
with gr.TabItem("✨ Upscaler de Resolução (SeedVR)"):
|
| 203 |
is_seedvr_available = seedvr_inference_server is not None
|
| 204 |
if not is_seedvr_available:
|
| 205 |
+
gr.Markdown("🔴 **AVISO: O serviço SeedVR não está disponível.**")
|
|
|
|
| 206 |
with gr.Row():
|
| 207 |
with gr.Column(scale=1):
|
| 208 |
ui['seedvr_seed'] = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
|
|
|
|
| 216 |
|
| 217 |
def _register_event_handlers(app_state: gr.State, ui: dict):
|
| 218 |
"""Registra todos os manipuladores de eventos do Gradio."""
|
| 219 |
+
def toggle_custom_guidance(preset_choice: str) -> gr.update:
|
| 220 |
+
return gr.update(visible=(preset_choice == "Customizado"))
|
| 221 |
|
| 222 |
+
ui['fp_guidance_preset'].change(fn=toggle_custom_guidance, inputs=ui['fp_guidance_preset'], outputs=ui['custom_guidance_group'])
|
| 223 |
+
|
| 224 |
def update_seed_display(state):
|
| 225 |
return state.get("used_seed", "N/A")
|
| 226 |
|
| 227 |
gen_inputs = [
|
| 228 |
ui['generation_mode'], ui['prompt'], ui['neg_prompt'], ui['start_image'],
|
| 229 |
ui['height'], ui['width'], ui['duration'],
|
| 230 |
+
ui['fp_guidance_preset'], ui['fp_guidance_scale_list'], ui['fp_stg_scale_list'],
|
| 231 |
ui['fp_num_inference_steps'], ui['fp_skip_initial_steps'], ui['fp_skip_final_steps'],
|
| 232 |
]
|
| 233 |
gen_outputs = [ui['low_res_video_output'], app_state, ui['post_prod_group']]
|
| 234 |
|
| 235 |
+
(ui['generate_low_btn'].click(fn=run_generate_base_video, inputs=gen_inputs, outputs=gen_outputs)
|
| 236 |
+
.then(fn=update_seed_display, inputs=[app_state], outputs=[ui['used_seed_display']]))
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
refine_inputs = [app_state, ui['prompt'], ui['neg_prompt']]
|
| 239 |
refine_outputs = [ui['ltx_refined_video_output'], app_state]
|
| 240 |
ui['ltx_refine_btn'].click(fn=run_ltx_refinement, inputs=refine_inputs, outputs=refine_outputs)
|
| 241 |
|
| 242 |
+
if 'run_seedvr_btn' in ui and ui['run_seedvr_btn'].interactive:
|
| 243 |
seedvr_inputs = [app_state, ui['seedvr_seed'], ui['seedvr_resolution'], ui['seedvr_batch_size'], ui['seedvr_fps']]
|
| 244 |
seedvr_outputs = [ui['seedvr_video_output'], ui['seedvr_status_box']]
|
| 245 |
ui['run_seedvr_btn'].click(fn=run_seedvr_upscaling, inputs=seedvr_inputs, outputs=seedvr_outputs)
|