eeuuia commited on
Commit
53c67fb
·
verified ·
1 Parent(s): 839c8a5

Delete app_ltx.py

Browse files
Files changed (1) hide show
  1. app_ltx.py +0 -206
app_ltx.py DELETED
@@ -1,206 +0,0 @@
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
- from huggingface_hub import logging
9
-
10
- logging.set_verbosity_error()
11
- logging.set_verbosity_warning()
12
- logging.set_verbosity_info()
13
- logging.set_verbosity_debug()
14
-
15
- # --- FUNÇÕES DE AJUDA PARA A UI ---
16
- # ... (calculate_new_dimensions e handle_media_upload_for_dims permanecem as mesmas) ...
17
- TARGET_FIXED_SIDE = 768
18
- MIN_DIM_SLIDER = 256
19
- MAX_IMAGE_SIZE = 1280
20
-
21
- def calculate_new_dimensions(orig_w, orig_h):
22
- if orig_w == 0 or orig_h == 0: return int(TARGET_FIXED_SIDE), int(TARGET_FIXED_SIDE)
23
- if orig_w >= orig_h:
24
- new_h, aspect_ratio = TARGET_FIXED_SIDE, orig_w / orig_h
25
- new_w = round((new_h * aspect_ratio) / 32) * 32
26
- new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
27
- new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
28
- else:
29
- new_w, aspect_ratio = TARGET_FIXED_SIDE, orig_h / orig_w
30
- new_h = round((new_w * aspect_ratio) / 32) * 32
31
- new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
32
- new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
33
- return int(new_h), int(new_w)
34
-
35
- def handle_media_upload_for_dims(filepath, current_h, current_w):
36
- if not filepath or not os.path.exists(str(filepath)): return gr.update(value=current_h), gr.update(value=current_w)
37
- try:
38
- if str(filepath).lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
39
- with Image.open(filepath) as img:
40
- orig_w, orig_h = img.size
41
- else: # Assumir que é um vídeo
42
- with imageio.get_reader(filepath) as reader:
43
- meta = reader.get_meta_data()
44
- orig_w, orig_h = meta.get('size', (current_w, current_h))
45
- new_h, new_w = calculate_new_dimensions(orig_w, orig_h)
46
- return gr.update(value=new_h), gr.update(value=new_w)
47
- except Exception as e:
48
- print(f"Erro ao processar mídia para dimensões: {e}")
49
- return gr.update(value=current_h), gr.update(value=current_w)
50
-
51
- def update_frame_slider(duration):
52
- """Atualiza o valor máximo do slider de frame do meio com base na duração."""
53
- fps = 24.0
54
- max_frames = int(duration * fps)
55
- # Garante que o valor padrão não seja maior que o novo máximo
56
- new_value = 48 if max_frames >= 48 else max_frames // 2
57
- return gr.update(maximum=max_frames, value=new_value)
58
-
59
- # --- FUNÇÃO WRAPPER PARA CHAMAR O SERVIÇO ---
60
- def gradio_generate_wrapper(
61
- prompt, negative_prompt, mode,
62
- # Entradas de Keyframe
63
- start_image,
64
- middle_image, middle_frame, middle_weight,
65
- end_image, end_weight,
66
- # Outras entradas
67
- input_video, height, width, duration,
68
- frames_to_use, seed, randomize_seed,
69
- guidance_scale, improve_texture,
70
- progress=gr.Progress(track_tqdm=True)
71
- ):
72
- try:
73
- def progress_handler(step, total_steps):
74
- progress(step / total_steps, desc="Salvando vídeo...")
75
-
76
- output_path, used_seed = video_generation_service.generate(
77
- prompt=prompt, negative_prompt=negative_prompt, mode=mode,
78
- start_image_filepath=start_image,
79
- middle_image_filepath=middle_image,
80
- middle_frame_number=middle_frame,
81
- middle_image_weight=middle_weight,
82
- end_image_filepath=end_image,
83
- end_image_weight=end_weight,
84
- input_video_filepath=input_video,
85
- height=int(height), width=int(width), duration=float(duration),
86
- frames_to_use=int(frames_to_use), seed=int(seed),
87
- randomize_seed=bool(randomize_seed), guidance_scale=float(guidance_scale),
88
- improve_texture=bool(improve_texture), progress_callback=progress_handler
89
- )
90
- return output_path, used_seed
91
- except ValueError as e:
92
- raise gr.Error(str(e))
93
- except Exception as e:
94
- print(f"Erro inesperado na geração: {e}")
95
- raise gr.Error("Ocorreu um erro inesperado. Verifique os logs.")
96
-
97
- # --- DEFINIÇÃO DA INTERFACE GRADIO ---
98
- css = "#col-container { margin: 0 auto; max-width: 900px; }"
99
- with gr.Blocks(css=css) as demo:
100
- gr.Markdown("# LTX Video com Keyframes")
101
- gr.Markdown("Guie a geração de vídeo usando imagens de início, meio e fim.")
102
-
103
- with gr.Row():
104
- with gr.Column():
105
- with gr.Tab("image-to-video (Keyframes)") as image_tab:
106
- i2v_prompt = gr.Textbox(label="Prompt", value="Uma bela transição entre as imagens", lines=2)
107
-
108
- with gr.Row():
109
- with gr.Column(scale=1):
110
- gr.Markdown("#### Início (Obrigatório)")
111
- start_image_i2v = gr.Image(label="Imagem de Início", type="filepath", sources=["upload", "clipboard"])
112
- with gr.Row():
113
- with gr.Accordion("Imagens condicionais opcional", open=False):
114
- with gr.Column(scale=1):
115
- gr.Markdown("#### Meio (Opcional)")
116
- middle_image_i2v = gr.Image(label="Imagem do Meio", type="filepath", sources=["upload", "clipboard"])
117
- middle_frame_i2v = gr.Slider(label="Frame Alvo", minimum=0, maximum=200, step=1, value=48)
118
- middle_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
119
- with gr.Column(scale=1):
120
- gr.Markdown("#### Fim (Opcional)")
121
- end_image_i2v = gr.Image(label="Imagem de Fim", type="filepath", sources=["upload", "clipboard"])
122
- end_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
123
-
124
- i2v_button = gr.Button("Generate Image-to-Video", variant="primary")
125
-
126
- with gr.Tab("text-to-video") as text_tab:
127
- t2v_prompt = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
128
- t2v_button = gr.Button("Generate Text-to-Video", variant="primary")
129
-
130
- with gr.Tab("video-to-video") as video_tab:
131
- video_v2v = gr.Video(label="Input Video", sources=["upload", "webcam"])
132
- 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.")
133
- v2v_prompt = gr.Textbox(label="Prompt", value="Change the style to cinematic anime", lines=3)
134
- v2v_button = gr.Button("Generate Video-to-Video", variant="primary")
135
-
136
- duration_input = gr.Slider(label="Video Duration (seconds)", minimum=1, maximum=30, value=8, step=0.5)
137
- improve_texture = gr.Checkbox(label="Improve Texture (multi-scale)", value=True, visible=True)
138
-
139
- with gr.Column():
140
- output_video = gr.Video(label="Generated Video", interactive=False)
141
-
142
- with gr.Accordion("Advanced settings", open=False):
143
- mode = gr.Dropdown(["text-to-video", "image-to-video", "video-to-video"], label="task", value="image-to-video", visible=False)
144
- negative_prompt_input = gr.Textbox(label="Negative Prompt", value="worst quality, blurry, jittery", lines=2)
145
- with gr.Row():
146
- seed_input = gr.Number(label="Seed", value=42, precision=0)
147
- randomize_seed_input = gr.Checkbox(label="Randomize Seed", value=True)
148
- guidance_scale_input = gr.Slider(label="Guidance Scale (CFG)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
149
- with gr.Row():
150
- height_input = gr.Slider(label="Height", value=512, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
151
- width_input = gr.Slider(label="Width", value=704, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
152
-
153
- # --- LÓGICA DE EVENTOS DA UI ---
154
-
155
- start_image_i2v.upload(fn=handle_media_upload_for_dims, inputs=[start_image_i2v, height_input, width_input], outputs=[height_input, width_input])
156
- video_v2v.upload(fn=handle_media_upload_for_dims, inputs=[video_v2v, height_input, width_input], outputs=[height_input, width_input])
157
- duration_input.change(fn=update_frame_slider, inputs=duration_input, outputs=middle_frame_i2v)
158
-
159
- image_tab.select(fn=lambda: "image-to-video", outputs=[mode])
160
- text_tab.select(fn=lambda: "text-to-video", outputs=[mode])
161
- video_tab.select(fn=lambda: "video-to-video", outputs=[mode])
162
-
163
- # Placeholders para os botões que não usam certos inputs
164
- none_image = gr.Textbox(visible=False, value=None)
165
- none_video = gr.Textbox(visible=False, value=None)
166
-
167
- # Parâmetros comuns a todos
168
- shared_params = [
169
- height_input, width_input, duration_input, frames_to_use,
170
- seed_input, randomize_seed_input, guidance_scale_input, improve_texture
171
- ]
172
-
173
- i2v_inputs = [
174
- i2v_prompt, negative_prompt_input, mode,
175
- start_image_i2v, middle_image_i2v, middle_frame_i2v, middle_weight_i2v,
176
- end_image_i2v, end_weight_i2v,
177
- none_video, # Placeholder para input_video
178
- *shared_params
179
- ]
180
-
181
- t2v_inputs = [
182
- t2v_prompt, negative_prompt_input, mode,
183
- none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), # Placeholders para keyframes
184
- none_image, gr.Slider(value=0, visible=False),
185
- none_video, # Placeholder para input_video
186
- *shared_params
187
- ]
188
-
189
- v2v_inputs = [
190
- v2v_prompt, negative_prompt_input, mode,
191
- none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), # Placeholders para keyframes
192
- none_image, gr.Slider(value=0, visible=False),
193
- video_v2v, # Input de vídeo real
194
- *shared_params
195
- ]
196
-
197
- common_outputs = [output_video, seed_input]
198
-
199
- i2v_button.click(fn=gradio_generate_wrapper, inputs=i2v_inputs, outputs=common_outputs, api_name="image_to_video_keyframes")
200
- t2v_button.click(fn=gradio_generate_wrapper, inputs=t2v_inputs, outputs=common_outputs, api_name="text_to_video")
201
- v2v_button.click(fn=gradio_generate_wrapper, inputs=v2v_inputs, outputs=common_outputs, api_name="video_to_video")
202
- # --- <FIM DA CORREÇÃO> ---
203
-
204
-
205
- if __name__ == "__main__":
206
- demo.queue().launch(debug=True, share=False)