XCarleX commited on
Commit
8ca7229
·
verified ·
1 Parent(s): 2652da1

Upload app (27).py

Browse files
Files changed (1) hide show
  1. app (27).py +186 -0
app (27).py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (Versão com UI para Upscaler)
2
+
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import os
6
+ import imageio
7
+
8
+ # --- FUNÇÕES DE AJUDA PARA A UI ---
9
+ TARGET_FIXED_SIDE = 768
10
+ MIN_DIM_SLIDER = 256
11
+ MAX_IMAGE_SIZE = 1280
12
+
13
+ def calculate_new_dimensions(orig_w, orig_h):
14
+ if orig_w == 0 or orig_h == 0: return int(TARGET_FIXED_SIDE), int(TARGET_FIXED_SIDE)
15
+ if orig_w >= orig_h:
16
+ new_h, aspect_ratio = TARGET_FIXED_SIDE, orig_w / orig_h
17
+ new_w = round((new_h * aspect_ratio) / 32) * 32
18
+ new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
19
+ new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
20
+ else:
21
+ new_w, aspect_ratio = TARGET_FIXED_SIDE, orig_h / orig_w
22
+ new_h = round((new_w * aspect_ratio) / 32) * 32
23
+ new_h = max(MIN_DIM_SLIDER, min(new_h, MAX_IMAGE_SIZE))
24
+ new_w = max(MIN_DIM_SLIDER, min(new_w, MAX_IMAGE_SIZE))
25
+ return int(new_h), int(new_w)
26
+
27
+ def handle_media_upload_for_dims(filepath, current_h, current_w):
28
+ if not filepath or not os.path.exists(str(filepath)): return gr.update(value=current_h), gr.update(value=current_w)
29
+ try:
30
+ if str(filepath).lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
31
+ with Image.open(filepath) as img:
32
+ orig_w, orig_h = img.size
33
+ else: # Assumir que é um vídeo
34
+ with imageio.get_reader(filepath) as reader:
35
+ meta = reader.get_meta_data()
36
+ orig_w, orig_h = meta.get('size', (current_w, current_h))
37
+ new_h, new_w = calculate_new_dimensions(orig_w, orig_h)
38
+ return gr.update(value=new_h), gr.update(value=new_w)
39
+ except Exception as e:
40
+ print(f"Erro ao processar mídia para dimensões: {e}")
41
+ return gr.update(value=current_h), gr.update(value=current_w)
42
+
43
+ def update_frame_slider(duration):
44
+ fps = 24.0
45
+ max_frames = int(duration * fps)
46
+ new_value = 48 if max_frames >= 48 else max_frames // 2
47
+ return gr.update(maximum=max_frames, value=new_value)
48
+
49
+
50
+ # --- FUNÇÃO WRAPPER PARA CHAMAR O SERVIÇO ---
51
+ def gradio_generate_wrapper(
52
+ prompt, negative_prompt, mode,
53
+ start_image, middle_image, middle_frame, middle_weight, end_image, end_weight,
54
+ input_video, height, width, duration,
55
+ frames_to_use, seed, randomize_seed,
56
+ guidance_scale, enable_upscaler, adain_factor,
57
+ progress=gr.Progress(track_tqdm=True)
58
+ ):
59
+ try:
60
+ #output_path, used_seed = video_generation_service.generate(
61
+ # prompt=prompt, negative_prompt=negative_prompt, mode=mode,
62
+ # start_image_filepath=start_image,
63
+ # middle_image_filepath=middle_image,
64
+ # middle_frame_number=middle_frame,
65
+ # middle_image_weight=middle_weight,
66
+ # end_image_filepath=end_image,
67
+ # end_image_weight=end_weight,
68
+ # input_video_filepath=input_video,
69
+ # height=int(height), width=int(width), duration=float(duration),
70
+ # frames_to_use=int(frames_to_use), seed=int(seed),
71
+ # randomize_seed=bool(randomize_seed), guidance_scale=float(guidance_scale),
72
+ # enable_upscaler=bool(enable_upscaler),
73
+ # adain_factor=float(adain_factor),
74
+ # progress_callback=progress
75
+ #)
76
+ return None, None
77
+ except ValueError as e:
78
+ raise gr.Error(str(e))
79
+ except Exception as e:
80
+ print(f"Erro inesperado na geração: {e}")
81
+ raise gr.Error("Ocorreu um erro inesperado. Verifique os logs.")
82
+
83
+ # --- DEFINIÇÃO DA INTERFACE GRADIO ---
84
+ css = "#col-container { margin: 0 auto; max-width: 900px; }"
85
+ with gr.Blocks(css=css) as demo:
86
+ gr.Markdown("# LTX Video com Keyframes e Latent Upscaler")
87
+ gr.Markdown("Gere vídeos em baixa resolução e opcionalmente duplique a resolução com um Upscaler.")
88
+
89
+ with gr.Row():
90
+ with gr.Column():
91
+ with gr.Tab("image-to-video (Keyframes)") as image_tab:
92
+ i2v_prompt = gr.Textbox(label="Prompt", value="Uma bela transição entre as imagens", lines=2)
93
+ with gr.Row():
94
+ with gr.Column(scale=1):
95
+ gr.Markdown("#### Keyframe de Início (Obrigatório)")
96
+ start_image_i2v = gr.Image(label="Imagem de Início", type="filepath", sources=["upload", "clipboard"])
97
+ with gr.Column(scale=1):
98
+ with gr.Accordion("Keyframe do Meio (Opcional)", open=False):
99
+ middle_image_i2v = gr.Image(label="Imagem do Meio", type="filepath", sources=["upload", "clipboard"]); middle_frame_i2v = gr.Slider(label="Frame Alvo", minimum=0, maximum=200, step=1, value=48); middle_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
100
+ with gr.Column(scale=1):
101
+ with gr.Accordion("Keyframe de Fim (Opcional)", open=False):
102
+ end_image_i2v = gr.Image(label="Imagem de Fim", type="filepath", sources=["upload", "clipboard"]); end_weight_i2v = gr.Slider(label="Peso/Força", minimum=0.0, maximum=1.0, step=0.05, value=1.0)
103
+ i2v_button = gr.Button("Generate Image-to-Video", variant="primary")
104
+
105
+ with gr.Tab("text-to-video") as text_tab:
106
+ t2v_prompt = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3); t2v_button = gr.Button("Generate Text-to-Video", variant="primary")
107
+
108
+ with gr.Tab("video-to-video") as video_tab:
109
+ video_v2v = gr.Video(label="Input Video", sources=["upload", "webcam"]); 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."); v2v_prompt = gr.Textbox(label="Prompt", value="Change the style to cinematic anime", lines=3); v2v_button = gr.Button("Generate Video-to-Video", variant="primary")
110
+
111
+ duration_input = gr.Slider(label="Video Duration (seconds)", minimum=0.3, maximum=8.5, value=4, step=0.1)
112
+
113
+ with gr.Column():
114
+ output_video = gr.Video(label="Generated Video", interactive=False)
115
+
116
+ with gr.Accordion("Opções Avançadas", open=False):
117
+ mode = gr.Dropdown(["text-to-video", "image-to-video", "video-to-video"], label="task", value="image-to-video", visible=False)
118
+
119
+ with gr.Accordion("Ajustes de Geração (Sampling)", open=True):
120
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value="worst quality, blurry, jittery", lines=2)
121
+ with gr.Row():
122
+ seed_input = gr.Number(label="Seed", value=42, precision=0)
123
+ randomize_seed_input = gr.Checkbox(label="Randomize Seed", value=True)
124
+ guidance_scale_input = gr.Slider(label="Guidance Scale (CFG)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
125
+
126
+ with gr.Accordion("Dimensões do Vídeo (Base)", open=False):
127
+ with gr.Row():
128
+ height_input = gr.Slider(label="Height", value=512, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
129
+ width_input = gr.Slider(label="Width", value=704, step=32, minimum=MIN_DIM_SLIDER, maximum=MAX_IMAGE_SIZE)
130
+
131
+ with gr.Accordion("Configurações do Upscaler 2x (Etapa 2)", open=False):
132
+ with gr.Row():
133
+ enable_upscaler_input = gr.Checkbox(label="Enable Upscaler", value=True, info="Gera o vídeo final com o dobro da resolução base.")
134
+ adain_factor_input = gr.Slider(label="AdaIN Factor", minimum=0.0, maximum=2.0, value=1.0, step=0.05, info="Controla a transferência de estilo/cor para o vídeo ampliado.")
135
+
136
+ # --- LÓGICA DE EVENTOS DA UI ---
137
+ start_image_i2v.upload(fn=handle_media_upload_for_dims, inputs=[start_image_i2v, height_input, width_input], outputs=[height_input, width_input])
138
+ video_v2v.upload(fn=handle_media_upload_for_dims, inputs=[video_v2v, height_input, width_input], outputs=[height_input, width_input])
139
+ duration_input.change(fn=update_frame_slider, inputs=duration_input, outputs=middle_frame_i2v)
140
+
141
+ image_tab.select(fn=lambda: "image-to-video", outputs=[mode])
142
+ text_tab.select(fn=lambda: "text-to-video", outputs=[mode])
143
+ video_tab.select(fn=lambda: "video-to-video", outputs=[mode])
144
+
145
+ none_image = gr.Textbox(visible=False, value=None)
146
+ none_video = gr.Textbox(visible=False, value=None)
147
+
148
+ shared_params = [
149
+ height_input, width_input, duration_input, frames_to_use,
150
+ seed_input, randomize_seed_input, guidance_scale_input,
151
+ enable_upscaler_input, adain_factor_input
152
+ ]
153
+
154
+ i2v_inputs = [i2v_prompt, negative_prompt_input, mode, start_image_i2v, middle_image_i2v, middle_frame_i2v, middle_weight_i2v, end_image_i2v, end_weight_i2v, none_video, *shared_params]
155
+ t2v_inputs = [t2v_prompt, negative_prompt_input, mode, none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), none_image, gr.Slider(value=0, visible=False), none_video, *shared_params]
156
+ v2v_inputs = [v2v_prompt, negative_prompt_input, mode, none_image, none_image, gr.Number(value=-1, visible=False), gr.Slider(value=0, visible=False), none_image, gr.Slider(value=0, visible=False), video_v2v, *shared_params]
157
+
158
+ common_outputs = [output_video, seed_input]
159
+
160
+ i2v_button.click(fn=gradio_generate_wrapper, inputs=i2v_inputs, outputs=common_outputs, api_name="image_to_video_keyframes")
161
+ t2v_button.click(fn=gradio_generate_wrapper, inputs=t2v_inputs, outputs=common_outputs, api_name="text_to_video")
162
+ v2v_button.click(fn=gradio_generate_wrapper, inputs=v2v_inputs, outputs=common_outputs, api_name="video_to_video")
163
+
164
+ # --- <INÍCIO DA ATUALIZAÇÃO> ---
165
+ if __name__ == "__main__":
166
+ import sys
167
+
168
+ # Define os padrões de inicialização
169
+ share_option = False
170
+ server_name = "127.0.0.1"
171
+
172
+ # Verifica se argumentos foram passados na linha de comando
173
+ if '--share' in sys.argv:
174
+ share_option = True
175
+ print("Iniciando com a opção de compartilhamento público (share=True)")
176
+
177
+ if '--listen' in sys.argv:
178
+ server_name = "0.0.0.0"
179
+ print("Iniciando para ser acessível na rede local (listen)")
180
+
181
+ # Inicia a aplicação com as opções definidas
182
+ demo.queue().launch(
183
+ debug=True,
184
+ share=share_option,
185
+ server_name=server_name
186
+ )