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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -228
app.py DELETED
@@ -1,228 +0,0 @@
1
- # FILE: app.py
2
- # DESCRIPTION: Final Gradio web interface for the ADUC-SDR Video Suite.
3
- # This version definitively removes the guidance settings from the UI for a streamlined experience.
4
-
5
- import gradio as gr
6
- import traceback
7
- import sys
8
- import os
9
- import logging
10
-
11
- # ==============================================================================
12
- # --- IMPORTAÇÃO DOS SERVIÇOS DE BACKEND E UTILS ---
13
- # ==============================================================================
14
- try:
15
- from api.ltx_server_refactored_complete import video_generation_service
16
- from api.utils.debug_utils import log_function_io
17
- from api.seedvr_server import seedvr_server_singleton as seedvr_inference_server
18
- logging.info("All backend services (LTX, SeedVR) and debug utils imported successfully.")
19
- except ImportError as e:
20
- def log_function_io(func): return func
21
- logging.warning(f"Could not import a module. Some services or debug logs may be unavailable. Details: {e}")
22
- if 'video_generation_service' not in locals():
23
- logging.critical(f"FATAL: Main LTX service failed to import.", exc_info=True)
24
- sys.exit(1)
25
- if 'seedvr_inference_server' not in locals():
26
- seedvr_inference_server = None
27
- logging.warning("SeedVR server could not be initialized. Upscaling tab will be disabled.")
28
- except Exception as e:
29
- logging.critical(f"FATAL ERROR during backend initialization. Details: {e}", exc_info=True)
30
- sys.exit(1)
31
-
32
- # ==============================================================================
33
- # --- FUNÇÕES WRAPPER (PONTE ENTRE UI E BACKEND) ---
34
- # ==============================================================================
35
-
36
- @log_function_io
37
- def run_generate_base_video(
38
- generation_mode: str, prompt: str, neg_prompt: str, start_img: str,
39
- height: int, width: int, duration: float,
40
- fp_num_inference_steps: int, fp_skip_initial_steps: int, fp_skip_final_steps: int,
41
- progress=gr.Progress(track_tqdm=True)
42
- ) -> tuple:
43
- """Wrapper that collects UI data and calls the backend (without guidance parameters)."""
44
- try:
45
- logging.info(f"[UI] Request received. Selected mode: {generation_mode}")
46
- initial_conditions = []
47
- if start_img:
48
- num_frames_estimate = int(duration * 24)
49
- items_list = [[start_img, 0, 1.0]]
50
- initial_conditions = video_generation_service.prepare_condition_items(
51
- items_list, height, width, num_frames_estimate
52
- )
53
-
54
- ltx_configs = {
55
- "num_inference_steps": fp_num_inference_steps,
56
- "skip_initial_inference_steps": fp_skip_initial_steps,
57
- "skip_final_inference_steps": fp_skip_final_steps,
58
- }
59
-
60
- video_path, tensor_path, final_seed = video_generation_service.generate_low_resolution(
61
- prompt=prompt, negative_prompt=neg_prompt,
62
- height=height, width=width, duration=duration,
63
- initial_conditions=initial_conditions, ltx_configs_override=ltx_configs
64
- )
65
-
66
- if not video_path: raise RuntimeError("Backend failed to return a valid video path.")
67
- new_state = {"low_res_video": video_path, "low_res_latents": tensor_path, "used_seed": final_seed}
68
- logging.info(f"[UI] Base video generation successful. Seed used: {final_seed}, Path: {video_path}")
69
- return video_path, new_state, gr.update(visible=True)
70
-
71
- except Exception as e:
72
- error_message = f"❌ An error occurred during base generation:\n{e}"
73
- logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
74
- raise gr.Error(error_message)
75
-
76
- @log_function_io
77
- def run_ltx_refinement(state: dict, prompt: str, neg_prompt: str, progress=gr.Progress(track_tqdm=True)) -> tuple:
78
- """Wrapper for the LTX texture refinement function."""
79
- if not state or not state.get("low_res_latents"):
80
- raise gr.Error("Error: Please generate a base video in Step 1 before refining.")
81
- try:
82
- logging.info(f"[UI] Requesting LTX refinement for latents: {state.get('low_res_latents')}")
83
- video_path, tensor_path = video_generation_service.generate_upscale_denoise(
84
- latents_path=state["low_res_latents"],
85
- prompt=prompt, negative_prompt=neg_prompt,
86
- seed=state["used_seed"]
87
- )
88
- state["refined_video_ltx"] = video_path
89
- state["refined_latents_ltx"] = tensor_path
90
- logging.info(f"[UI] LTX refinement successful. Path: {video_path}")
91
- return video_path, state
92
- except Exception as e:
93
- error_message = f"❌ An error occurred during LTX Refinement:\n{e}"
94
- logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
95
- raise gr.Error(error_message)
96
-
97
- @log_function_io
98
- def run_seedvr_upscaling(state: dict, seed: int, resolution: int, batch_size: int, fps: int, progress=gr.Progress(track_tqdm=True)) -> tuple:
99
- """Wrapper for the SeedVR resolution upscaling service."""
100
- if not state or not state.get("low_res_video"):
101
- raise gr.Error("Error: Please generate a base video in Step 1 before upscaling.")
102
- if not seedvr_inference_server:
103
- raise gr.Error("Error: The SeedVR upscaling server is not available.")
104
- try:
105
- logging.info(f"[UI] Requesting SeedVR upscaling for video: {state.get('low_res_video')}")
106
- def progress_wrapper(p, desc=""): progress(p, desc=desc)
107
- output_filepath = seedvr_inference_server.run_inference(
108
- file_path=state["low_res_video"], seed=int(seed), resolution=int(resolution),
109
- batch_size=int(batch_size), fps=float(fps), progress=progress_wrapper
110
- )
111
- status_message = f"✅ Upscaling complete!\nSaved to: {output_filepath}"
112
- logging.info(f"[UI] SeedVR upscaling successful. Path: {output_filepath}")
113
- return gr.update(value=output_filepath), gr.update(value=status_message)
114
- except Exception as e:
115
- error_message = f"❌ An error occurred during SeedVR Upscaling:\n{e}"
116
- logging.error(f"{error_message}\nDetails: {traceback.format_exc()}", exc_info=True)
117
- return None, gr.update(value=error_message)
118
-
119
- # ==============================================================================
120
- # --- CONSTRUÇÃO DA INTERFACE GRADIO ---
121
- # ==============================================================================
122
-
123
- def build_ui():
124
- """Builds the entire Gradio application UI."""
125
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
126
- app_state = gr.State(value={"low_res_video": None, "low_res_latents": None, "used_seed": None})
127
- ui_components = {}
128
- gr.Markdown("# ADUC-SDR Video Suite - LTX & SeedVR Workflow", elem_id="main-title")
129
- with gr.Row():
130
- with gr.Column(scale=1): _build_generation_controls(ui_components)
131
- with gr.Column(scale=1):
132
- gr.Markdown("### Etapa 1: Vídeo Base Gerado")
133
- ui_components['low_res_video_output'] = gr.Video(label="O resultado aparecerá aqui", interactive=False)
134
- ui_components['used_seed_display'] = gr.Textbox(label="Seed Utilizada", interactive=False)
135
- _build_postprod_controls(ui_components)
136
- _register_event_handlers(app_state, ui_components)
137
- return demo
138
-
139
- def _build_generation_controls(ui: dict):
140
- """Builds the UI components for Step 1, with the guidance section removed."""
141
- gr.Markdown("### Configurações de Geração")
142
- ui['generation_mode'] = gr.Radio(label="Modo de Geração", choices=["Simples (Prompt Único)", "Narrativa (Múltiplos Prompts)"], value="Narrativa (Múltiplos Prompts)")
143
- 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)
144
- ui['neg_prompt'] = gr.Textbox(label="Negative Prompt", value="blurry, low quality, bad anatomy, deformed", lines=2)
145
- ui['start_image'] = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload"])
146
-
147
- with gr.Accordion("Parâmetros Principais", open=True):
148
- ui['duration'] = gr.Slider(label="Duração Total (s)", value=4, step=1, minimum=1, maximum=30)
149
- with gr.Row():
150
- ui['height'] = gr.Slider(label="Height", value=432, step=8, minimum=256, maximum=1024)
151
- ui['width'] = gr.Slider(label="Width", value=768, step=8, minimum=256, maximum=1024)
152
-
153
- with gr.Accordion("Opções Avançadas LTX", open=False):
154
- gr.Markdown("#### Configurações de Passos de Inferência (First Pass)")
155
- gr.Markdown("*Deixe o valor padrão (ex: 20) ou 0 para usar a configuração do `config.yaml`.*")
156
- 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.")
157
- ui['fp_skip_initial_steps'] = gr.Slider(label="Pular Passos Iniciais", minimum=0, maximum=100, step=1, value=0)
158
- ui['fp_skip_final_steps'] = gr.Slider(label="Pular Passos Finais", minimum=0, maximum=100, step=1, value=0)
159
-
160
- ui['generate_low_btn'] = gr.Button("1. Gerar Vídeo Base", variant="primary")
161
-
162
- def _build_postprod_controls(ui: dict):
163
- """Builds the UI components for Step 2: Post-Production."""
164
- with gr.Group(visible=False) as ui['post_prod_group']:
165
- gr.Markdown("--- \n## Etapa 2: Pós-Produção")
166
- with gr.Tabs():
167
- with gr.TabItem("🚀 Upscaler de Textura (LTX)"):
168
- with gr.Row():
169
- with gr.Column(scale=1):
170
- gr.Markdown("Usa o prompt e a semente originais para refinar o vídeo, adicionando detalhes e texturas de alta qualidade.")
171
- ui['ltx_refine_btn'] = gr.Button("2. Aplicar Refinamento LTX", variant="primary")
172
- with gr.Column(scale=1):
173
- ui['ltx_refined_video_output'] = gr.Video(label="Vídeo com Textura Refinada", interactive=False)
174
-
175
- with gr.TabItem("✨ Upscaler de Resolução (SeedVR)"):
176
- is_seedvr_available = seedvr_inference_server is not None
177
- if not is_seedvr_available:
178
- gr.Markdown("🔴 **AVISO: O serviço SeedVR não está disponível.**")
179
- with gr.Row():
180
- with gr.Column(scale=1):
181
- ui['seedvr_seed'] = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
182
- ui['seedvr_resolution'] = gr.Slider(minimum=720, maximum=2160, value=1080, step=8, label="Resolução Vertical Alvo")
183
- ui['seedvr_batch_size'] = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
184
- ui['seedvr_fps'] = gr.Number(label="FPS de Saída (0 = original)", value=0)
185
- ui['run_seedvr_btn'] = gr.Button("2. Iniciar Upscaling SeedVR", variant="primary", interactive=is_seedvr_available)
186
- with gr.Column(scale=1):
187
- ui['seedvr_video_output'] = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
188
- ui['seedvr_status_box'] = gr.Textbox(label="Status do SeedVR", value="Aguardando...", lines=3, interactive=False)
189
-
190
- def _register_event_handlers(app_state: gr.State, ui: dict):
191
- """Registers all Gradio event handlers."""
192
- def update_seed_display(state):
193
- return state.get("used_seed", "N/A")
194
-
195
- gen_inputs = [
196
- ui['generation_mode'], ui['prompt'], ui['neg_prompt'], ui['start_image'],
197
- ui['height'], ui['width'], ui['duration'],
198
- ui['fp_num_inference_steps'], ui['fp_skip_initial_steps'], ui['fp_skip_final_steps'],
199
- ]
200
- gen_outputs = [ui['low_res_video_output'], app_state, ui['post_prod_group']]
201
-
202
- (ui['generate_low_btn'].click(fn=run_generate_base_video, inputs=gen_inputs, outputs=gen_outputs)
203
- .then(fn=update_seed_display, inputs=[app_state], outputs=[ui['used_seed_display']]))
204
-
205
- refine_inputs = [app_state, ui['prompt'], ui['neg_prompt']]
206
- refine_outputs = [ui['ltx_refined_video_output'], app_state]
207
- ui['ltx_refine_btn'].click(fn=run_ltx_refinement, inputs=refine_inputs, outputs=refine_outputs)
208
-
209
- if 'run_seedvr_btn' in ui and ui['run_seedvr_btn'].interactive:
210
- seedvr_inputs = [app_state, ui['seedvr_seed'], ui['seedvr_resolution'], ui['seedvr_batch_size'], ui['seedvr_fps']]
211
- seedvr_outputs = [ui['seedvr_video_output'], ui['seedvr_status_box']]
212
- ui['run_seedvr_btn'].click(fn=run_seedvr_upscaling, inputs=seedvr_inputs, outputs=seedvr_outputs)
213
-
214
- # ==============================================================================
215
- # --- PONTO DE ENTRADA DA APLICAÇÃO ---
216
- # ==============================================================================
217
- if __name__ == "__main__":
218
- log_level = os.environ.get("ADUC_LOG_LEVEL", "INFO").upper()
219
- logging.basicConfig(level=log_level, format='[%(levelname)s] [%(name)s] %(message)s')
220
-
221
- print("Building Gradio UI...")
222
- gradio_app = build_ui()
223
- print("Launching Gradio app...")
224
- gradio_app.queue().launch(
225
- server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
226
- server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
227
- show_error=True
228
- )