Eueuiaa commited on
Commit
db47818
·
verified ·
1 Parent(s): 21e9173

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +231 -0
app.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app_refactored_with_postprod.py
2
+
3
+ import gradio as gr
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+ import traceback
8
+
9
+ # --- Import dos Serviços de Backend ---
10
+
11
+ # Serviço LTX para geração de vídeo base e refinamento de textura
12
+ try:
13
+ from api.ltx_server_refactored import video_generation_service
14
+ except ImportError:
15
+ print("ERRO FATAL: Não foi possível importar 'video_generation_service' de 'api.ltx_server_refactored'.")
16
+ print("Verifique se o arquivo existe e se o ambiente está configurado corretamente.")
17
+ sys.exit(1)
18
+
19
+
20
+ # Serviço SeedVR para upscaling de alta qualidade
21
+ try:
22
+ from api.seedvr_server import SeedVRServer
23
+ except ImportError:
24
+ print("AVISO: Não foi possível importar SeedVRServer. A aba de upscaling SeedVR será desativada.")
25
+ SeedVRServer = None # Define como None para tratamento gracioso de erro
26
+
27
+ # Inicializa o servidor SeedVR uma vez, se disponível
28
+ if SeedVRServer:
29
+ print("Inicializando o servidor de inferência SeedVR...")
30
+ seedvr_inference_server = SeedVRServer()
31
+ else:
32
+ seedvr_inference_server = None
33
+
34
+ # --- ESTADO DA SESSÃO ---
35
+ # Mantém os caminhos dos arquivos entre os cliques dos botões
36
+ def create_initial_state():
37
+ return {
38
+ "low_res_video": None,
39
+ "low_res_latents": None,
40
+ "refined_video": None,
41
+ "refined_latents": None,
42
+ "used_seed": None
43
+ }
44
+
45
+ # --- FUNÇÕES WRAPPER PARA A UI ---
46
+
47
+ def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
48
+ """
49
+ Executa a primeira etapa: geração de um vídeo base em baixa resolução.
50
+ """
51
+ print("UI: Chamando generate_low")
52
+
53
+ try:
54
+ # 1. Preparar conditioning_items (se uma imagem de início for fornecida)
55
+ conditioning_items = []
56
+ if start_img:
57
+ # A função `prepare_condition_items` precisa de uma estimativa do número de frames
58
+ num_frames_estimate = int(duration * 24)
59
+ items_list = [[start_img, 0, 1.0]] # Imagem de início, no frame 0, com peso 1.0
60
+ conditioning_items = video_generation_service.prepare_condition_items(items_list, height, width, num_frames_estimate)
61
+
62
+ # Determina a seed a ser usada
63
+ used_seed = None if randomize_seed else seed
64
+
65
+ # 2. Chamar a função de geração de baixa resolução do backend
66
+ video_path, tensor_path, final_seed = video_generation_service.generate_low(
67
+ prompt=prompt, negative_prompt=neg_prompt,
68
+ height=height, width=width, duration=duration,
69
+ guidance_scale=cfg, seed=used_seed,
70
+ conditioning_items=conditioning_items
71
+ )
72
+
73
+ # 3. Atualizar o estado da aplicação com os caminhos dos arquivos resultantes
74
+ new_state = {
75
+ "low_res_video": video_path,
76
+ "low_res_latents": tensor_path,
77
+ "refined_video": None, # Limpa resultados de execuções anteriores
78
+ "refined_latents": None,
79
+ "used_seed": final_seed
80
+ }
81
+
82
+ # 4. Retorna os resultados para a UI
83
+ # - O caminho do vídeo para o componente de vídeo
84
+ # - O novo estado para o componente gr.State
85
+ # - Um update para tornar o grupo de pós-produção visível
86
+ return video_path, new_state, gr.update(visible=True)
87
+
88
+ except Exception as e:
89
+ error_message = f"❌ Ocorreu um erro na Geração Base:\n{e}"
90
+ print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
91
+ raise gr.Error(error_message)
92
+
93
+
94
+ def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
95
+ """
96
+ Função de callback que executa o processo de upscaling com SeedVR.
97
+ """
98
+ if not state or not state.get("low_res_video"):
99
+ raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
100
+ if not seedvr_inference_server:
101
+ raise gr.Error("Erro: O servidor SeedVR não está disponível. Verifique a instalação e os logs.")
102
+
103
+ video_path = state["low_res_video"]
104
+
105
+ progress(0, desc="Iniciando SeedVR Upscaling...")
106
+ print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
107
+
108
+ try:
109
+ # Wrapper para a barra de progresso do Gradio
110
+ def progress_wrapper(p, desc=""):
111
+ progress(p, desc=desc)
112
+ print(f"⌛ Progresso SeedVR: {p*100:.1f}% - {desc}")
113
+
114
+ # Chama o método de inferência do servidor SeedVR
115
+ output_filepath = seedvr_inference_server.run_inference(
116
+ file_path=video_path,
117
+ seed=seed,
118
+ resolution=resolution,
119
+ batch_size=batch_size,
120
+ fps=fps,
121
+ progress=progress_wrapper
122
+ )
123
+
124
+ final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
125
+ print(final_message)
126
+ # Retorna o vídeo e a mensagem de sucesso para a UI
127
+ return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
128
+
129
+ except Exception as e:
130
+ error_message = f"❌ Ocorreu um erro grave durante o upscaling com SeedVR:\n{e}"
131
+ print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
132
+ # Retorna None para o vídeo e a mensagem de erro para o status box
133
+ return None, gr.update(value=error_message, interactive=False)
134
+
135
+
136
+ # --- DEFINIÇÃO DA INTERFACE GRADIO ---
137
+ with gr.Blocks(css="#col-container { margin: 0 auto; max-width: 900px; }", theme=gr.themes.Monochrome()) as demo:
138
+ gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
139
+
140
+ # Componente invisível para armazenar o estado da aplicação (caminhos de arquivos, etc.)
141
+ app_state = gr.State(value=create_initial_state())
142
+
143
+ # --- ETAPA 1: Geração Base ---
144
+ with gr.Row():
145
+ with gr.Column(scale=1):
146
+ gr.Markdown("### Etapa 1: Configurações de Geração")
147
+ prompt_input = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
148
+ neg_prompt_input = gr.Textbox(label="Negative Prompt", value="worst quality, blurry, low quality, jittery", lines=2)
149
+ start_image = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload", "clipboard"])
150
+
151
+ with gr.Accordion("Parâmetros Avançados", open=False):
152
+ height_input = gr.Slider(label="Height", value=512, step=32, minimum=256, maximum=1024)
153
+ width_input = gr.Slider(label="Width", value=704, step=32, minimum=256, maximum=1024)
154
+ duration_input = gr.Slider(label="Duração (s)", value=4, step=1, minimum=1, maximum=10)
155
+ cfg_input = gr.Slider(label="Guidance Scale (CFG)", value=3.0, step=0.1, minimum=1.0, maximum=10.0)
156
+ seed_input = gr.Number(label="Seed", value=42, precision=0)
157
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
158
+
159
+ generate_low_btn = gr.Button("1. Gerar Vídeo Base (Low-Res)", variant="primary")
160
+
161
+ with gr.Column(scale=1):
162
+ gr.Markdown("### Vídeo Base Gerado")
163
+ low_res_video_output = gr.Video(label="O resultado da Etapa 1 aparecerá aqui", interactive=False)
164
+
165
+ # --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
166
+ with gr.Group(visible=False) as post_prod_group:
167
+ gr.Markdown("<hr style='margin-top: 20px; margin-bottom: 20px;'>")
168
+ gr.Markdown("## Etapa 2: Pós-Produção")
169
+ gr.Markdown("Use o vídeo gerado acima como entrada para as ferramentas abaixo.")
170
+
171
+ with gr.Tabs():
172
+ with gr.TabItem("🚀 Upscaler Textura (LTX)"):
173
+ gr.Markdown("*(Funcionalidade a ser implementada no futuro)*")
174
+ # Aqui iriam os componentes para o refinamento LTX
175
+ # refine_ltx_btn = gr.Button("Aplicar Refinamento de Textura LTX")
176
+ # refined_ltx_video_output = gr.Video(label="Vídeo com Textura Refinada")
177
+
178
+ with gr.TabItem("✨ Upscaler SeedVR"):
179
+ with gr.Row():
180
+ with gr.Column(scale=1):
181
+ gr.Markdown("### Parâmetros do SeedVR")
182
+ seedvr_seed = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
183
+ seedvr_resolution = gr.Slider(minimum=720, maximum=1440, value=1072, step=8, label="Resolução Vertical (Altura)")
184
+ seedvr_batch_size = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
185
+ seedvr_fps_output = gr.Number(label="FPS de Saída (0 = original)", value=0)
186
+ run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
187
+ if not seedvr_inference_server:
188
+ gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
189
+
190
+ with gr.Column(scale=1):
191
+ gr.Markdown("### Resultado do Upscaling")
192
+ seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
193
+ seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
194
+
195
+ with gr.TabItem("🔊 Áudio (MM-Audio)"):
196
+ gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
197
+ # Componentes para a geração de áudio viriam aqui
198
+
199
+ # --- LÓGICA DE EVENTOS DA UI ---
200
+
201
+ # Conecta o botão da Etapa 1 à sua função de backend
202
+ generate_low_btn.click(
203
+ fn=run_generate_low,
204
+ inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
205
+ outputs=[low_res_video_output, app_state, post_prod_group]
206
+ )
207
+
208
+ # Conecta o botão da Aba SeedVR à sua função de backend
209
+ run_seedvr_button.click(
210
+ fn=run_seedvr_upscaling,
211
+ inputs=[
212
+ app_state,
213
+ seedvr_seed,
214
+ seedvr_resolution,
215
+ seedvr_batch_size,
216
+ seedvr_fps_output
217
+ ],
218
+ outputs=[
219
+ seedvr_video_output,
220
+ seedvr_status_box
221
+ ]
222
+ )
223
+
224
+
225
+ if __name__ == "__main__":
226
+ # Inicia a aplicação Gradio
227
+ demo.queue().launch(
228
+ server_name="0.0.0.0",
229
+ debug=True,
230
+ show_error=True
231
+ )