Carlexx commited on
Commit
06a2ae7
·
verified ·
1 Parent(s): 414cdce

Delete app5.5.6.py

Browse files
Files changed (1) hide show
  1. app5.5.6.py +0 -423
app5.5.6.py DELETED
@@ -1,423 +0,0 @@
1
- # Euia-AducSdr: Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
2
- # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
- #
4
- # Contato:
5
- # Carlos Rodrigues dos Santos
6
7
- # Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
8
- #
9
- # Repositórios e Projetos Relacionados:
10
- # GitHub: https://github.com/carlex22/Aduc-sdr
11
- # Hugging Face: https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
12
- # Hugging Face: https://huggingface.co/spaces/Carlexxx/Novinho/
13
- #
14
- # Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
15
- # sob os termos da Licença Pública Geral Affero da GNU como publicada pela
16
- # Free Software Foundation, seja a versão 3 da Licença, ou
17
- # (a seu critério) qualquer versão posterior.
18
- #
19
- # Este programa é distribuído na esperança de que seja útil,
20
- # mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
21
- # COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
22
- # Licença Pública Geral Affero da GNU para mais detalhes.
23
- #
24
- # Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
25
- # junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
26
-
27
- # --- app.py (NOVINHO-5.3-DEJAVU: Lógica de Handoff com "Eco Fantasma") ---
28
-
29
- # --- Ato 1: A Convocação da Orquestra (Importações) ---
30
- import gradio as gr
31
- import torch
32
- import os
33
- import yaml
34
- from PIL import Image, ImageOps, ExifTags
35
- import shutil
36
- import gc
37
- import subprocess
38
- import google.generativeai as genai
39
- import numpy as np
40
- import imageio
41
- from pathlib import Path
42
- import huggingface_hub
43
- import json
44
- import time
45
-
46
- from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
47
- from dreamo_helpers import dreamo_generator_singleton
48
-
49
- # --- Ato 2: A Preparação do Palco (Configurações) ---
50
- config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
51
- with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
52
-
53
- LTX_REPO = "Lightricks/LTX-Video"
54
- models_dir = "downloaded_models_gradio"
55
- Path(models_dir).mkdir(parents=True, exist_ok=True)
56
- WORKSPACE_DIR = "aduc_workspace"
57
- GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
58
-
59
- # Valores padrão que agora podem ser sobrescritos pela UI
60
- VIDEO_FPS_DEFAULT = 24
61
- VIDEO_DURATION_SECONDS_DEFAULT = 8.0
62
- TARGET_RESOLUTION = 420
63
-
64
- print("Criando pipelines LTX na CPU (estado de repouso)...")
65
- distilled_model_actual_path = huggingface_hub.hf_hub_download(repo_id=LTX_REPO, filename=PIPELINE_CONFIG_YAML["checkpoint_path"], local_dir=models_dir, local_dir_use_symlinks=False)
66
- pipeline_instance = create_ltx_video_pipeline(
67
- ckpt_path=distilled_model_actual_path,
68
- precision=PIPELINE_CONFIG_YAML["precision"],
69
- text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
70
- sampler=PIPELINE_CONFIG_YAML["sampler"],
71
- device='cpu'
72
- )
73
- print("Modelos LTX prontos (na CPU).")
74
-
75
-
76
- # --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
77
-
78
- # --- Funções da ETAPA 1 (Roteiro) ---
79
- def robust_json_parser(raw_text: str) -> dict:
80
- try:
81
- start_index = raw_text.find('{'); end_index = raw_text.rfind('}')
82
- if start_index != -1 and end_index != -1 and end_index > start_index:
83
- json_str = raw_text[start_index : end_index + 1]
84
- return json.loads(json_str)
85
- else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
86
- except json.JSONDecodeError as e: raise ValueError(f"Falha ao decodificar JSON: {e}")
87
-
88
- def extract_image_exif(image_path: str) -> str:
89
- try:
90
- img = Image.open(image_path); exif_data = img._getexif()
91
- if not exif_data: return "No EXIF metadata found."
92
- exif = { ExifTags.TAGS[k]: v for k, v in exif_data.items() if k in ExifTags.TAGS }
93
- relevant_tags = ['DateTimeOriginal', 'Model', 'LensModel', 'FNumber', 'ExposureTime', 'ISOSpeedRatings', 'FocalLength']
94
- metadata_str = ", ".join(f"{key}: {exif[key]}" for key in relevant_tags if key in exif)
95
- return metadata_str if metadata_str else "No relevant EXIF metadata found."
96
- except Exception: return "Could not read EXIF data."
97
-
98
- def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
99
- if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
100
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
101
- exif_metadata = extract_image_exif(initial_image_path)
102
- prompt_file = "prompts/unified_storyboard_prompt.txt"
103
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
104
- director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata=exif_metadata)
105
- genai.configure(api_key=GEMINI_API_KEY)
106
- model = genai.GenerativeModel('gemini-2.0-flash'); img = Image.open(initial_image_path)
107
- response = model.generate_content([director_prompt, img])
108
- try:
109
- storyboard_data = robust_json_parser(response.text)
110
- storyboard = storyboard_data.get("scene_storyboard", [])
111
- if not storyboard or len(storyboard) != int(num_fragments): raise ValueError(f"A IA não gerou o número correto de cenas. Esperado: {num_fragments}, Recebido: {len(storyboard)}")
112
- return storyboard
113
- except Exception as e: raise gr.Error(f"O Roteirista (Gemini) falhou: {e}. Resposta recebida: {response.text}")
114
-
115
- # --- Funções da ETAPA 2 (Keyframes) ---
116
- def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
117
- genai.configure(api_key=GEMINI_API_KEY)
118
- prompt_file = "prompts/img2img_evolution_prompt.txt"
119
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
120
- director_prompt = template.format(target_scene_description=target_scene_description)
121
- model = genai.GenerativeModel('gemini-2.0-flash'); img = Image.open(previous_image_path)
122
- response = model.generate_content([director_prompt, "Previous Image:", img])
123
- return response.text.strip().replace("\"", "")
124
-
125
- def run_keyframe_generation(storyboard, initial_ref_image_path, sequential_ref_task, *additional_refs_and_tasks, progress=gr.Progress()):
126
- if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
127
- if not initial_ref_image_path: raise gr.Error("A imagem de referência principal é obrigatória.")
128
- log_history = ""; generated_images_for_gallery = []
129
- base_reference_items = []
130
- num_pairs = len(additional_refs_and_tasks) // 2
131
- for i in range(num_pairs):
132
- img_path, task = additional_refs_and_tasks[i * 2], additional_refs_and_tasks[i * 2 + 1]
133
- if img_path: base_reference_items.append({'image_np': np.array(Image.open(img_path).convert("RGB")), 'task': task})
134
- try:
135
- pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
136
- dreamo_generator_singleton.to_gpu()
137
- with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
138
- keyframe_paths, current_ref_image_path = [initial_ref_image_path], initial_ref_image_path
139
- for i, scene_description in enumerate(storyboard):
140
- progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
141
- log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
142
- dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
143
- recent_references_paths = keyframe_paths[-3:]
144
- sequential_reference_items = [{'image_np': np.array(Image.open(ref_path).convert("RGB")), 'task': sequential_ref_task} for ref_path in recent_references_paths]
145
- all_reference_items = base_reference_items + sequential_reference_items
146
- log_history += f" - Roteiro: '{scene_description}'\n - Usando {len(all_reference_items)} refs. Prompt do D.A.: \"{dreamo_prompt}\"\n"
147
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
148
- output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
149
- image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=all_reference_items, prompt=dreamo_prompt, width=width, height=height)
150
- image.save(output_path)
151
- keyframe_paths.append(output_path); generated_images_for_gallery.append(output_path); current_ref_image_path = output_path
152
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
153
- except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
154
- finally: dreamo_generator_singleton.to_cpu(); gc.collect(); torch.cuda.empty_cache()
155
- log_history += "\nPintura de todos os keyframes concluída.\n"
156
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery), keyframe_images_state: keyframe_paths}
157
-
158
- # --- Funções da ETAPA 3 (Produção de Vídeo) ---
159
- def get_initial_motion_prompt(user_prompt, start_image_path, destination_image_path, dest_scene_desc):
160
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
161
- try:
162
- genai.configure(api_key=GEMINI_API_KEY)
163
- model = genai.GenerativeModel('gemini-2.0-flash')
164
- prompt_file = "prompts/initial_motion_prompt.txt"
165
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
166
- cinematographer_prompt = template.format(user_prompt=user_prompt, destination_scene_description=dest_scene_desc)
167
- start_img, dest_img = Image.open(start_image_path), Image.open(destination_image_path)
168
- model_contents = ["START Image:", start_img, "DESTINATION Image:", dest_img, cinematographer_prompt]
169
- response = model.generate_content(model_contents)
170
- return response.text.strip()
171
- except Exception as e: raise gr.Error(f"O Cineasta de IA (Inicial) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
172
-
173
- def get_dynamic_motion_prompt(user_prompt, story_history, memory_image_path, path_image_path, destination_image_path, path_scene_desc, dest_scene_desc):
174
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
175
- try:
176
- genai.configure(api_key=GEMINI_API_KEY)
177
- model = genai.GenerativeModel('gemini-2.0-flash')
178
- prompt_file = "prompts/dynamic_motion_prompt.txt"
179
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
180
- cinematographer_prompt = template.format(user_prompt=user_prompt, story_history=story_history, midpoint_scene_description=path_scene_desc, destination_scene_description=dest_scene_desc)
181
- mem_img, path_img, dest_img = Image.open(memory_image_path), Image.open(path_image_path), Image.open(destination_image_path)
182
- model_contents = ["START Image (Memory):", mem_img, "MIDPOINT Image (Path):", path_img, "DESTINATION Image (Destination):", dest_img, cinematographer_prompt]
183
- response = model.generate_content(model_contents)
184
- return response.text.strip()
185
- except Exception as e: raise gr.Error(f"O Cineasta de IA (Dinâmico) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
186
-
187
- def run_video_production(prompt_geral, keyframe_images_state, scene_storyboard, seed, cfg,
188
- video_duration, video_fps, num_inference_steps, handoff_point, use_slicing,
189
- mid_cond_strength, end_cond_offset, end_cond_strength,
190
- progress=gr.Progress()):
191
- if not keyframe_images_state or len(keyframe_images_state) < 3: raise gr.Error("Pinte pelo menos 2 keyframes para produzir uma transição.")
192
- log_history = "\n--- FASE 3/4: Iniciando Produção com Lógica 'Big Bang' e 'Eco Fantasma'...\n"
193
- yield {production_log_output: log_history, video_gallery_glitch: []}
194
-
195
- VIDEO_TOTAL_FRAMES = int(video_duration * video_fps)
196
- END_COND_FRAME = VIDEO_TOTAL_FRAMES - int(end_cond_offset)
197
- if int(handoff_point) >= END_COND_FRAME:
198
- raise gr.Error(f"Erro de timing: O 'Ponto de Handoff' ({handoff_point}) não pode ocorrer no mesmo frame ou depois do frame de 'Destino' ({END_COND_FRAME}). Aumente a duração, diminua o offset ou reduza o ponto de handoff.")
199
-
200
- target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
201
- try:
202
- pipeline_instance.to(target_device)
203
- video_fragments, story_history = [], ""
204
- kinetic_memory_path = None # Esta será a nossa memória, o "Eco Fantasma"
205
-
206
- with Image.open(keyframe_images_state[1]) as img: width, height = img.size
207
-
208
- num_transitions = len(keyframe_images_state) - 2
209
- for i in range(num_transitions):
210
- fragment_num = i + 1
211
- progress(i / num_transitions, desc=f"Filmando Fragmento {fragment_num}/{num_transitions}")
212
- log_history += f"\n--- FRAGMENTO {fragment_num} ---\n"
213
-
214
- if i == 0: # Big Bang
215
- start_path, destination_path = keyframe_images_state[1], keyframe_images_state[2]
216
- dest_scene_desc = scene_storyboard[1]
217
- log_history += f" - Início (Big Bang): {os.path.basename(start_path)}\n - Destino: {os.path.basename(destination_path)}\n"
218
- current_motion_prompt = get_initial_motion_prompt(prompt_geral, start_path, destination_path, dest_scene_desc)
219
- conditioning_items_data = [(start_path, 0, 1.0), (destination_path, END_COND_FRAME, float(end_cond_strength))]
220
- else: # Handoff Cinético com "Eco Fantasma"
221
- memory_path, path_path, destination_path = kinetic_memory_path, keyframe_images_state[i+1], keyframe_images_state[i+2]
222
- path_scene_desc, dest_scene_desc = scene_storyboard[i], scene_storyboard[i+1]
223
- log_history += f" - Memória (Eco Fantasma): {os.path.basename(memory_path)}\n - Caminho (Déjà Vu): {os.path.basename(path_path)}\n - Destino: {os.path.basename(destination_path)}\n"
224
- current_motion_prompt = get_dynamic_motion_prompt(prompt_geral, story_history, memory_path, path_path, destination_path, path_scene_desc, dest_scene_desc)
225
- conditioning_items_data = [(memory_path, 0, 1.0), (path_path, int(handoff_point), float(mid_cond_strength)), (destination_path, END_COND_FRAME, float(end_cond_strength))]
226
-
227
- story_history += f"\n- Ato {fragment_num + 1}: {current_motion_prompt}"
228
- log_history += f" - Instrução do Cineasta: '{current_motion_prompt}'\n"; yield {production_log_output: log_history}
229
-
230
- full_fragment_path, _ = run_ltx_animation(
231
- current_fragment_index=fragment_num, motion_prompt=current_motion_prompt, conditioning_items_data=conditioning_items_data,
232
- width=width, height=height, seed=seed, cfg=cfg, video_total_frames=VIDEO_TOTAL_FRAMES, video_fps=video_fps,
233
- num_inference_steps=num_inference_steps, use_slicing=use_slicing, progress=progress
234
- )
235
-
236
- # *** LÓGICA DO ECO FANTASMA IMPLEMENTADA AQUI ***
237
- is_last_fragment = (i == num_transitions - 1)
238
- if is_last_fragment:
239
- final_fragment_path = full_fragment_path
240
- log_history += " - Último fragmento gerado, mantendo a duração total para um final limpo.\n"
241
- else:
242
- # 1. Extrai o "Eco Fantasma" do vídeo COMPLETO para a PRÓXIMA geração
243
- eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_fantasma_from_frag_{fragment_num}.png")
244
- kinetic_memory_path = extract_last_frame_as_image(full_fragment_path, eco_output_path)
245
-
246
- # 2. Corta o vídeo para a montagem FINAL
247
- final_fragment_path = os.path.join(WORKSPACE_DIR, f"fragment_{fragment_num}_trimmed.mp4")
248
- trim_video_to_frames(full_fragment_path, final_fragment_path, int(handoff_point))
249
-
250
- log_history += f" - Gerado e cortado em {handoff_point} frames.\n - Novo Eco Fantasma (Déjà Vu) criado para o próximo fragmento: {os.path.basename(kinetic_memory_path)}\n"
251
-
252
- video_fragments.append(final_fragment_path)
253
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
254
-
255
- progress(1.0, desc="Produção Concluída.")
256
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
257
- finally:
258
- pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
259
-
260
-
261
- # --- Funções Utilitárias e de Pós-Produção ---
262
- def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
263
- if not image_path: return None
264
- try:
265
- img = Image.open(image_path).convert("RGB"); img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
266
- output_path = os.path.join(WORKSPACE_DIR, f"initial_ref_{size}x{size}.png"); img_square.save(output_path)
267
- return output_path
268
- except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
269
-
270
- def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
271
- return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
272
-
273
- def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg,
274
- video_total_frames, video_fps, num_inference_steps, use_slicing, progress=gr.Progress()):
275
- progress(0, desc=f"[Câmera LTX] Filmando Cena {current_fragment_index}...");
276
- output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4"); target_device = pipeline_instance.device
277
- try:
278
- if use_slicing: pipeline_instance.enable_attention_slicing()
279
- conditioning_items = [ConditioningItem(load_conditioning_tensor(p, height, width).to(target_device), s, t) for p, s, t in conditioning_items_data]
280
- actual_num_frames = int(round((float(video_total_frames) - 1.0) / 8.0) * 8 + 1)
281
- padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
282
- padding_vals = calculate_padding(height, width, padded_h, padded_w)
283
- for item in conditioning_items: item.media_item = torch.nn.functional.pad(item.media_item, padding_vals)
284
- kwargs = {
285
- "prompt": motion_prompt, "negative_prompt": "blurry, distorted, bad quality, artifacts",
286
- "height": padded_h, "width": padded_w, "num_frames": actual_num_frames, "frame_rate": int(video_fps),
287
- "generator": torch.Generator(device=target_device).manual_seed(int(seed) + current_fragment_index),
288
- "output_type": "pt", "guidance_scale": float(cfg), "timesteps": int(num_inference_steps),
289
- "conditioning_items": conditioning_items, "decode_timestep": PIPELINE_CONFIG_YAML.get("decode_timestep"),
290
- "decode_noise_scale": PIPELINE_CONFIG_YAML.get("decode_noise_scale"), "stochastic_sampling": PIPELINE_CONFIG_YAML.get("stochastic_sampling"),
291
- "image_cond_noise_scale": 0.15, "is_video": True, "vae_per_channel_normalize": True,
292
- "mixed_precision": (PIPELINE_CONFIG_YAML.get("precision") == "mixed_precision"), "enhance_prompt": False, "decode_every": 4
293
- }
294
- result_tensor = pipeline_instance(**kwargs).images
295
- pad_l, pad_r, pad_t, pad_b = map(int, padding_vals); slice_h = -pad_b if pad_b > 0 else None; slice_w = -pad_r if pad_r > 0 else None
296
- cropped_tensor = result_tensor[:, :, :video_total_frames, pad_t:slice_h, pad_l:slice_w]
297
- video_np = (cropped_tensor[0].permute(1, 2, 3, 0).cpu().float().numpy() * 255).astype(np.uint8)
298
- with imageio.get_writer(output_path, fps=int(video_fps), codec='libx264', quality=8) as writer:
299
- for i, frame in enumerate(video_np): writer.append_data(frame)
300
- return output_path, actual_num_frames
301
- finally:
302
- if use_slicing: pipeline_instance.disable_attention_slicing()
303
-
304
- def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
305
- try:
306
- subprocess.run(f"ffmpeg -y -v error -i \"{input_path}\" -vf \"select='lt(n,{frames_to_keep})'\" -an \"{output_path}\"", shell=True, check=True, text=True)
307
- return output_path
308
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao cortar vídeo: {e.stderr}")
309
-
310
- def extract_last_frame_as_image(video_path: str, output_image_path: str) -> str:
311
- try:
312
- subprocess.run(f"ffmpeg -y -v error -sseof -1 -i \"{video_path}\" -update 1 -q:v 1 \"{output_image_path}\"", shell=True, check=True, text=True)
313
- return output_image_path
314
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao extrair último frame: {e.stderr}")
315
-
316
- def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
317
- if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
318
- progress(0.5, desc="Montando a obra-prima final...");
319
- try:
320
- list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
321
- with open(list_file_path, "w") as f:
322
- for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
323
- subprocess.run(f"ffmpeg -y -v error -f concat -safe 0 -i \"{list_file_path}\" -c copy \"{final_output_path}\"", shell=True, check=True, text=True)
324
- progress(1.0, desc="Montagem concluída!")
325
- return final_output_path
326
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
327
-
328
- # --- Ato 5: A Interface com o Mundo (UI) ---
329
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
330
- gr.Markdown("# NOVINHO-5.3 (Déjà Vu)\n*By Carlex & Gemini & DreamO*")
331
-
332
- if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
333
- os.makedirs(WORKSPACE_DIR); Path("prompts").mkdir(exist_ok=True)
334
-
335
- # State variables
336
- scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
337
- prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
338
- MAX_ADDITIONAL_REFS = 4
339
-
340
- gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
341
- with gr.Row():
342
- with gr.Column(scale=1):
343
- prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
344
- num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Atos (Keyframes)")
345
- image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
346
- director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
347
- with gr.Column(scale=2):
348
- storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado (em Inglês)")
349
-
350
- gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
351
- with gr.Row():
352
- with gr.Column(scale=2):
353
- gr.Markdown("O Pintor usará as referências abaixo + as **3 últimas imagens** geradas para criar a próxima.")
354
- with gr.Group():
355
- ref1_image = gr.Image(label="Referência Principal (Automática da Etapa 1)", type="filepath", interactive=False)
356
- ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa das Referências em Cadeia")
357
- additional_ref_images, additional_ref_tasks = [], []
358
- with gr.Accordion("Referências Adicionais do Pintor (Opcional)", open=False):
359
- with gr.Tabs():
360
- for i in range(MAX_ADDITIONAL_REFS):
361
- with gr.TabItem(f"Ref. Extra {i+1}"):
362
- with gr.Column():
363
- ref_img = gr.Image(label=f"Imagem de Referência Extra {i+1}", type="filepath", scale=2)
364
- ref_task_dd = gr.Dropdown(choices=["ip", "id", "style"], value="style", label=f"Tarefa da Ref. Extra {i+1}")
365
- additional_ref_images.append(ref_img)
366
- additional_ref_tasks.append(ref_task_dd)
367
- photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
368
- keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=10, interactive=False)
369
- with gr.Column(scale=1):
370
- keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
371
-
372
- gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
373
- with gr.Row():
374
- with gr.Column(scale=1):
375
- with gr.Row():
376
- seed_number = gr.Number(42, label="Seed")
377
- cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
378
- with gr.Accordion("Controles Avançados de Timing e Performance", open=False):
379
- video_duration_slider = gr.Slider(label="Duração da Cena (segundos)", minimum=2.0, maximum=10.0, value=VIDEO_DURATION_SECONDS_DEFAULT, step=0.5)
380
- video_fps_slider = gr.Slider(label="FPS do Vídeo", minimum=12, maximum=30, value=VIDEO_FPS_DEFAULT, step=1)
381
- num_inference_steps_slider = gr.Slider(label="Etapas de Inferência", minimum=10, maximum=50, value=30, step=1)
382
- handoff_point_slider = gr.Slider(label="Ponto de Handoff (Frames)", minimum=30, maximum=300, value=150, step=1, info="Define o corte do vídeo para a montagem final.")
383
- slicing_checkbox = gr.Checkbox(label="Usar Attention Slicing (Economiza VRAM)", value=True)
384
- gr.Markdown("---"); gr.Markdown("#### Controles de Condicionamento")
385
- mid_cond_strength_slider = gr.Slider(label="Força do 'Caminho'", minimum=0.1, maximum=1.0, value=0.5, step=0.05)
386
- end_cond_offset_slider = gr.Slider(label="Offset do 'Destino' (frames do fim)", minimum=1, maximum=48, value=8, step=1, info="Define quão cedo o vídeo converge para o destino e qual frame será o 'Eco Fantasma'.")
387
- end_cond_strength_slider = gr.Slider(label="Força do 'Destino'", minimum=0.1, maximum=1.0, value=1.0, step=0.05)
388
- gr.Markdown(
389
- """
390
- **Instruções (Lógica 'Eco Fantasma'):**
391
- - O `Eco Fantasma` (a memória do futuro) é extraído do último frame do vídeo *completo*, antes do corte.
392
- - Este `Eco` se torna o ponto de partida para o próximo fragmento, garantindo máxima continuidade.
393
- - O `Ponto de Handoff` define o frame de corte para a montagem e onde o `Keyframe` seguinte ('Caminho') será posicionado no tempo.
394
- """
395
- )
396
- animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
397
- production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=15, interactive=False)
398
- with gr.Column(scale=1):
399
- video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
400
-
401
- gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (IA Editor)")
402
- editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
403
- final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
404
-
405
- # --- Event Handlers ---
406
- director_button.click(fn=run_storyboard_generation, inputs=[num_fragments_input, prompt_input, image_input], outputs=[scene_storyboard_state]).success(fn=lambda s, p: (s, p), inputs=[scene_storyboard_state, prompt_input], outputs=[storyboard_to_show, prompt_geral_state]).success(fn=process_image_to_square, inputs=[image_input], outputs=[processed_ref_path_state]).success(fn=lambda p: p, inputs=[processed_ref_path_state], outputs=[ref1_image])
407
-
408
- photographer_button_inputs = [scene_storyboard_state, ref1_image, ref1_task]
409
- for i in range(MAX_ADDITIONAL_REFS):
410
- photographer_button_inputs.append(additional_ref_images[i])
411
- photographer_button_inputs.append(additional_ref_tasks[i])
412
- photographer_button.click(fn=run_keyframe_generation, inputs=photographer_button_inputs, outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state])
413
-
414
- animator_button_inputs = [prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider,
415
- video_duration_slider, video_fps_slider, num_inference_steps_slider, handoff_point_slider, slicing_checkbox,
416
- mid_cond_strength_slider, end_cond_offset_slider, end_cond_strength_slider]
417
- animator_button_outputs = [production_log_output, video_gallery_glitch, fragment_list_state]
418
- animator_button.click(fn=run_video_production, inputs=animator_button_inputs, outputs=animator_button_outputs)
419
-
420
- editor_button.click(fn=concatenate_and_trim_masterpiece, inputs=[fragment_list_state], outputs=[final_video_output])
421
-
422
- if __name__ == "__main__":
423
- demo.queue().launch(server_name="0.0.0.0", share=True)