File size: 11,705 Bytes
8bbdce0
db47818
 
 
 
 
5096465
db47818
 
7720807
 
 
8bbdce0
7720807
 
 
 
 
8bbdce0
7720807
db47818
35e29a5
db47818
 
 
994d098
db47818
 
8bbdce0
994d098
8bbdce0
 
d993e45
994d098
 
8bbdce0
 
 
994d098
8bbdce0
db47818
994d098
db47818
 
35e29a5
994d098
db47818
 
 
8bbdce0
994d098
7720807
 
 
 
db47818
994d098
8bbdce0
994d098
8bbdce0
 
 
 
 
861dd74
994d098
8bbdce0
 
 
 
 
 
861dd74
994d098
 
 
8bbdce0
db47818
994d098
db47818
 
 
 
 
8bbdce0
35e29a5
 
 
 
994d098
8bbdce0
35e29a5
994d098
35e29a5
 
994d098
db47818
 
 
 
 
35e29a5
db47818
994d098
db47818
994d098
35e29a5
db47818
994d098
db47818
994d098
db47818
 
f85c8b3
35e29a5
8bbdce0
db47818
 
 
 
 
 
994d098
 
 
 
 
 
 
 
8bbdce0
 
994d098
8bbdce0
 
994d098
 
 
 
 
8bbdce0
 
 
 
 
994d098
7720807
 
 
 
 
994d098
7720807
 
 
 
 
8bbdce0
994d098
db47818
 
 
994d098
db47818
9362b35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bbdce0
 
701d78c
7720807
 
 
 
994d098
8bbdce0
994d098
 
db47818
994d098
 
8bbdce0
9b84a2b
8bbdce0
994d098
db47818
 
 
35e29a5
 
8bbdce0
35e29a5
 
 
db47818
 
35e29a5
 
db47818
 
 
35e29a5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# app_refactored_with_postprod.py (com Presets de Guiagem e Opções LTX Completas)

import gradio as gr
import os
import sys
import traceback
from pathlib import Path

# --- Import dos Serviços de Backend ---
try:
    from api.ltx_server_refactored import video_generation_service
except ImportError:
    print("ERRO FATAL: Não foi possível importar 'video_generation_service' de 'api.ltx_server_refactored'.")
    sys.exit(1)

try:
    from api.seedvr_server import SeedVRServer
except ImportError:
    print("AVISO: Não foi possível importar SeedVRServer. A aba de upscaling SeedVR será desativada.")
    SeedVRServer = None

seedvr_inference_server = SeedVRServer() if SeedVRServer else None

# --- ESTADO DA SESSÃO ---
def create_initial_state():
    return {"low_res_video": None, "low_res_latents": None, "used_seed": None}

# --- FUNÇÕES WRAPPER PARA A UI ---

def run_generate_base_video(
    # Parâmetros de Geração
    generation_mode, prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed,
    fp_guidance_preset, fp_guidance_scale_list, fp_stg_scale_list, fp_timesteps_list,
    progress=gr.Progress(track_tqdm=True)
):
    """
    Função wrapper que decide qual pipeline de backend chamar, passando todas as configurações LTX.
    """
    print(f"UI: Iniciando geração no modo: {generation_mode}")
    
    try:
        initial_image_conditions = []
        if start_img:
            num_frames_estimate = int(duration * 24)
            items_list = [[start_img, 0, 1.0]]
            initial_image_conditions = video_generation_service.prepare_condition_items(items_list, height, width, num_frames_estimate)

        used_seed = None if randomize_seed else seed
        
        # Agrupa todas as configurações LTX em um único dicionário para o backend
        ltx_configs = {
            "guidance_preset": fp_guidance_preset,
            "guidance_scale_list": fp_guidance_scale_list,
            "stg_scale_list": fp_stg_scale_list,
            "timesteps_list": fp_timesteps_list,
        }

        # Decide qual função de backend chamar com base no modo
        if generation_mode == "Narrativa (Múltiplos Prompts)":
            video_path, tensor_path, final_seed = video_generation_service.generate_narrative_low(
                prompt=prompt, negative_prompt=neg_prompt,
                height=height, width=width, duration=duration,
                guidance_scale=cfg, seed=used_seed,
                initial_image_conditions=initial_image_conditions,
                ltx_configs_override=ltx_configs,
            )
        else: # Modo "Simples (Prompt Único)"
            video_path, tensor_path, final_seed = video_generation_service.generate_single_low(
                prompt=prompt, negative_prompt=neg_prompt,
                height=height, width=width, duration=duration,
                guidance_scale=cfg, seed=used_seed,
                initial_image_conditions=initial_image_conditions,
                ltx_configs_override=ltx_configs,
            )
        
        new_state = {"low_res_video": video_path, "low_res_latents": tensor_path, "used_seed": final_seed}
        
        return video_path, new_state, gr.update(visible=True)
        
    except Exception as e:
        error_message = f"❌ Ocorreu um erro na Geração Base:\n{e}"
        print(f"{error_message}\nDetalhes: {traceback.format_exc()}")
        raise gr.Error(error_message)

def run_ltx_refinement(state, prompt, neg_prompt, cfg, progress=gr.Progress(track_tqdm=True)):
    if not state or not state.get("low_res_latents"):
        raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
    try:
        video_path, tensor_path = video_generation_service.generate_upscale_denoise(
            latents_path=state["low_res_latents"], prompt=prompt,
            negative_prompt=neg_prompt, guidance_scale=cfg, seed=state["used_seed"]
        )
        state["refined_video_ltx"] = video_path; state["refined_latents_ltx"] = tensor_path
        return video_path, state
    except Exception as e:
        raise gr.Error(f"Erro no Refinamento LTX: {e}")

def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
    if not state or not state.get("low_res_video"):
        raise gr.Error("Erro: Gere um vídeo base primeiro na Etapa 1.")
    if not seedvr_inference_server:
        raise gr.Error("Erro: O servidor SeedVR não está disponível.")
    try:
        def progress_wrapper(p, desc=""): progress(p, desc=desc)
        output_filepath = seedvr_inference_server.run_inference(
            file_path=state["low_res_video"], seed=seed, resolution=resolution,
            batch_size=batch_size, fps=fps, progress=progress_wrapper
        )
        return gr.update(value=output_filepath), gr.update(value=f"✅ Concluído!\nSalvo em: {output_filepath}")
    except Exception as e:
        return None, gr.update(value=f"❌ Erro no SeedVR:\n{e}")

# --- DEFINIÇÃO DA INTERFACE GRADIO ---
with gr.Blocks() as demo:
    gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
    
    app_state = gr.State(value=create_initial_state())

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Etapa 1: Configurações de Geração")
            
            generation_mode_input = gr.Radio(
                label="Modo de Geração", choices=["Simples (Prompt Único)", "Narrativa (Múltiplos Prompts)"],
                value="Narrativa (Múltiplos Prompts)", info="Simples para uma ação, Narrativa para uma sequência (uma cena por linha)."
            )
            prompt_input = gr.Textbox(label="Prompt(s)", value="Um leão majestoso caminha pela savana\nEle sobe em uma grande pedra e olha o horizonte", lines=4)
            neg_prompt_input = gr.Textbox(label="Negative Prompt", value="blurry, low quality, bad anatomy", lines=2)
            start_image = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload"])
            
            with gr.Accordion("Parâmetros Principais", open=False):
                duration_input = gr.Slider(label="Duração Total (s)", value=1, step=1, minimum=1, maximum=40)
                with gr.Row():
                    height_input = gr.Slider(label="Height", value=720, step=32, minimum=256, maximum=1024)
                    width_input = gr.Slider(label="Width", value=720, step=32, minimum=256, maximum=1024)
                with gr.Row():
                    seed_input = gr.Number(label="Seed", value=42, precision=0)
                    randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)

            with gr.Accordion("Opções Adicionais LTX (Avançado)", open=False):
                cfg_input = gr.Slider(label="Guidance Scale (CFG)", info="Afeta o refinamento (se usado) e não tem efeito no First Pass dos modelos 'distilled'.", value=0.0, step=1, minimum=0.0, maximum=10.0)
                fp_num_inference_steps = gr.Slider(label="Passos de Inferência (First Pass)", minimum=10, maximum=100, step=1, value=10)
                ship_initial_inference_steps = gr.Slider(label="Passos de Inferência (Ship First)", minimum=0, maximum=100, step=1, value=0)
                ship_final_inference_steps = gr.Slider(label="Passos de Inferência (Ship Last)", minimum=0, maximum=100, step=1, value=0)
            
                with gr.Tabs():
                    with gr.TabItem("Guiagem (First Pass)"):
                        fp_guidance_preset = gr.Dropdown(
                            label="Preset de Guiagem",
                            choices=["Padrão (Recomendado)", "Agressivo", "Suave", "Customizado"],
                            value="Padrão (Recomendado)", info="Muda o comportamento da guiagem ao longo da difusão."
                        )
                        with gr.Group(visible=False) as custom_guidance_group:
                            gr.Markdown("⚠️ Edite as listas em formato JSON. Ex: `[1, 2, 3]`")
                            fp_guidance_scale_list = gr.Textbox(label="Lista de Guidance Scale", value="[1, 1, 6, 8, 6, 1, 1]")
                            fp_stg_scale_list = gr.Textbox(label="Lista de STG Scale (Movimento)", value="[0, 0, 4, 4, 4, 2, 1]")
                            fp_timesteps_list = gr.Textbox(label="Lista de Guidance Timesteps", value="[1.0, 0.996, 0.9933, 0.9850, 0.9767, 0.9008, 0.6180]")
                        
            generate_low_btn = gr.Button("1. Gerar Vídeo Base", variant="primary")
        
        with gr.Column(scale=1):
            gr.Markdown("### Vídeo Base Gerado")
            low_res_video_output = gr.Video(label="O resultado da Etapa 1 aparecerá aqui", interactive=False)

    with gr.Group(visible=False) as post_prod_group:
        gr.Markdown("## Etapa 2: Pós-Produção")
        
        with gr.Tabs():
            with gr.TabItem("🚀 Upscaler Textura (LTX)"):
                with gr.Row():
                    with gr.Column(scale=1):
                         gr.Markdown("Reutiliza o prompt e CFG para refinar a textura.")
                         ltx_refine_btn = gr.Button("Aplicar Refinamento LTX", variant="primary")
                    with gr.Column(scale=1):
                        ltx_refined_video_output = gr.Video(label="Vídeo com Textura Refinada", interactive=False)
            
            with gr.TabItem("✨ Upscaler SeedVR"):
                with gr.Row():
                    with gr.Column(scale=1):
                        seedvr_seed = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
                        seedvr_resolution = gr.Slider(minimum=720, maximum=1440, value=1072, step=8, label="Resolução Vertical")
                        seedvr_batch_size = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
                        seedvr_fps_output = gr.Number(label="FPS de Saída (0 = original)", value=0)
                        run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
                    with gr.Column(scale=1):
                        seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
                        seedvr_status_box = gr.Textbox(label="Status", value="Aguardando...", lines=3, interactive=False)

    # --- LÓGICA DE EVENTOS ---
    def update_custom_guidance_visibility(preset_choice):
        return gr.update(visible=(preset_choice == "Customizado"))
    
    fp_guidance_preset.change(fn=update_custom_guidance_visibility, inputs=fp_guidance_preset, outputs=custom_guidance_group)

    all_ltx_inputs = [
        fp_guidance_preset, fp_guidance_scale_list, fp_stg_scale_list, fp_timesteps_list
    ]
    
    generate_low_btn.click(
        fn=run_generate_base_video,
        inputs=[
            generation_mode_input, prompt_input, neg_prompt_input, start_image, height_input, width_input, 
            duration_input, cfg_input, seed_input, randomize_seed,
            *all_ltx_inputs
        ],
        outputs=[low_res_video_output, app_state, post_prod_group]
    )

    ltx_refine_btn.click(
        fn=run_ltx_refinement,
        inputs=[app_state, prompt_input, neg_prompt_input, cfg_input],
        outputs=[ltx_refined_video_output, app_state]
    )

    run_seedvr_button.click(
        fn=run_seedvr_upscaling,
        inputs=[app_state, seedvr_seed, seedvr_resolution, seedvr_batch_size, seedvr_fps_output],
        outputs=[seedvr_video_output, seedvr_status_box]
    )

if __name__ == "__main__":
    demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True)