Carlexx commited on
Commit
ad91dba
·
verified ·
1 Parent(s): 6cc8fcd

Upload ai_studio_code (41).py

Browse files
Files changed (1) hide show
  1. ai_studio_code (41).py +612 -0
ai_studio_code (41).py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-4.2: O Piloto de Testes - Correção Final e Documentação de Bordo) ---
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
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_cpu_init"
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
+ VIDEO_FPS = 36
60
+ VIDEO_DURATION_SECONDS = 4
61
+ VIDEO_TOTAL_FRAMES = VIDEO_DURATION_SECONDS * VIDEO_FPS
62
+ CONVERGENCE_FRAMES = 8
63
+ TARGET_RESOLUTION = 720
64
+ MAX_REFS = 4
65
+
66
+ print("Baixando e criando pipelines LTX na CPU...")
67
+ 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)
68
+ pipeline_instance = create_ltx_video_pipeline(
69
+ ckpt_path=distilled_model_actual_path,
70
+ precision=PIPELINE_CONFIG_YAML["precision"],
71
+ text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
72
+ sampler=PIPELINE_CONFIG_YAML["sampler"],
73
+ device='cpu'
74
+ )
75
+ print("Modelos LTX prontos (na CPU).")
76
+
77
+
78
+ # --- Ato 3: As Partituras dos Músicos (Funções Corrigidas e Documentadas) ---
79
+
80
+ ####
81
+ # Carrega uma mídia (imagem ou vídeo) e a converte em um tensor Pytorch.
82
+ # Esta função prepara as imagens de condicionamento (início e fim) para o pipeline LTX.
83
+ # Se a entrada for um vídeo, extrai e usa apenas o seu primeiro frame.
84
+ ####
85
+ def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
86
+ if not media_path: raise ValueError("Caminho da mídia de condicionamento não pode ser nulo.")
87
+ lower_path = media_path.lower()
88
+ if lower_path.endswith(('.png', '.jpg', '.jpeg')):
89
+ return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
90
+ elif lower_path.endswith('.mp4'):
91
+ try:
92
+ with imageio.get_reader(media_path) as reader:
93
+ first_frame = reader.get_data(0)
94
+ image = Image.fromarray(first_frame).convert("RGB")
95
+ return load_image_to_tensor_with_resize_and_crop(image, height, width)
96
+ except Exception as e:
97
+ raise gr.Error(f"Falha ao ler o primeiro frame do vídeo '{media_path}': {e}")
98
+ else:
99
+ raise gr.Error(f"Formato de arquivo de condicionamento não suportado: {media_path}")
100
+
101
+ ####
102
+ # Executa o pipeline LTX para gerar um único fragmento de vídeo.
103
+ # Atua como a "Câmera" do sistema. Recebe um ponto de partida e um ponto de
104
+ # chegada (em `conditioning_items_data`), uma instrução de movimento (`motion_prompt`),
105
+ # e renderiza o clipe de vídeo correspondente. Gerencia o uso da GPU.
106
+ ####
107
+ def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg, progress=gr.Progress()):
108
+ progress(0, desc=f"[TECPIX 5000] Filmando Cena {current_fragment_index}...");
109
+ output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}.mp4"); target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
110
+ try:
111
+ pipeline_instance.to(target_device)
112
+ conditioning_items = []
113
+ for (path, start_frame, strength) in conditioning_items_data:
114
+ tensor = load_conditioning_tensor(path, height, width)
115
+ conditioning_items.append(ConditioningItem(tensor.to(target_device), start_frame, strength))
116
+
117
+ n_val = round((float(VIDEO_TOTAL_FRAMES) - 1.0) / 8.0); actual_num_frames = int(n_val * 8 + 1)
118
+ padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
119
+ padding_vals = calculate_padding(height, width, padded_h, padded_w)
120
+ for cond_item in conditioning_items: cond_item.media_item = torch.nn.functional.pad(cond_item.media_item, padding_vals)
121
+ kwargs = {"prompt": motion_prompt, "negative_prompt": "blurry, distorted, bad quality, artifacts", "height": padded_h, "width": padded_w, "num_frames": actual_num_frames, "frame_rate": VIDEO_FPS, "generator": torch.Generator(device=target_device).manual_seed(int(seed) + current_fragment_index), "output_type": "pt", "guidance_scale": float(cfg), "timesteps": PIPELINE_CONFIG_YAML.get("first_pass", {}).get("timesteps"), "conditioning_items": conditioning_items, "decode_timestep": PIPELINE_CONFIG_YAML.get("decode_timestep"), "decode_noise_scale": PIPELINE_CONFIG_YAML.get("decode_noise_scale"), "stochastic_sampling": PIPELINE_CONFIG_YAML.get("stochastic_sampling"), "image_cond_noise_scale": 0.15, "is_video": True, "vae_per_channel_normalize": True, "mixed_precision": (PIPELINE_CONFIG_YAML.get("precision") == "mixed_precision"), "offload_to_cpu": False, "enhance_prompt": False}
122
+ result_tensor = pipeline_instance(**kwargs).images
123
+ 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
124
+ cropped_tensor = result_tensor[:, :, :VIDEO_TOTAL_FRAMES, pad_t:slice_h, pad_l:slice_w]; video_np = (cropped_tensor[0].permute(1, 2, 3, 0).cpu().float().numpy() * 255).astype(np.uint8)
125
+ with imageio.get_writer(output_path, fps=VIDEO_FPS, codec='libx264', quality=8) as writer:
126
+ for i, frame in enumerate(video_np): progress(i / len(video_np), desc=f"Renderizando frame {i+1}/{len(video_np)}..."); writer.append_data(frame)
127
+ return output_path
128
+ finally:
129
+ pipeline_instance.to('cpu'); gc.collect()
130
+ if torch.cuda.is_available(): torch.cuda.empty_cache()
131
+
132
+ ####
133
+ # Processa a imagem de referência inicial do usuário, tornando-a quadrada.
134
+ # Garante que a imagem de referência principal tenha as dimensões corretas
135
+ # (ex: 720x720) antes de ser usada no pipeline, evitando distorções.
136
+ ####
137
+ def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
138
+ if not image_path or not os.path.exists(image_path): return None
139
+ try:
140
+ img = Image.open(image_path).convert("RGB")
141
+ img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
142
+ output_filename = f"initial_ref_{size}x{size}.png"
143
+ output_path = os.path.join(WORKSPACE_DIR, output_filename)
144
+ img_square.save(output_path)
145
+ return output_path
146
+ except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
147
+
148
+ ####
149
+ # Gera o roteiro de cenas estáticas (storyboard) usando Gemini.
150
+ # Atua como o "Sonhador" ou "Fotógrafo". Analisa a ideia geral do usuário
151
+ # e a imagem de referência para criar uma sequência de descrições de cenas.
152
+ ####
153
+ def get_static_scenes_storyboard(num_fragments: int, prompt: str, initial_image_path: str):
154
+ if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
155
+ if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
156
+ genai.configure(api_key=GEMINI_API_KEY)
157
+ prompt_file = "prompts/photographer_prompt.txt"
158
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
159
+ director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments))
160
+ model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(initial_image_path)
161
+ response = model.generate_content([director_prompt, img])
162
+ try:
163
+ cleaned_response = response.text.strip().replace("```json", "").replace("```", "")
164
+ storyboard_data = json.loads(cleaned_response)
165
+ return storyboard_data.get("scene_storyboard", [])
166
+ except Exception as e: raise gr.Error(f"O Sonhador (Gemini) falhou ao criar o roteiro: {e}. Resposta: {response.text}")
167
+
168
+ ####
169
+ # Gera todas as imagens-chave (keyframes) para a história usando DreamO.
170
+ # Atua como o "Pintor". Itera sobre o roteiro e pinta uma imagem para cada cena.
171
+ # Opera de forma sequencial, usando o keyframe anterior como referência para o próximo.
172
+ ####
173
+ def run_keyframe_generation(storyboard, initial_ref_image_path, *reference_args):
174
+ if not storyboard:
175
+ raise gr.Error("Nenhum roteiro para gerar imagens-chave.")
176
+ if not initial_ref_image_path or not os.path.exists(initial_ref_image_path):
177
+ raise gr.Error("A imagem de referência principal é obrigat��ria para iniciar a pintura.")
178
+
179
+ num_total_refs = MAX_REFS + 1
180
+ ref_paths = list(reference_args[:num_total_refs])
181
+ ref_tasks = list(reference_args[num_total_refs:])
182
+
183
+ with Image.open(initial_ref_image_path) as img:
184
+ width, height = img.size
185
+ width, height = (width // 32) * 32, (height // 32) * 32
186
+
187
+ keyframe_paths = []
188
+ log_history = ""
189
+
190
+ try:
191
+ dreamo_generator_singleton.to_gpu()
192
+
193
+ log_history += f"Pintando Keyframe Inicial (Cena 1/{len(storyboard)})...\n"
194
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
195
+
196
+ references_for_first_frame = []
197
+ references_for_first_frame.append({'image_np': np.array(Image.open(initial_ref_image_path).convert("RGB")), 'task': 'ip'})
198
+ log_history += f" - Usando imagem de referência principal '{os.path.basename(initial_ref_image_path)}' (Tarefa: ip)\n"
199
+
200
+ for j in range(1, num_total_refs):
201
+ aux_path, aux_task = ref_paths[j], ref_tasks[j]
202
+ if aux_path and os.path.exists(aux_path):
203
+ references_for_first_frame.append({'image_np': np.array(Image.open(aux_path).convert("RGB")), 'task': aux_task})
204
+ log_history += f" - Usando ref. auxiliar: {os.path.basename(aux_path)} (Tarefa: {aux_task})\n"
205
+
206
+ first_prompt = storyboard[0]
207
+ output_path = os.path.join(WORKSPACE_DIR, "keyframe_1.png")
208
+ image = dreamo_generator_singleton.generate_image_with_gpu_management(
209
+ reference_items=references_for_first_frame, prompt=first_prompt, width=width, height=height
210
+ )
211
+ image.save(output_path)
212
+ keyframe_paths.append(output_path)
213
+ current_ref_image_path = output_path
214
+
215
+ for i, prompt in enumerate(storyboard[1:], start=1):
216
+ log_history += f"\nPintando Cena Sequencial {i+1}/{len(storyboard)}...\n"
217
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
218
+
219
+ reference_items_for_dreamo = []
220
+ sequential_ref_task = ref_tasks[0]
221
+ reference_items_for_dreamo.append({'image_np': np.array(Image.open(current_ref_image_path).convert("RGB")), 'task': sequential_ref_task})
222
+ log_history += f" - Usando ref. sequencial: {os.path.basename(current_ref_image_path)} (Tarefa: {sequential_ref_task})\n"
223
+
224
+ for j in range(1, num_total_refs):
225
+ aux_path, aux_task = ref_paths[j], ref_tasks[j]
226
+ if aux_path and os.path.exists(aux_path):
227
+ reference_items_for_dreamo.append({'image_np': np.array(Image.open(aux_path).convert("RGB")), 'task': aux_task})
228
+ log_history += f" - Usando ref. auxiliar: {os.path.basename(aux_path)} (Tarefa: {aux_task})\n"
229
+
230
+ output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
231
+ image = dreamo_generator_singleton.generate_image_with_gpu_management(
232
+ reference_items=reference_items_for_dreamo, prompt=prompt, width=width, height=height
233
+ )
234
+ image.save(output_path)
235
+ keyframe_paths.append(output_path)
236
+ current_ref_image_path = output_path
237
+
238
+ except Exception as e:
239
+ raise gr.Error(f"O Pintor (DreamO) encontrou um erro: {e}")
240
+ finally:
241
+ dreamo_generator_singleton.to_cpu()
242
+
243
+ log_history += "\nPintura de todos os keyframes concluída.\n"
244
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths), keyframe_images_state: keyframe_paths}
245
+
246
+ ####
247
+ # Gera um único prompt de movimento para uma transição, usando Gemini.
248
+ # Atua como a "consciência" do Cineasta. Analisa uma mídia de partida e uma
249
+ # imagem de chegada para descrever como a câmera deve se mover.
250
+ # Usa uma lógica bifocal e espera ativa para robustez.
251
+ ####
252
+ def get_single_motion_prompt(user_prompt: str, story_history: str, start_media_path: str, end_keyframe_path: str, prompt_filename: str):
253
+ if not GEMINI_API_KEY:
254
+ raise gr.Error("Chave da API Gemini não configurada!")
255
+
256
+ uploaded_file = None
257
+ try:
258
+ genai.configure(api_key=GEMINI_API_KEY)
259
+ model = genai.GenerativeModel('gemini-1.5-flash')
260
+
261
+ print(f"Cineasta: Fazendo upload do arquivo de contexto '{start_media_path}'...")
262
+ file_to_upload = genai.upload_file(start_media_path)
263
+
264
+ print(f"Cineasta: Aguardando arquivo '{file_to_upload.name}' ficar ATIVO...")
265
+ timeout_seconds = 180
266
+ start_time = time.time()
267
+
268
+ while file_to_upload.state.name == "PROCESSING":
269
+ if time.time() - start_time > timeout_seconds:
270
+ genai.delete_file(name=file_to_upload.name)
271
+ raise TimeoutError(f"Tempo de espera para o processamento do arquivo '{file_to_upload.name}' excedido.")
272
+
273
+ time.sleep(5)
274
+ file_to_upload = genai.get_file(name=file_to_upload.name)
275
+
276
+ if file_to_upload.state.name != "ACTIVE":
277
+ raise gr.Error(f"O arquivo de mídia '{file_to_upload.name}' não pôde ser processado. Estado final: {file_to_upload.state.name}")
278
+
279
+ print(f"Cineasta: Arquivo '{file_to_upload.name}' está ATIVO. Gerando prompt...")
280
+ uploaded_file = file_to_upload
281
+
282
+ end_media = Image.open(end_keyframe_path)
283
+
284
+ prompt_file_path = os.path.join(os.path.dirname(__file__), "prompts", prompt_filename)
285
+ with open(prompt_file_path, "r", encoding="utf-8") as f:
286
+ template = f.read()
287
+
288
+ director_prompt = template.format(user_prompt=user_prompt, story_history=story_history)
289
+
290
+ model_contents = [director_prompt, uploaded_file, end_media]
291
+ response = model.generate_content(model_contents)
292
+
293
+ cleaned_text = response.text.strip()
294
+ if cleaned_text.startswith("```json"):
295
+ cleaned_text = cleaned_text[len("```json"):].strip()
296
+ if cleaned_text.endswith("```"):
297
+ cleaned_text = cleaned_text[:-len("```")].strip()
298
+
299
+ try:
300
+ motion_data = json.loads(cleaned_text)
301
+ final_prompt = motion_data.get("motion_prompt", "")
302
+ if not final_prompt:
303
+ raise ValueError("Prompt de movimento vazio no JSON.")
304
+ return final_prompt
305
+ except (json.JSONDecodeError, ValueError):
306
+ return cleaned_text.replace("\"", "").replace("{", "").replace("}", "").replace("motion_prompt:", "").strip()
307
+
308
+ except Exception as e:
309
+ response_text = getattr(e, 'text', 'Nenhuma resposta de texto disponível.')
310
+ raise gr.Error(f"O Cineasta (Gemini) falhou ao criar o prompt de movimento: {e}. Resposta: {response_text}")
311
+
312
+ finally:
313
+ if uploaded_file:
314
+ try:
315
+ genai.delete_file(uploaded_file.name)
316
+ except Exception as delete_e:
317
+ print(f"Aviso: Falha ao deletar o arquivo temporário {uploaded_file.name} da API Gemini. Erro: {delete_e}")
318
+
319
+ ####
320
+ # Orquestra a produção de todos os fragmentos de vídeo.
321
+ # Implementa a lógica central da arquitetura ADUC-SDR para a geração de vídeo:
322
+ # 1. Fragmento 1: Gerado a partir da transição do Keyframe 1 para o Keyframe 2.
323
+ # 2. Fragmentos Subsequentes: Gerados a partir do "eco" do vídeo anterior para o
324
+ # próximo keyframe na sequência.
325
+ ####
326
+ def run_video_production(prompt_geral, keyframe_image_paths, scene_storyboard, seed, cfg, progress=gr.Progress()):
327
+ if not keyframe_image_paths or len(keyframe_image_paths) < 2:
328
+ raise gr.Error("Pinte pelo menos 2 keyframes na Etapa 2 para produzir as transições.")
329
+
330
+ log_history = "\n--- FASE 3/4: A Câmera e o Cineasta estão filmando em sequência just-in-time...\n"
331
+ yield {production_log_output: log_history, video_gallery_glitch: []}
332
+
333
+ video_fragments = []
334
+
335
+ previous_media_path = keyframe_image_paths[0]
336
+
337
+ story_history = ""
338
+ with Image.open(keyframe_image_paths[0]) as img:
339
+ width, height = img.size
340
+
341
+ num_transitions = len(keyframe_image_paths) - 1
342
+ for i in range(num_transitions):
343
+ start_media_path = previous_media_path
344
+ end_keyframe_path = keyframe_image_paths[i+1]
345
+
346
+ is_first_fragment = (i == 0)
347
+
348
+ fragment_num = i + 1
349
+ progress(i / num_transitions, desc=f"Planejando e Filmando Fragmento {fragment_num}/{num_transitions}")
350
+
351
+ log_history += f"\n--- FRAGMENTO {fragment_num} ---\n"
352
+ log_history += "Cineasta (Gemini) está analisando a cena anterior e a próxima...\n"
353
+ yield {production_log_output: log_history}
354
+
355
+ if is_first_fragment:
356
+ prompt_filename_to_use = "director_motion_prompt.txt"
357
+ story_history = f"A história começa com a transição da cena '{scene_storyboard[0]}' para '{scene_storyboard[1]}'."
358
+ else:
359
+ prompt_filename_to_use = "director_motion_prompt_transition.txt"
360
+ story_history += f"\n- Em seguida, a cena muda de '{scene_storyboard[i]}' para '{scene_storyboard[i+1]}'."
361
+
362
+ current_motion_prompt = get_single_motion_prompt(prompt_geral, story_history, start_media_path, end_keyframe_path, prompt_filename_to_use)
363
+
364
+ log_history += f"Instrução do Cineasta ({prompt_filename_to_use}): '{current_motion_prompt}'\n"
365
+ log_history += f"Filmando transição de '{os.path.basename(start_media_path)}' para '{os.path.basename(end_keyframe_path)}'...\n"
366
+ yield {production_log_output: log_history}
367
+
368
+ end_frame_index = VIDEO_TOTAL_FRAMES - CONVERGENCE_FRAMES
369
+ conditioning_items_data = [(start_media_path, 0, 1.0), (end_keyframe_path, end_frame_index, 1.0)]
370
+
371
+ fragment_path = run_ltx_animation(fragment_num, current_motion_prompt, conditioning_items_data, width, height, seed, cfg, progress)
372
+ video_fragments.append(fragment_path)
373
+
374
+ log_history += f"Fragmento {fragment_num} filmado. Extraindo memória física para a próxima cena...\n"
375
+ yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
376
+
377
+ previous_media_path = extract_final_frames_video(fragment_path, fragment_num, CONVERGENCE_FRAMES)
378
+
379
+ log_history += "\nFilmagem de todos os fragmentos de transição concluída.\n"
380
+ progress(1.0, desc="Produção Concluída.")
381
+ yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
382
+
383
+ ####
384
+ # Extrai os últimos N frames de um vídeo para criar o "clipe de convergência" ou "eco".
385
+ # Esta é a etapa de "Destilação" da arquitetura ADUC-SDR. O clipe gerado
386
+ # serve como o ponto de partida (Contexto Causal) para a próxima animação.
387
+ # O comando FFmpeg é robustecido para garantir compatibilidade com a API do Google.
388
+ ####
389
+ def extract_final_frames_video(input_video_path: str, fragment_index: int, num_frames: int):
390
+ output_video_path = os.path.join(WORKSPACE_DIR, f"convergence_clip_{fragment_index}.mp4")
391
+ if not os.path.exists(input_video_path): raise gr.Error(f"Erro Interno: Vídeo de entrada para extração não encontrado: {input_video_path}")
392
+ try:
393
+ command_probe = f"ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=noprint_wrappers=1:nokey=1 \"{input_video_path}\""
394
+ result_probe = subprocess.run(command_probe, shell=True, check=True, capture_output=True, text=True); total_frames = int(result_probe.stdout.strip())
395
+ start_frame_index = total_frames - num_frames
396
+ if start_frame_index < 0:
397
+ shutil.copyfile(input_video_path, output_video_path); return output_video_path
398
+
399
+ command_extract = (
400
+ f"ffmpeg -y -v error -i \"{input_video_path}\" "
401
+ f"-vf \"select='gte(n,{start_frame_index})'\" "
402
+ f"-c:v libx264 -profile:v baseline -level 3.0 -pix_fmt yuv420p "
403
+ f"-an \"{output_video_path}\""
404
+ )
405
+
406
+ subprocess.run(command_extract, shell=True, check=True, capture_output=True, text=True); return output_video_path
407
+ except (subprocess.CalledProcessError, ValueError) as e:
408
+ error_message = f"Editor Mágico (FFmpeg) falhou ao extrair o clipe de convergência: {e}"
409
+ if hasattr(e, 'stderr'): error_message += f"\nDetalhes: {e.stderr}"
410
+ raise gr.Error(error_message)
411
+
412
+ ####
413
+ # Realiza a pós-produção, unindo todos os fragmentos de vídeo em uma obra final.
414
+ # Atua como o "Editor". Remove a sobreposição de "eco" entre os clipes e os concatena.
415
+ ####
416
+ def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
417
+ if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
418
+ progress(0.2, desc="Aparando fragmentos para transições suaves...");
419
+ trimmed_dir = os.path.join(WORKSPACE_DIR, "trimmed"); os.makedirs(trimmed_dir, exist_ok=True)
420
+ paths_for_concat = []
421
+ try:
422
+ for i, path in enumerate(fragment_paths):
423
+ if i == len(fragment_paths) - 1:
424
+ paths_for_concat.append(path)
425
+ continue
426
+
427
+ trimmed_path = os.path.join(trimmed_dir, f"fragment_{i}_trimmed.mp4")
428
+ probe_cmd = f"ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=noprint_wrappers=1:nokey=1 \"{path}\""
429
+ result = subprocess.run(probe_cmd, shell=True, check=True, capture_output=True, text=True)
430
+ total_frames = int(result.stdout.strip())
431
+ frames_to_keep = total_frames - CONVERGENCE_FRAMES
432
+ if frames_to_keep <= 0:
433
+ shutil.copyfile(path, trimmed_path)
434
+ paths_for_concat.append(trimmed_path)
435
+ continue
436
+
437
+ trim_cmd = f"ffmpeg -y -v error -i \"{path}\" -vf \"select='lt(n,{frames_to_keep})'\" -c:v libx264 -preset ultrafast -an \"{trimmed_path}\""
438
+ subprocess.run(trim_cmd, shell=True, check=True, capture_output=True, text=True)
439
+ paths_for_concat.append(trimmed_path)
440
+
441
+ progress(0.6, desc="Montando a obra-prima final...")
442
+ list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "obra_prima_final.mp4")
443
+ with open(list_file_path, "w") as f:
444
+ for p in paths_for_concat: f.write(f"file '{os.path.abspath(p)}'\n")
445
+ concat_cmd = f"ffmpeg -y -v error -f concat -safe 0 -i \"{list_file_path}\" -c copy \"{final_output_path}\""
446
+ subprocess.run(concat_cmd, shell=True, check=True, capture_output=True, text=True)
447
+ return final_output_path
448
+ except (subprocess.CalledProcessError, ValueError) as e:
449
+ error_message = f"FFmpeg falhou durante a pós-produção (corte e concatenação): {e}"
450
+ if hasattr(e, 'stderr'): error_message += f"\nDetalhes do erro do FFmpeg: {e.stderr}"
451
+ raise gr.Error(error_message)
452
+
453
+ # --- Ato 5: A Interface com o Mundo (A UI Restaurada e Aprimorada) ---
454
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
455
+ gr.Markdown("# NOVINHO-4.2 (Piloto de Testes - Arquitetura Estabilizada)\n*By Carlex & Gemini & DreamO*")
456
+
457
+ if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
458
+ os.makedirs(WORKSPACE_DIR)
459
+ Path("examples").mkdir(exist_ok=True)
460
+
461
+ scene_storyboard_state = gr.State([])
462
+ keyframe_images_state = gr.State([])
463
+ fragment_list_state = gr.State([])
464
+ prompt_geral_state = gr.State("")
465
+ processed_ref_path_state = gr.State("")
466
+ visible_references_state = gr.State(0)
467
+
468
+ # --- ETAPA 1: O ROTEIRO ---
469
+ gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (Sonhador)")
470
+ with gr.Row():
471
+ with gr.Column(scale=1):
472
+ prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
473
+ num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Cenas")
474
+ image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
475
+ director_button = gr.Button("▶️ 1. Gerar Roteiro de Cenas", variant="primary")
476
+ with gr.Column(scale=2):
477
+ storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado")
478
+
479
+ # --- ETAPA 2: OS KEYFRAMES ---
480
+ gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (Pintor)")
481
+ with gr.Row():
482
+ with gr.Column(scale=2):
483
+ gr.Markdown("### Controles do Pintor (DreamO)")
484
+ gr.Markdown("**Tarefas:** `style` (estilo), `ip` (conteúdo), `id` (identidade).")
485
+ ref_image_inputs, ref_task_inputs, aux_ref_rows = [], [], []
486
+ with gr.Group():
487
+ with gr.Row():
488
+ ref_image_inputs.append(gr.Image(label="Referência Sequencial (Automática)", type="filepath", interactive=False))
489
+ ref_task_inputs.append(gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa Seq."))
490
+ for i in range(MAX_REFS):
491
+ with gr.Row(visible=False) as ref_row_aux:
492
+ ref_image_inputs.append(gr.Image(label=f"Ref. Auxiliar {i+1}", type="filepath"))
493
+ ref_task_inputs.append(gr.Dropdown(choices=["ip", "id", "style"], value="ip", label=f"Tarefa Aux. {i+1}"))
494
+ aux_ref_rows.append(ref_row_aux)
495
+ with gr.Row():
496
+ add_ref_button = gr.Button("➕ Add Ref.")
497
+ remove_ref_button = gr.Button("➖ Rem. Ref.")
498
+ photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave", variant="primary")
499
+ with gr.Column(scale=1):
500
+ keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
501
+ keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
502
+
503
+ # --- ETAPA 3: A PRODUÇÃO ---
504
+ gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (Cineasta e Câmera)")
505
+ with gr.Row():
506
+ with gr.Column(scale=1):
507
+ with gr.Row():
508
+ seed_number = gr.Number(42, label="Seed")
509
+ cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
510
+ animator_button = gr.Button("▶️ 3. Produzir Cenas em Vídeo", variant="primary")
511
+ production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
512
+ with gr.Column(scale=1):
513
+ video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados (com sobreposição)", object_fit="contain", height="auto", type="video")
514
+
515
+ # --- ETAPA 4: PÓS-PRODUÇÃO ---
516
+ gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
517
+ editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
518
+ final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
519
+
520
+ # --- Rodapé Filosófico ---
521
+ gr.Markdown(
522
+ """
523
+ ---
524
+ ### A Arquitetura ADUC-SDR: O Esquema Matemático
525
+ A geração de vídeo é governada por uma função seccional que define como cada fragmento (`V_i`) é criado. A fórmula muda dependendo se estamos no **"Gênesis"** da história ou na **"Cadeia Causal"** que se segue.
526
+
527
+ ---
528
+ #### **FÓRMULA 1: O FRAGMENTO INICIAL (Gênesis, `i=1`)**
529
+ *Define a criação do primeiro clipe a partir de imagens estáticas.*
530
+
531
+ **Ato 1: Planejamento Inicial (`P_1`)**
532
+ `P_1 = Γ_initial( K_1, K_2, P_geral )`
533
+
534
+ **Ato 2: Execução Inicial (`V_1`)**
535
+ `V_1 = Ψ( { (K_1, F_start), (K_2, F_end) }, P_1 )`
536
+
537
+ ---
538
+ #### **FÓRMULA 2: A CADEIA CAUSAL (Momentum, `i > 1`)**
539
+ *Define a criação dos fragmentos subsequentes, garantindo a continuidade através do "eco".*
540
+
541
+ **Ato 0: Destilação do Eco (`C_(i-1)`)**
542
+ `C_(i-1) = Δ(V_(i-1))`
543
+
544
+ **Ato 1: Planejamento de Continuidade (`P_i`)**
545
+ `P_i = Γ_transition( C_(i-1), K_(i+1), P_geral, H_(i-1) )`
546
+
547
+ **Ato 2: Execução Causal (`V_i`)**
548
+ `V_i = Ψ( { (C_(i-1), F_start), (K_(i+1), F_end) }, P_i )`
549
+
550
+ ---
551
+ #### **Componentes (O Léxico da Arquitetura):**
552
+ - **`V_i`**: Fragmento de Vídeo
553
+ - **`K_i`**: Keyframe (Imagem Estática)
554
+ - **`C_i`**: "Eco" Causal (Clipe de Vídeo)
555
+ - **`P_i`**: Prompt de Movimento
556
+ - **`P_geral`**: Prompt Geral (Intenção do Diretor)
557
+ - **`H_i`**: Histórico Narrativo
558
+ - **`Γ`**: Cineasta (Gerador de Prompt)
559
+ - **`Ψ`**: Câmera (Gerador de Vídeo)
560
+ - **`Δ`**: Editor (Extrator de "Eco")
561
+ - **`F_start`, `F_end`**: Constantes de Frame (Âncoras Temporais)
562
+ """
563
+ )
564
+
565
+
566
+ # --- Ato 6: A Regência (Lógica de Conexão dos Botões) ---
567
+ def update_reference_visibility(current_count, action):
568
+ if action == "add": new_count = min(MAX_REFS, current_count + 1)
569
+ else: new_count = max(0, current_count - 1)
570
+ return [new_count] + [gr.update(visible=(i < new_count)) for i in range(MAX_REFS)]
571
+
572
+ add_ref_button.click(fn=update_reference_visibility, inputs=[visible_references_state, gr.State("add")], outputs=[visible_references_state] + aux_ref_rows)
573
+ remove_ref_button.click(fn=update_reference_visibility, inputs=[visible_references_state, gr.State("remove")], outputs=[visible_references_state] + aux_ref_rows)
574
+
575
+ director_button.click(
576
+ fn=get_static_scenes_storyboard,
577
+ inputs=[num_fragments_input, prompt_input, image_input],
578
+ outputs=[scene_storyboard_state]
579
+ ).success(
580
+ fn=lambda s, p: (s, p),
581
+ inputs=[scene_storyboard_state, prompt_input],
582
+ outputs=[storyboard_to_show, prompt_geral_state]
583
+ ).success(
584
+ fn=process_image_to_square,
585
+ inputs=[image_input],
586
+ outputs=[processed_ref_path_state]
587
+ ).success(
588
+ fn=lambda p: p,
589
+ inputs=[processed_ref_path_state],
590
+ outputs=[ref_image_inputs[0]]
591
+ )
592
+
593
+ photographer_button.click(
594
+ fn=run_keyframe_generation,
595
+ inputs=[scene_storyboard_state, processed_ref_path_state] + ref_image_inputs + ref_task_inputs,
596
+ outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
597
+ )
598
+
599
+ animator_button.click(
600
+ fn=run_video_production,
601
+ inputs=[prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider],
602
+ outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
603
+ )
604
+
605
+ editor_button.click(
606
+ fn=concatenate_and_trim_masterpiece,
607
+ inputs=[fragment_list_state],
608
+ outputs=[final_video_output]
609
+ )
610
+
611
+ if __name__ == "__main__":
612
+ demo.queue().launch(server_name="0.0.0.0", share=True)