Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app_refactored_with_postprod.py
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
import os
|
|
@@ -13,7 +13,6 @@ 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 |
# Serviço SeedVR para upscaling de alta qualidade
|
|
@@ -21,47 +20,34 @@ try:
|
|
| 21 |
from api.seedvr_server import SeedVRServer
|
| 22 |
except ImportError:
|
| 23 |
print("AVISO: Não foi possível importar SeedVRServer. A aba de upscaling SeedVR será desativada.")
|
| 24 |
-
SeedVRServer = None
|
| 25 |
|
| 26 |
# Inicializa o servidor SeedVR uma vez, se disponível
|
| 27 |
-
if SeedVRServer
|
| 28 |
-
print("Inicializando o servidor de inferência SeedVR...")
|
| 29 |
-
seedvr_inference_server = SeedVRServer()
|
| 30 |
-
else:
|
| 31 |
-
seedvr_inference_server = None
|
| 32 |
|
| 33 |
# --- ESTADO DA SESSÃO ---
|
| 34 |
-
# Mantém os caminhos dos arquivos entre os cliques dos botões
|
| 35 |
def create_initial_state():
|
| 36 |
return {
|
| 37 |
"low_res_video": None,
|
| 38 |
"low_res_latents": None,
|
| 39 |
-
"
|
| 40 |
-
"
|
| 41 |
"used_seed": None
|
| 42 |
}
|
| 43 |
|
| 44 |
# --- FUNÇÕES WRAPPER PARA A UI ---
|
| 45 |
|
| 46 |
def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
|
| 47 |
-
"""
|
| 48 |
-
Executa a primeira etapa: geração de um vídeo base em baixa resolução.
|
| 49 |
-
"""
|
| 50 |
print("UI: Chamando generate_low")
|
| 51 |
-
|
| 52 |
try:
|
| 53 |
-
# 1. Preparar conditioning_items (se uma imagem de início for fornecida)
|
| 54 |
conditioning_items = []
|
| 55 |
if start_img:
|
| 56 |
-
# A função `prepare_condition_items` precisa de uma estimativa do número de frames
|
| 57 |
num_frames_estimate = int(duration * 24)
|
| 58 |
-
items_list = [[start_img, 0, 1.0]]
|
| 59 |
conditioning_items = video_generation_service.prepare_condition_items(items_list, height, width, num_frames_estimate)
|
| 60 |
|
| 61 |
-
# Determina a seed a ser usada
|
| 62 |
used_seed = None if randomize_seed else seed
|
| 63 |
-
|
| 64 |
-
# 2. Chamar a função de geração de baixa resolução do backend
|
| 65 |
video_path, tensor_path, final_seed = video_generation_service.generate_low(
|
| 66 |
prompt=prompt, negative_prompt=neg_prompt,
|
| 67 |
height=height, width=width, duration=duration,
|
|
@@ -69,74 +55,73 @@ def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg
|
|
| 69 |
conditioning_items=conditioning_items
|
| 70 |
)
|
| 71 |
|
| 72 |
-
# 3. Atualizar o estado da aplicação com os caminhos dos arquivos resultantes
|
| 73 |
new_state = {
|
| 74 |
"low_res_video": video_path,
|
| 75 |
"low_res_latents": tensor_path,
|
| 76 |
-
"
|
| 77 |
-
"
|
| 78 |
"used_seed": final_seed
|
| 79 |
}
|
| 80 |
|
| 81 |
-
# 4. Retorna os resultados para a UI
|
| 82 |
-
# - O caminho do vídeo para o componente de vídeo
|
| 83 |
-
# - O novo estado para o componente gr.State
|
| 84 |
-
# - Um update para tornar o grupo de pós-produção visível
|
| 85 |
return video_path, new_state, gr.update(visible=True)
|
| 86 |
-
|
| 87 |
except Exception as e:
|
| 88 |
error_message = f"❌ Ocorreu um erro na Geração Base:\n{e}"
|
| 89 |
print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
|
| 90 |
raise gr.Error(error_message)
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
|
| 94 |
-
"""
|
| 95 |
-
Função de callback que executa o processo de upscaling com SeedVR.
|
| 96 |
-
"""
|
| 97 |
if not state or not state.get("low_res_video"):
|
| 98 |
raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
|
| 99 |
if not seedvr_inference_server:
|
| 100 |
-
raise gr.Error("Erro: O servidor SeedVR não está disponível.
|
| 101 |
|
| 102 |
video_path = state["low_res_video"]
|
| 103 |
-
|
| 104 |
-
progress(0, desc="Iniciando SeedVR Upscaling...")
|
| 105 |
print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
|
| 106 |
|
| 107 |
try:
|
| 108 |
-
# Wrapper para a barra de progresso do Gradio
|
| 109 |
def progress_wrapper(p, desc=""):
|
| 110 |
progress(p, desc=desc)
|
| 111 |
-
print(f"⌛ Progresso SeedVR: {p*100:.1f}% - {desc}")
|
| 112 |
-
|
| 113 |
-
# Chama o método de inferência do servidor SeedVR
|
| 114 |
output_filepath = seedvr_inference_server.run_inference(
|
| 115 |
-
file_path=video_path,
|
| 116 |
-
|
| 117 |
-
resolution=resolution,
|
| 118 |
-
batch_size=batch_size,
|
| 119 |
-
fps=fps,
|
| 120 |
-
progress=progress_wrapper
|
| 121 |
)
|
| 122 |
-
|
| 123 |
final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
|
| 124 |
-
print(final_message)
|
| 125 |
-
# Retorna o vídeo e a mensagem de sucesso para a UI
|
| 126 |
return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
|
| 127 |
-
|
| 128 |
except Exception as e:
|
| 129 |
error_message = f"❌ Ocorreu um erro grave durante o upscaling com SeedVR:\n{e}"
|
| 130 |
print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
|
| 131 |
-
# Retorna None para o vídeo e a mensagem de erro para o status box
|
| 132 |
return None, gr.update(value=error_message, interactive=False)
|
| 133 |
|
| 134 |
-
|
| 135 |
# --- DEFINIÇÃO DA INTERFACE GRADIO ---
|
| 136 |
-
with gr.Blocks(theme=gr.themes.
|
| 137 |
-
gr.Markdown("
|
| 138 |
|
| 139 |
-
# Componente invisível para armazenar o estado da aplicação (caminhos de arquivos, etc.)
|
| 140 |
app_state = gr.State(value=create_initial_state())
|
| 141 |
|
| 142 |
# --- ETAPA 1: Geração Base ---
|
|
@@ -163,17 +148,22 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Aduc-Srd Studio"
|
|
| 163 |
|
| 164 |
# --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
|
| 165 |
with gr.Group(visible=False) as post_prod_group:
|
| 166 |
-
gr.Markdown("<hr style='margin-top: 20px; margin-bottom: 20px;'>")
|
| 167 |
gr.Markdown("## Etapa 2: Pós-Produção")
|
| 168 |
-
gr.Markdown("Use o vídeo gerado acima como entrada para as ferramentas abaixo.")
|
| 169 |
|
| 170 |
with gr.Tabs():
|
|
|
|
| 171 |
with gr.TabItem("🚀 Upscaler Textura (LTX)"):
|
| 172 |
-
gr.
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
|
|
|
| 177 |
with gr.TabItem("✨ Upscaler SeedVR"):
|
| 178 |
with gr.Row():
|
| 179 |
with gr.Column(scale=1):
|
|
@@ -185,47 +175,37 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Aduc-Srd Studio"
|
|
| 185 |
run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
|
| 186 |
if not seedvr_inference_server:
|
| 187 |
gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
|
| 188 |
-
|
| 189 |
with gr.Column(scale=1):
|
| 190 |
gr.Markdown("### Resultado do Upscaling")
|
| 191 |
seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
|
| 192 |
seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
|
| 193 |
|
|
|
|
| 194 |
with gr.TabItem("🔊 Áudio (MM-Audio)"):
|
| 195 |
gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
|
| 196 |
-
# Componentes para a geração de áudio viriam aqui
|
| 197 |
|
| 198 |
# --- LÓGICA DE EVENTOS DA UI ---
|
| 199 |
|
| 200 |
-
#
|
| 201 |
generate_low_btn.click(
|
| 202 |
fn=run_generate_low,
|
| 203 |
inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
|
| 204 |
outputs=[low_res_video_output, app_state, post_prod_group]
|
| 205 |
)
|
| 206 |
|
| 207 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
run_seedvr_button.click(
|
| 209 |
fn=run_seedvr_upscaling,
|
| 210 |
-
inputs=[
|
| 211 |
-
|
| 212 |
-
seedvr_seed,
|
| 213 |
-
seedvr_resolution,
|
| 214 |
-
seedvr_batch_size,
|
| 215 |
-
seedvr_fps_output
|
| 216 |
-
],
|
| 217 |
-
outputs=[
|
| 218 |
-
seedvr_video_output,
|
| 219 |
-
seedvr_status_box
|
| 220 |
-
]
|
| 221 |
)
|
| 222 |
|
| 223 |
-
|
| 224 |
if __name__ == "__main__":
|
| 225 |
-
|
| 226 |
-
demo.queue().launch(
|
| 227 |
-
server_name="0.0.0.0",
|
| 228 |
-
server_port=7860,
|
| 229 |
-
debug=True,
|
| 230 |
-
show_error=True
|
| 231 |
-
)
|
|
|
|
| 1 |
+
# app_refactored_with_postprod.py (FINAL VERSION with LTX Refinement)
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
import os
|
|
|
|
| 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 |
sys.exit(1)
|
| 17 |
|
| 18 |
# Serviço SeedVR para upscaling de alta qualidade
|
|
|
|
| 20 |
from api.seedvr_server import SeedVRServer
|
| 21 |
except ImportError:
|
| 22 |
print("AVISO: Não foi possível importar SeedVRServer. A aba de upscaling SeedVR será desativada.")
|
| 23 |
+
SeedVRServer = None
|
| 24 |
|
| 25 |
# Inicializa o servidor SeedVR uma vez, se disponível
|
| 26 |
+
seedvr_inference_server = SeedVRServer() if SeedVRServer else None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# --- ESTADO DA SESSÃO ---
|
|
|
|
| 29 |
def create_initial_state():
|
| 30 |
return {
|
| 31 |
"low_res_video": None,
|
| 32 |
"low_res_latents": None,
|
| 33 |
+
"refined_video_ltx": None,
|
| 34 |
+
"refined_latents_ltx": None,
|
| 35 |
"used_seed": None
|
| 36 |
}
|
| 37 |
|
| 38 |
# --- FUNÇÕES WRAPPER PARA A UI ---
|
| 39 |
|
| 40 |
def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
|
| 41 |
+
"""Executa a primeira etapa: geração de um vídeo base em baixa resolução."""
|
|
|
|
|
|
|
| 42 |
print("UI: Chamando generate_low")
|
|
|
|
| 43 |
try:
|
|
|
|
| 44 |
conditioning_items = []
|
| 45 |
if start_img:
|
|
|
|
| 46 |
num_frames_estimate = int(duration * 24)
|
| 47 |
+
items_list = [[start_img, 0, 1.0]]
|
| 48 |
conditioning_items = video_generation_service.prepare_condition_items(items_list, height, width, num_frames_estimate)
|
| 49 |
|
|
|
|
| 50 |
used_seed = None if randomize_seed else seed
|
|
|
|
|
|
|
| 51 |
video_path, tensor_path, final_seed = video_generation_service.generate_low(
|
| 52 |
prompt=prompt, negative_prompt=neg_prompt,
|
| 53 |
height=height, width=width, duration=duration,
|
|
|
|
| 55 |
conditioning_items=conditioning_items
|
| 56 |
)
|
| 57 |
|
|
|
|
| 58 |
new_state = {
|
| 59 |
"low_res_video": video_path,
|
| 60 |
"low_res_latents": tensor_path,
|
| 61 |
+
"refined_video_ltx": None,
|
| 62 |
+
"refined_latents_ltx": None,
|
| 63 |
"used_seed": final_seed
|
| 64 |
}
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return video_path, new_state, gr.update(visible=True)
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
error_message = f"❌ Ocorreu um erro na Geração Base:\n{e}"
|
| 69 |
print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
|
| 70 |
raise gr.Error(error_message)
|
| 71 |
|
| 72 |
+
def run_ltx_refinement(state, prompt, neg_prompt, cfg, progress=gr.Progress(track_tqdm=True)):
|
| 73 |
+
"""Executa o processo de refinamento e upscaling de textura com o pipeline LTX."""
|
| 74 |
+
print("UI: Chamando run_ltx_refinement (generate_upscale_denoise)")
|
| 75 |
+
if not state or not state.get("low_res_latents"):
|
| 76 |
+
raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
video_path, tensor_path = video_generation_service.generate_upscale_denoise(
|
| 80 |
+
latents_path=state["low_res_latents"],
|
| 81 |
+
prompt=prompt,
|
| 82 |
+
negative_prompt=neg_prompt,
|
| 83 |
+
guidance_scale=cfg,
|
| 84 |
+
seed=state["used_seed"]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Atualiza o estado com os novos artefatos refinados
|
| 88 |
+
state["refined_video_ltx"] = video_path
|
| 89 |
+
state["refined_latents_ltx"] = tensor_path
|
| 90 |
+
|
| 91 |
+
return video_path, state
|
| 92 |
+
except Exception as e:
|
| 93 |
+
error_message = f"❌ Ocorreu um erro durante o Refinamento LTX:\n{e}"
|
| 94 |
+
print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
|
| 95 |
+
raise gr.Error(error_message)
|
| 96 |
|
| 97 |
def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
|
| 98 |
+
"""Executa o processo de upscaling com SeedVR."""
|
|
|
|
|
|
|
| 99 |
if not state or not state.get("low_res_video"):
|
| 100 |
raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
|
| 101 |
if not seedvr_inference_server:
|
| 102 |
+
raise gr.Error("Erro: O servidor SeedVR não está disponível.")
|
| 103 |
|
| 104 |
video_path = state["low_res_video"]
|
|
|
|
|
|
|
| 105 |
print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
|
| 106 |
|
| 107 |
try:
|
|
|
|
| 108 |
def progress_wrapper(p, desc=""):
|
| 109 |
progress(p, desc=desc)
|
|
|
|
|
|
|
|
|
|
| 110 |
output_filepath = seedvr_inference_server.run_inference(
|
| 111 |
+
file_path=video_path, seed=seed, resolution=resolution,
|
| 112 |
+
batch_size=batch_size, fps=fps, progress=progress_wrapper
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
)
|
|
|
|
| 114 |
final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
|
|
|
|
|
|
|
| 115 |
return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
error_message = f"❌ Ocorreu um erro grave durante o upscaling com SeedVR:\n{e}"
|
| 118 |
print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
|
|
|
|
| 119 |
return None, gr.update(value=error_message, interactive=False)
|
| 120 |
|
|
|
|
| 121 |
# --- DEFINIÇÃO DA INTERFACE GRADIO ---
|
| 122 |
+
with gr.Blocks(css="#col-container { margin: 0 auto; max-width: 900px; }", theme=gr.themes.Monochrome()) as demo:
|
| 123 |
+
gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
|
| 124 |
|
|
|
|
| 125 |
app_state = gr.State(value=create_initial_state())
|
| 126 |
|
| 127 |
# --- ETAPA 1: Geração Base ---
|
|
|
|
| 148 |
|
| 149 |
# --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
|
| 150 |
with gr.Group(visible=False) as post_prod_group:
|
|
|
|
| 151 |
gr.Markdown("## Etapa 2: Pós-Produção")
|
| 152 |
+
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.**")
|
| 153 |
|
| 154 |
with gr.Tabs():
|
| 155 |
+
# --- ABA LTX REFINEMENT (AGORA FUNCIONAL) ---
|
| 156 |
with gr.TabItem("🚀 Upscaler Textura (LTX)"):
|
| 157 |
+
with gr.Row():
|
| 158 |
+
with gr.Column(scale=1):
|
| 159 |
+
gr.Markdown("### Parâmetros de Refinamento")
|
| 160 |
+
gr.Markdown("Esta etapa reutiliza o prompt, o prompt negativo e a CFG da Etapa 1 para manter a consistência.")
|
| 161 |
+
ltx_refine_btn = gr.Button("Aplicar Refinamento de Textura LTX", variant="primary")
|
| 162 |
+
with gr.Column(scale=1):
|
| 163 |
+
gr.Markdown("### Resultado do Refinamento")
|
| 164 |
+
ltx_refined_video_output = gr.Video(label="Vídeo com Textura Refinada (LTX)", interactive=False)
|
| 165 |
|
| 166 |
+
# --- ABA SEEDVR UPSCALER ---
|
| 167 |
with gr.TabItem("✨ Upscaler SeedVR"):
|
| 168 |
with gr.Row():
|
| 169 |
with gr.Column(scale=1):
|
|
|
|
| 175 |
run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
|
| 176 |
if not seedvr_inference_server:
|
| 177 |
gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
|
|
|
|
| 178 |
with gr.Column(scale=1):
|
| 179 |
gr.Markdown("### Resultado do Upscaling")
|
| 180 |
seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
|
| 181 |
seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
|
| 182 |
|
| 183 |
+
# --- ABA MM-AUDIO ---
|
| 184 |
with gr.TabItem("🔊 Áudio (MM-Audio)"):
|
| 185 |
gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
|
|
|
|
| 186 |
|
| 187 |
# --- LÓGICA DE EVENTOS DA UI ---
|
| 188 |
|
| 189 |
+
# Botão da Etapa 1
|
| 190 |
generate_low_btn.click(
|
| 191 |
fn=run_generate_low,
|
| 192 |
inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
|
| 193 |
outputs=[low_res_video_output, app_state, post_prod_group]
|
| 194 |
)
|
| 195 |
|
| 196 |
+
# Botão da Aba LTX Refinement
|
| 197 |
+
ltx_refine_btn.click(
|
| 198 |
+
fn=run_ltx_refinement,
|
| 199 |
+
inputs=[app_state, prompt_input, neg_prompt_input, cfg_input],
|
| 200 |
+
outputs=[ltx_refined_video_output, app_state]
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Botão da Aba SeedVR
|
| 204 |
run_seedvr_button.click(
|
| 205 |
fn=run_seedvr_upscaling,
|
| 206 |
+
inputs=[app_state, seedvr_seed, seedvr_resolution, seedvr_batch_size, seedvr_fps_output],
|
| 207 |
+
outputs=[seedvr_video_output, seedvr_status_box]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
)
|
| 209 |
|
|
|
|
| 210 |
if __name__ == "__main__":
|
| 211 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|