eeuuia commited on
Commit
7c81ca5
·
verified ·
1 Parent(s): 42998d3

Upload app (1).py

Browse files
Files changed (1) hide show
  1. app (1).py +262 -0
app (1).py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ---
14
+ # ==============================================================================
15
+
16
+ try:
17
+ # Serviço principal para geração LTX
18
+ from api.ltx_server_refactored_complete import video_generation_service
19
+
20
+ # Nosso decorador de logging para depuração
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)
40
+
41
+ # ==============================================================================
42
+ # --- FUNÇÕES WRAPPER (PONTE ENTRE UI E BACKEND) ---
43
+ # ==============================================================================
44
+
45
+ @log_function_io
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:
53
+ """Wrapper para a geração do vídeo base LTX."""
54
+ try:
55
+ logging.info(f"[UI] Request received. Selected mode: {generation_mode}")
56
+
57
+ initial_conditions = []
58
+ if start_img:
59
+ num_frames_estimate = int(duration * 24)
60
+ items_list = [[start_img, 0, 1.0]]
61
+ initial_conditions = video_generation_service.prepare_condition_items(
62
+ items_list, height, width, num_frames_estimate
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,
72
+ }
73
+
74
+ video_path, tensor_path, final_seed = video_generation_service.generate_low_resolution(
75
+ prompt=prompt, negative_prompt=neg_prompt,
76
+ height=height, width=width, duration=duration,
77
+ initial_conditions=initial_conditions, ltx_configs_override=ltx_configs
78
+ )
79
+
80
+ if not video_path: raise RuntimeError("Backend failed to return a valid video path.")
81
+
82
+ new_state = {"low_res_video": video_path, "low_res_latents": tensor_path, "used_seed": final_seed}
83
+ logging.info(f"[UI] Base video generation successful. Seed used: {final_seed}, Path: {video_path}")
84
+ return video_path, new_state, gr.update(visible=True)
85
+
86
+ except Exception as e:
87
+ error_message = f"❌ An error occurred during base generation:\n{e}"
88
+ logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
89
+ raise gr.Error(error_message)
90
+
91
+ @log_function_io
92
+ def run_ltx_refinement(state: dict, prompt: str, neg_prompt: str, progress=gr.Progress(track_tqdm=True)) -> tuple:
93
+ """Wrapper para o refinamento de textura LTX."""
94
+ if not state or not state.get("low_res_latents"):
95
+ raise gr.Error("Error: Please generate a base video in Step 1 before refining.")
96
+
97
+ try:
98
+ logging.info(f"[UI] Requesting LTX refinement for latents: {state.get('low_res_latents')}")
99
+ video_path, tensor_path = video_generation_service.generate_upscale_denoise(
100
+ latents_path=state["low_res_latents"],
101
+ prompt=prompt,
102
+ negative_prompt=neg_prompt,
103
+ seed=state["used_seed"]
104
+ )
105
+ state["refined_video_ltx"] = video_path
106
+ state["refined_latents_ltx"] = tensor_path
107
+ logging.info(f"[UI] LTX refinement successful. Path: {video_path}")
108
+ return video_path, state
109
+ except Exception as e:
110
+ error_message = f"❌ An error occurred during LTX Refinement:\n{e}"
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."""
117
+ if not state or not state.get("low_res_video"):
118
+ raise gr.Error("Error: Please generate a base video in Step 1 before upscaling.")
119
+ if not seedvr_inference_server:
120
+ raise gr.Error("Error: The SeedVR upscaling server is not available.")
121
+
122
+ try:
123
+ logging.info(f"[UI] Requesting SeedVR upscaling for video: {state.get('low_res_video')}")
124
+ def progress_wrapper(p, desc=""): progress(p, desc=desc)
125
+
126
+ output_filepath = seedvr_inference_server.run_inference(
127
+ file_path=state["low_res_video"], seed=int(seed), resolution=int(resolution),
128
+ batch_size=int(batch_size), fps=float(fps), progress=progress_wrapper
129
+ )
130
+
131
+ status_message = f"✅ Upscaling complete!\nSaved to: {output_filepath}"
132
+ logging.info(f"[UI] SeedVR upscaling successful. Path: {output_filepath}")
133
+ return gr.update(value=output_filepath), gr.update(value=status_message)
134
+ except Exception as e:
135
+ error_message = f"❌ An error occurred during SeedVR Upscaling:\n{e}"
136
+ logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
137
+ return None, gr.update(value=error_message)
138
+
139
+ # ==============================================================================
140
+ # --- CONSTRUÇÃO DA INTERFACE GRADIO ---
141
+ # ==============================================================================
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)")
175
+ gr.Markdown("*Deixe o valor padrão (ex: 20) ou 0 para usar a configuração do `config.yaml`.*")
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):
190
+ """Constrói os componentes da UI para a Etapa 2: Pós-Produção."""
191
+ with gr.Group(visible=False) as ui['post_prod_group']:
192
+ gr.Markdown("--- \n## Etapa 2: Pós-Produção")
193
+ with gr.Tabs():
194
+ with gr.TabItem("🚀 Upscaler de Textura (LTX)"):
195
+ with gr.Row():
196
+ with gr.Column(scale=1):
197
+ gr.Markdown("Usa o prompt e a semente originais para refinar o vídeo, adicionando detalhes e texturas de alta qualidade.")
198
+ ui['ltx_refine_btn'] = gr.Button("2. Aplicar Refinamento LTX", variant="primary")
199
+ with gr.Column(scale=1):
200
+ ui['ltx_refined_video_output'] = gr.Video(label="Vídeo com Textura Refinada", interactive=False)
201
+
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")
209
+ ui['seedvr_resolution'] = gr.Slider(minimum=720, maximum=2160, value=1080, step=8, label="Resolução Vertical Alvo")
210
+ ui['seedvr_batch_size'] = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
211
+ ui['seedvr_fps'] = gr.Number(label="FPS de Saída (0 = original)", value=0)
212
+ ui['run_seedvr_btn'] = gr.Button("2. Iniciar Upscaling SeedVR", variant="primary", interactive=is_seedvr_available)
213
+ with gr.Column(scale=1):
214
+ ui['seedvr_video_output'] = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
215
+ ui['seedvr_status_box'] = gr.Textbox(label="Status do SeedVR", value="Aguardando...", lines=3, interactive=False)
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)
246
+
247
+ # ==============================================================================
248
+ # --- PONTO DE ENTRADA DA APLICAÇÃO ---
249
+ # ==============================================================================
250
+
251
+ if __name__ == "__main__":
252
+ log_level = os.environ.get("ADUC_LOG_LEVEL", "INFO").upper()
253
+ logging.basicConfig(level=log_level, format='[%(levelname)s] [%(name)s] %(message)s')
254
+
255
+ print("Building Gradio UI...")
256
+ gradio_app = build_ui()
257
+ print("Launching Gradio app...")
258
+ gradio_app.queue().launch(
259
+ server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
260
+ server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
261
+ show_error=True
262
+ )