Aduc-sdr-2_5s / app_ltx.py
euIaxs22's picture
Update app_ltx.py
83f4660 verified
raw
history blame
3.78 kB
import os
import gradio as gr
from pathlib import Path
# Importa o singleton do nosso novo servidor LTX
try:
from services.ltx_server import ltx_server_singleton as server
except Exception as e:
print(f"ERRO FATAL: Não foi possível importar o LTXServer. A aplicação não pode iniciar.")
print(f"Detalhe do erro: {e}")
raise
# --- Função de Callback da UI ---
def generate_video_from_image(
prompt: str,
image_input: str,
height: int,
width: int,
num_frames: int,
seed: int,
progress=gr.Progress(track_tqdm=True) # <<< ADICIONADO PROGRESSO AQUI
):
"""Callback para a UI que chama o backend LTXServer."""
progress(0.1, desc="Validando entradas...")
if not image_input or not Path(image_input).exists():
gr.Warning("Por favor, faça o upload de uma imagem de entrada.")
return None
if not prompt or not prompt.strip():
gr.Warning("Por favor, insira um prompt.")
return None
try:
progress(0.5, desc="Enviando tarefa para o backend LTX (Q8). A inferência pode demorar um pouco...")
video_path = server.run_inference(
prompt=prompt,
image_path=image_input,
height=int(height),
width=int(width),
num_frames=int(num_frames),
seed=int(seed)
)
progress(1.0, desc="Inferência concluída!")
return video_path
except Exception as e:
print(f"[UI LTX ERROR] A inferência falhou: {e}")
gr.Error(f"Erro na Geração: {e}")
return None
# --- Definição da Interface Gráfica com Gradio ---
with gr.Blocks(title="LTX-Video (Q8 Img2Vid)") as demo:
gr.HTML(
"""
<div style='text-align:center; margin-bottom: 20px;'>
<h1>LTX-Video Q8 - Imagem para Vídeo</h1>
<p>Interface de teste isolada para o modelo LTX-Video quantizado.</p>
</div>
"""
)
with gr.Row():
with gr.Column(scale=1):
image_in = gr.Image(type="filepath", label="Imagem de Entrada")
prompt_in = gr.Textbox(label="Prompt", lines=3, placeholder="Ex: a cinematic shot of a woman smiling")
with gr.Accordion("Parâmetros de Geração", open=True):
with gr.Row():
height_in = gr.Slider(label="Altura (Height)", minimum=256, maximum=1024, step=64, value=512)
width_in = gr.Slider(label="Largura (Width)", minimum=256, maximum=1024, step=64, value=512)
with gr.Row():
frames_in = gr.Slider(label="Número de Frames", minimum=16, maximum=128, step=8, value=32)
seed_in = gr.Number(label="Seed", value=42, precision=0)
run_button = gr.Button("Gerar Vídeo", variant="primary")
with gr.Column(scale=1):
video_out = gr.Video(label="Vídeo Gerado")
run_button.click(
fn=generate_video_from_image,
inputs=[prompt_in, image_in, height_in, width_in, frames_in, seed_in],
outputs=[video_out],
)
gr.Markdown("---")
gr.Examples(
examples=[["A beautiful woman with a gentle smile, cinematic lighting", "frame_1.png", 512, 512, 32, 123]],
inputs=[prompt_in, image_in, height_in, width_in, frames_in, seed_in],
)
if __name__ == "__main__":
if not os.path.exists("frame_1.png"):
try:
from PIL import Image
img = Image.new('RGB', (512, 512), color = 'grey')
img.save('frame_1.png')
except:
pass
demo.launch(
server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
server_port=int(os.getenv("GRADIO_SERVER_PORT", "7861")),
show_error=True,
)