euIaxs22 commited on
Commit
87cc7c1
·
verified ·
1 Parent(s): 111d2af

Create app_ltx.py

Browse files
Files changed (1) hide show
  1. app_ltx.py +113 -0
app_ltx.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from pathlib import Path
4
+
5
+ # Importa o singleton do nosso novo servidor LTX
6
+ try:
7
+ from services.ltx_server import ltx_server_singleton as server
8
+ except Exception as e:
9
+ print(f"ERRO FATAL: Não foi possível importar o LTXServer. A aplicação não pode iniciar.")
10
+ print(f"Detalhe do erro: {e}")
11
+ raise
12
+
13
+ # --- Função de Callback da UI ---
14
+ def generate_video_from_image(
15
+ prompt: str,
16
+ image_input: str, # O Gradio passa o caminho do arquivo temporário
17
+ height: int,
18
+ width: int,
19
+ num_frames: int,
20
+ seed: int,
21
+ progress=gr.Progress(track_tqdm=True)
22
+ ):
23
+ """Callback para a UI que chama o backend LTXServer."""
24
+ progress(0.1, desc="Validando entradas...")
25
+ if not image_input or not Path(image_input).exists():
26
+ gr.Warning("Por favor, faça o upload de uma imagem de entrada.")
27
+ return None
28
+ if not prompt or not prompt.strip():
29
+ gr.Warning("Por favor, insira um prompt.")
30
+ return None
31
+
32
+ try:
33
+ progress(0.5, desc="Enviando tarefa para o backend LTX (Q8). A inferência pode demorar um pouco...")
34
+
35
+ # Chama o método do servidor, passando todos os parâmetros
36
+ video_path = server.run_inference(
37
+ prompt=prompt,
38
+ image_path=image_input,
39
+ height=int(height),
40
+ width=int(width),
41
+ num_frames=int(num_frames),
42
+ seed=int(seed)
43
+ )
44
+
45
+ progress(0.9, desc="Inferência concluída!")
46
+ return video_path
47
+
48
+ except Exception as e:
49
+ print(f"[UI LTX ERROR] A inferência falhou: {e}")
50
+ gr.Error(f"Erro na Geração: {e}")
51
+ return None
52
+
53
+ # --- Definição da Interface Gráfica com Gradio ---
54
+ with gr.Blocks(title="LTX-Video (Q8 Img2Vid)") as demo:
55
+ gr.HTML(
56
+ """
57
+ <div style='text-align:center; margin-bottom: 20px;'>
58
+ <h1>LTX-Video Q8 - Imagem para Vídeo</h1>
59
+ <p>Interface de teste isolada para o modelo LTX-Video quantizado.</p>
60
+ </div>
61
+ """
62
+ )
63
+
64
+ with gr.Row():
65
+ with gr.Column(scale=1):
66
+ image_in = gr.Image(type="filepath", label="Imagem de Entrada")
67
+ prompt_in = gr.Textbox(label="Prompt", lines=3, placeholder="Ex: a cinematic shot of a woman smiling")
68
+
69
+ with gr.Accordion("Parâmetros de Geração", open=True):
70
+ with gr.Row():
71
+ height_in = gr.Slider(label="Altura (Height)", minimum=256, maximum=1024, step=64, value=512)
72
+ width_in = gr.Slider(label="Largura (Width)", minimum=256, maximum=1024, step=64, value=512)
73
+ with gr.Row():
74
+ frames_in = gr.Slider(label="Número de Frames", minimum=16, maximum=128, step=8, value=32)
75
+ seed_in = gr.Number(label="Seed", value=42, precision=0)
76
+
77
+ run_button = gr.Button("Gerar Vídeo", variant="primary")
78
+
79
+ with gr.Column(scale=1):
80
+ video_out = gr.Video(label="Vídeo Gerado")
81
+
82
+ # Ação do botão
83
+ run_button.click(
84
+ fn=generate_video_from_image,
85
+ inputs=[prompt_in, image_in, height_in, width_in, frames_in, seed_in],
86
+ outputs=[video_out],
87
+ )
88
+
89
+ gr.Markdown("---")
90
+ gr.Markdown("### Exemplos")
91
+ gr.Examples(
92
+ examples=[
93
+ ["A beautiful woman with a gentle smile, cinematic lighting", "example_image.jpg", 512, 512, 32, 123],
94
+ ],
95
+ inputs=[prompt_in, image_in, height_in, width_in, frames_in, seed_in],
96
+ )
97
+
98
+ # --- Ponto de Entrada da Aplicação ---
99
+ if __name__ == "__main__":
100
+ # Cria um arquivo de exemplo se não existir
101
+ if not os.path.exists("frame_1.png"):
102
+ try:
103
+ from PIL import Image
104
+ img = Image.new('RGB', (512, 512), color = 'red')
105
+ img.save('example_image.jpg')
106
+ except:
107
+ pass
108
+
109
+ demo.launch(
110
+ server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
111
+ server_port=int(os.getenv("GRADIO_SERVER_PORT", "7861")), # Usa uma porta diferente para não conflitar
112
+ show_error=True,
113
+ )