caarleexx commited on
Commit
953686b
·
verified ·
1 Parent(s): 583f069

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -178
app.py CHANGED
@@ -1,194 +1,213 @@
1
-
2
- # app_refactored_with_postprod.py (FINAL VERSION with LTX Refinement)
3
 
4
  import gradio as gr
5
- import os
6
- import sys
7
- import traceback
8
- from pathlib import Path
9
- import torch
10
- import numpy as np
11
  from PIL import Image
12
-
13
- # --- Import dos Serviços de Backend ---
14
-
15
- # Serviço LTX para geração de vídeo base e refinamento de textura
16
- from api.ltx_server_refactored import video_generation_service
17
-
18
- # Serviço SeedVR para upscaling de alta qualidade
19
- from api.seedvr_server import SeedVRServer
20
-
21
- # Inicializa o servidor SeedVR uma vez, se disponível
22
- seedvr_inference_server = SeedVRServer() if SeedVRServer else None
23
-
24
- # --- ESTADO DA SESSÃO ---
25
- def create_initial_state():
26
- return {
27
- "low_res_video": None,
28
- "low_res_latents": None,
29
- "refined_video_ltx": None,
30
- "refined_latents_ltx": None,
31
- "used_seed": None
32
- }
33
-
34
- # --- FUNÇÕES WRAPPER PARA A UI ---
35
-
36
- def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
37
- """Executa a primeira etapa: geração de um vídeo base em baixa resolução."""
38
- print("UI: Chamando generate_low")
39
- if True:
40
-
41
- conditioning_items = []
42
- if start_img:
43
- num_frames_estimate = int(duration * 24)
44
- items_list = [[start_img, 0, 1.0]]
45
- conditioning_items = video_generation_service._prepare_condition_items(items_list, height, width, num_frames_estimate)
46
-
47
-
48
- used_seed = None if randomize_seed else seed
49
-
50
- video_path, tensor_path, final_seed = video_generation_service.generate_low_resolution(
51
- prompt=prompt, negative_prompt=neg_prompt,
52
- height=height, width=width, duration_secs=duration,
53
- guidance_scale=cfg, seed=used_seed,
54
- conditioning_items=conditioning_items
55
- )
56
-
57
- new_state = {
58
- "low_res_video": video_path,
59
- "low_res_latents": tensor_path,
60
- "refined_video_ltx": None,
61
- "refined_latents_ltx": None,
62
- "used_seed": final_seed
63
- }
64
-
65
- return video_path, new_state, gr.update(visible=True)
66
-
67
- def run_ltx_refinement(state, prompt, neg_prompt, cfg, progress=gr.Progress(track_tqdm=True)):
68
- """Executa o processo de refinamento e upscaling de textura com o pipeline LTX."""
69
- print("UI: Chamando run_ltx_refinement (generate_upscale_denoise)")
70
-
71
- if True:
72
- video_path, tensor_path = video_generation_service.generate_upscale_denoise(
73
- latents_path=state["low_res_latents"],
74
- prompt=prompt,
75
- negative_prompt=neg_prompt,
76
- guidance_scale=cfg,
77
- seed=state["used_seed"]
78
- )
79
-
80
- # Atualiza o estado com os novos artefatos refinados
81
- state["refined_video_ltx"] = video_path
82
- state["refined_latents_ltx"] = tensor_path
83
-
84
- return video_path, state
85
-
86
- def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
87
- """Executa o processo de upscaling com SeedVR."""
88
-
89
- video_path = state["low_res_video"]
90
- print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
91
-
92
- if True:
93
- def progress_wrapper(p, desc=""):
94
- progress(p, desc=desc)
95
- output_filepath = seedvr_inference_server.run_inference(
96
- file_path=video_path, seed=seed, resolution=resolution,
97
- batch_size=batch_size, fps=fps, progress=progress_wrapper
 
 
 
 
98
  )
99
- final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
100
- return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
101
-
 
 
 
 
102
  # --- DEFINIÇÃO DA INTERFACE GRADIO ---
103
- with gr.Blocks() as demo:
104
- gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
105
-
106
- app_state = gr.State(value=create_initial_state())
107
 
108
- # --- ETAPA 1: Geração Base ---
109
  with gr.Row():
110
- with gr.Column(scale=1):
111
- gr.Markdown("### Etapa 1: Configurações de Geração")
112
- prompt_input = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
113
- neg_prompt_input = gr.Textbox(visible=False, label="Negative Prompt", value="worst quality, blurry, low quality, jittery", lines=2)
114
- start_image = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload", "clipboard"])
115
-
116
- with gr.Accordion("Parâmetros Avançados", open=False):
117
- height_input = gr.Slider(label="Height", value=512, step=64, minimum=256, maximum=1024)
118
- width_input = gr.Slider(label="Width", value=512, step=64, minimum=256, maximum=1024)
119
- duration_input = gr.Slider(label="Duração (s)", value=8, step=0.5, minimum=1, maximum=16)
120
- cfg_input = gr.Slider(label="Guidance Scale (CFG)", value=5.0, step=1, minimum=1, maximum=10.0)
121
- seed_input = gr.Number(label="Seed", value=42, precision=0)
122
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
123
-
124
- generate_low_btn = gr.Button("1. Gerar Vídeo Base (Low-Res)", variant="primary")
125
-
126
- with gr.Column(scale=1):
127
- gr.Markdown("### Vídeo Base Gerado")
128
- low_res_video_output = gr.Video(label="O resultado da Etapa 1 aparecerá aqui", interactive=False)
129
-
130
- # --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
131
- with gr.Group(visible=False) as post_prod_group:
132
- gr.Markdown("<hr style='margin-top: 20px; margin-bottom: 20px;'>")
133
- gr.Markdown("## Etapa 2: Pós-Produção")
134
- gr.Markdown("Use o vídeo gerado acima como entrada para as ferramentas abaixo. **O prompt e a CFG da Etapa 1 serão reutilizados.**")
135
-
136
- with gr.Tabs():
137
- # --- ABA LTX REFINEMENT (AGORA FUNCIONAL) ---
138
- with gr.TabItem("🚀 Upscaler Textura (LTX)"):
139
  with gr.Row():
140
  with gr.Column(scale=1):
141
- gr.Markdown("### Parâmetros de Refinamento")
142
- gr.Markdown("Esta etapa reutiliza o prompt, o prompt negativo e a CFG da Etapa 1 para manter a consistência.")
143
- ltx_refine_btn = gr.Button("Aplicar Refinamento de Textura LTX", variant="primary")
144
  with gr.Column(scale=1):
145
- gr.Markdown("### Resultado do Refinamento")
146
- ltx_refined_video_output = gr.Video(label="Vídeo com Textura Refinada (LTX)", interactive=False)
147
-
148
- # --- ABA SEEDVR UPSCALER ---
149
- with gr.TabItem("✨ Upscaler SeedVR"):
150
- with gr.Row():
151
- with gr.Column(scale=1):
152
- gr.Markdown("### Parâmetros do SeedVR")
153
- seedvr_seed = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
154
- seedvr_resolution = gr.Slider(minimum=720, maximum=1440, value=1072, step=8, label="Resolução Vertical (Altura)")
155
- seedvr_batch_size = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
156
- seedvr_fps_output = gr.Number(label="FPS de Saída (0 = original)", value=0)
157
- run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
158
- if not seedvr_inference_server:
159
- gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
160
  with gr.Column(scale=1):
161
- gr.Markdown("### Resultado do Upscaling")
162
- seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
163
- seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
164
-
165
- # --- ABA MM-AUDIO ---
166
- with gr.TabItem("🔊 Áudio (MM-Audio)"):
167
- gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  # --- LÓGICA DE EVENTOS DA UI ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
- # Botão da Etapa 1
172
- generate_low_btn.click(
173
- fn=run_generate_low,
174
- inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
175
- outputs=[low_res_video_output, app_state, post_prod_group]
176
- )
177
-
178
- # Botão da Aba LTX Refinement
179
- ltx_refine_btn.click(
180
- fn=run_ltx_refinement,
181
- inputs=[app_state, prompt_input, neg_prompt_input, cfg_input],
182
- outputs=[ltx_refined_video_output, app_state]
183
- )
184
-
185
- # Botão da Aba SeedVR
186
- run_seedvr_button.click(
187
- fn=run_seedvr_upscaling,
188
- inputs=[app_state, seedvr_seed, seedvr_resolution, seedvr_batch_size, seedvr_fps_output],
189
- outputs=[seedvr_video_output, seedvr_status_box]
190
- )
191
 
192
  if __name__ == "__main__":
193
- demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True)
194
-
 
1
+ # app.py (Versão Corrigida)
 
2
 
3
  import gradio as gr
 
 
 
 
 
 
4
  from PIL import Image
5
+ import os
6
+ import imageio
7
+ from api.ltx_server import video_generation_service
8
+
9
+
10
+ from huggingface_hub import logging
11
+
12
+
13
+ logging.set_verbosity_error()
14
+ logging.set_verbosity_warning()
15
+ logging.set_verbosity_info()
16
+ logging.set_verbosity_debug()
17
+
18
+
19
+
20
+ # --- FUNÇÕES DE AJUDA PARA A UI ---
21
+ # ... (calculate_new_dimensions e handle_media_upload_for_dims permanecem as mesmas) ...
22
+ TARGET_FIXED_SIDE = 768
23
+ MIN_DIM_SLIDER = 256
24
+ MAX_IMAGE_SIZE = 1280
25
+
26
+ def calculate_new_dimensions(orig_w, orig_h):
27
+ if orig_w == 0 or orig_h == 0: return int(TARGET_FIXED_SIDE), int(TARGET_FIXED_SIDE)
28
+ if orig_w >= orig_h:
29
+ new_h, aspect_ratio = TARGET_FIXED_SIDE, orig_w / orig_h
30
+ new_w = round((new_h * aspect_ratio) / 32) * 32
31
+ new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
32
+ new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
33
+ else:
34
+ new_w, aspect_ratio = TARGET_FIXED_SIDE, orig_h / orig_w
35
+ new_h = round((new_w * aspect_ratio) / 32) * 32
36
+ new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
37
+ new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
38
+ return int(new_h), int(new_w)
39
+
40
+ def handle_media_upload_for_dims(filepath, current_h, current_w):
41
+ if not filepath or not os.path.exists(str(filepath)): return gr.update(value=current_h), gr.update(value=current_w)
42
+ try:
43
+ if str(filepath).lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
44
+ with Image.open(filepath) as img:
45
+ orig_w, orig_h = img.size
46
+ else: # Assumir que é um vídeo
47
+ with imageio.get_reader(filepath) as reader:
48
+ meta = reader.get_meta_data()
49
+ orig_w, orig_h = meta.get('size', (current_w, current_h))
50
+ new_h, new_w = calculate_new_dimensions(orig_w, orig_h)
51
+ return gr.update(value=new_h), gr.update(value=new_w)
52
+ except Exception as e:
53
+ print(f"Erro ao processar mídia para dimensões: {e}")
54
+ return gr.update(value=current_h), gr.update(value=current_w)
55
+
56
+ def update_frame_slider(duration):
57
+ """Atualiza o valor máximo do slider de frame do meio com base na duração."""
58
+ fps = 24.0
59
+ max_frames = int(duration * fps)
60
+ # Garante que o valor padrão não seja maior que o novo máximo
61
+ new_value = 48 if max_frames >= 48 else max_frames // 2
62
+ return gr.update(maximum=max_frames, value=new_value)
63
+
64
+
65
+ # --- FUNÇÃO WRAPPER PARA CHAMAR O SERVIÇO ---
66
+ def gradio_generate_wrapper(
67
+ prompt, negative_prompt, mode,
68
+ # Entradas de Keyframe
69
+ start_image,
70
+ middle_image, middle_frame, middle_weight,
71
+ end_image, end_weight,
72
+ # Outras entradas
73
+ input_video, height, width, duration,
74
+ frames_to_use, seed, randomize_seed,
75
+ guidance_scale, improve_texture,
76
+ progress=gr.Progress(track_tqdm=True)
77
+ ):
78
+ try:
79
+ def progress_handler(step, total_steps):
80
+ progress(step / total_steps, desc="Salvando vídeo...")
81
+
82
+ output_path, used_seed = video_generation_service.generate(
83
+ prompt=prompt, negative_prompt=negative_prompt, mode=mode,
84
+ start_image_filepath=start_image,
85
+ middle_image_filepath=middle_image,
86
+ middle_frame_number=middle_frame,
87
+ middle_image_weight=middle_weight,
88
+ end_image_filepath=end_image,
89
+ end_image_weight=end_weight,
90
+ input_video_filepath=input_video,
91
+ height=int(height), width=int(width), duration=float(duration),
92
+ frames_to_use=int(frames_to_use), seed=int(seed),
93
+ randomize_seed=bool(randomize_seed), guidance_scale=float(guidance_scale),
94
+ improve_texture=bool(improve_texture), progress_callback=progress_handler
95
  )
96
+ return output_path, used_seed
97
+ except ValueError as e:
98
+ raise gr.Error(str(e))
99
+ except Exception as e:
100
+ print(f"Erro inesperado na geração: {e}")
101
+ raise gr.Error("Ocorreu um erro inesperado. Verifique os logs.")
102
+
103
  # --- DEFINIÇÃO DA INTERFACE GRADIO ---
104
+ css = "#col-container { margin: 0 auto; max-width: 900px; }"
105
+ with gr.Blocks(css=css) as demo:
106
+ gr.Markdown("# LTX Video com Keyframes")
107
+ gr.Markdown("Guie a geração de vídeo usando imagens de início, meio e fim.")
108
 
 
109
  with gr.Row():
110
+ with gr.Column():
111
+ with gr.Tab("image-to-video (Keyframes)") as image_tab:
112
+ i2v_prompt = gr.Textbox(label="Prompt", value="Uma bela transição entre as imagens", lines=2)
113
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  with gr.Row():
115
  with gr.Column(scale=1):
116
+ gr.Markdown("#### Início (Obrigatório)")
117
+ start_image_i2v = gr.Image(label="Imagem de Início", type="filepath", sources=["upload", "clipboard"])
 
118
  with gr.Column(scale=1):
119
+ gr.Markdown("#### Meio (Opcional)")
120
+ middle_image_i2v = gr.Image(label="Imagem do Meio", type="filepath", sources=["upload", "clipboard"])
121
+ middle_frame_i2v = gr.Slider(label="Frame Alvo", minimum=0, maximum=200, step=1, value=48)
122
+ middle_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
 
 
 
 
 
 
 
 
 
 
 
123
  with gr.Column(scale=1):
124
+ gr.Markdown("#### Fim (Opcional)")
125
+ end_image_i2v = gr.Image(label="Imagem de Fim", type="filepath", sources=["upload", "clipboard"])
126
+ end_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
127
+
128
+ i2v_button = gr.Button("Generate Image-to-Video", variant="primary")
129
+
130
+ with gr.Tab("text-to-video") as text_tab:
131
+ t2v_prompt = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
132
+ t2v_button = gr.Button("Generate Text-to-Video", variant="primary")
133
+
134
+ with gr.Tab("video-to-video") as video_tab:
135
+ video_v2v = gr.Video(label="Input Video", sources=["upload", "webcam"])
136
+ frames_to_use = gr.Slider(label="Frames to use from input video", minimum=9, maximum=257, value=9, step=8, info="Must be N*8+1.")
137
+ v2v_prompt = gr.Textbox(label="Prompt", value="Change the style to cinematic anime", lines=3)
138
+ v2v_button = gr.Button("Generate Video-to-Video", variant="primary")
139
+
140
+ duration_input = gr.Slider(label="Video Duration (seconds)", minimum=1, maximum=30, value=8, step=0.5)
141
+ improve_texture = gr.Checkbox(label="Improve Texture (multi-scale)", value=True, visible=True)
142
+
143
+ with gr.Column():
144
+ output_video = gr.Video(label="Generated Video", interactive=False)
145
+
146
+ with gr.Accordion("Advanced settings", open=False):
147
+ mode = gr.Dropdown(["text-to-video", "image-to-video", "video-to-video"], label="task", value="image-to-video", visible=False)
148
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value="worst quality, blurry, jittery", lines=2)
149
+ with gr.Row():
150
+ seed_input = gr.Number(label="Seed", value=42, precision=0)
151
+ randomize_seed_input = gr.Checkbox(label="Randomize Seed", value=True)
152
+ guidance_scale_input = gr.Slider(label="Guidance Scale (CFG)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
153
+ with gr.Row():
154
+ height_input = gr.Slider(label="Height", value=512, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
155
+ width_input = gr.Slider(label="Width", value=704, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
156
 
157
  # --- LÓGICA DE EVENTOS DA UI ---
158
+
159
+ start_image_i2v.upload(fn=handle_media_upload_for_dims, inputs=[start_image_i2v, height_input, width_input], outputs=[height_input, width_input])
160
+ video_v2v.upload(fn=handle_media_upload_for_dims, inputs=[video_v2v, height_input, width_input], outputs=[height_input, width_input])
161
+ duration_input.change(fn=update_frame_slider, inputs=duration_input, outputs=middle_frame_i2v)
162
+
163
+ image_tab.select(fn=lambda: "image-to-video", outputs=[mode])
164
+ text_tab.select(fn=lambda: "text-to-video", outputs=[mode])
165
+ video_tab.select(fn=lambda: "video-to-video", outputs=[mode])
166
+
167
+ # --- <INÍCIO DA CORREÇÃO> ---
168
+ # Reescrevendo as listas de inputs de forma explícita para evitar erros.
169
+
170
+ # Placeholders para os botões que não usam certos inputs
171
+ none_image = gr.Textbox(visible=False, value=None)
172
+ none_video = gr.Textbox(visible=False, value=None)
173
+
174
+ # Parâmetros comuns a todos
175
+ shared_params = [
176
+ height_input, width_input, duration_input, frames_to_use,
177
+ seed_input, randomize_seed_input, guidance_scale_input, improve_texture
178
+ ]
179
+
180
+ i2v_inputs = [
181
+ i2v_prompt, negative_prompt_input, mode,
182
+ start_image_i2v, middle_image_i2v, middle_frame_i2v, middle_weight_i2v,
183
+ end_image_i2v, end_weight_i2v,
184
+ none_video, # Placeholder para input_video
185
+ *shared_params
186
+ ]
187
+
188
+ t2v_inputs = [
189
+ t2v_prompt, negative_prompt_input, mode,
190
+ none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), # Placeholders para keyframes
191
+ none_image, gr.Slider(value=0, visible=False),
192
+ none_video, # Placeholder para input_video
193
+ *shared_params
194
+ ]
195
+
196
+ v2v_inputs = [
197
+ v2v_prompt, negative_prompt_input, mode,
198
+ none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), # Placeholders para keyframes
199
+ none_image, gr.Slider(value=0, visible=False),
200
+ video_v2v, # Input de vídeo real
201
+ *shared_params
202
+ ]
203
+
204
+ common_outputs = [output_video, seed_input]
205
+
206
+ i2v_button.click(fn=gradio_generate_wrapper, inputs=i2v_inputs, outputs=common_outputs, api_name="image_to_video_keyframes")
207
+ t2v_button.click(fn=gradio_generate_wrapper, inputs=t2v_inputs, outputs=common_outputs, api_name="text_to_video")
208
+ v2v_button.click(fn=gradio_generate_wrapper, inputs=v2v_inputs, outputs=common_outputs, api_name="video_to_video")
209
+ # --- <FIM DA CORREÇÃO> ---
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  if __name__ == "__main__":
213
+ demo.queue().launch(debug=True, share=False)