Carlexx commited on
Commit
6a8044d
·
verified ·
1 Parent(s): 15ed66d

Upload ai_studio_code (97).py

Browse files
Files changed (1) hide show
  1. ai_studio_code (97).py +540 -0
ai_studio_code (97).py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_gpu.py (NOVINHO-6.1: Eco + Déjà Vu para HF Spaces) ---
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
+ import spaces # Importação para o decorador de GPU do Hugging Face Spaces
46
+
47
+ from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
48
+ from dreamo_helpers import dreamo_generator_singleton
49
+
50
+ # --- Ato 2: A Preparação do Palco (Configurações) ---
51
+ config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
52
+ with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
53
+
54
+ LTX_REPO = "Lightricks/LTX-Video"
55
+ models_dir = "downloaded_models_gradio"
56
+ Path(models_dir).mkdir(parents=True, exist_ok=True)
57
+ WORKSPACE_DIR = "aduc_workspace"
58
+ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
59
+
60
+ VIDEO_FPS = 24
61
+ TARGET_RESOLUTION = 420
62
+
63
+ print("Criando pipelines LTX na CPU (estado de repouso)...")
64
+ 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)
65
+ pipeline_instance = create_ltx_video_pipeline(
66
+ ckpt_path=distilled_model_actual_path,
67
+ precision=PIPELINE_CONFIG_YAML["precision"],
68
+ text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
69
+ sampler=PIPELINE_CONFIG_YAML["sampler"],
70
+ device='cpu' # Os modelos iniciam na CPU para economizar recursos
71
+ )
72
+ print("Modelos LTX prontos (na CPU).")
73
+
74
+
75
+ # --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
76
+
77
+ def robust_json_parser(raw_text: str) -> dict:
78
+ try:
79
+ start_index = raw_text.find('{'); end_index = raw_text.rfind('}')
80
+ if start_index != -1 and end_index != -1 and end_index > start_index:
81
+ json_str = raw_text[start_index : end_index + 1]; return json.loads(json_str)
82
+ else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
83
+ except json.JSONDecodeError as e: raise ValueError(f"Falha ao decodificar JSON: {e}")
84
+
85
+ def extract_image_exif(image_path: str) -> str:
86
+ try:
87
+ img = Image.open(image_path); exif_data = img._getexif()
88
+ if not exif_data: return "No EXIF metadata found."
89
+ exif = { ExifTags.TAGS[k]: v for k, v in exif_data.items() if k in ExifTags.TAGS }
90
+ relevant_tags = ['DateTimeOriginal', 'Model', 'LensModel', 'FNumber', 'ExposureTime', 'ISOSpeedRatings', 'FocalLength']
91
+ metadata_str = ", ".join(f"{key}: {exif[key]}" for key in relevant_tags if key in exif)
92
+ return metadata_str if metadata_str else "No relevant EXIF metadata found."
93
+ except Exception: return "Could not read EXIF data."
94
+
95
+ def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
96
+ if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
97
+ if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
98
+ exif_metadata = extract_image_exif(initial_image_path)
99
+ prompt_file = "prompts/unified_storyboard_prompt.txt"
100
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
101
+ director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata=exif_metadata)
102
+ genai.configure(api_key=GEMINI_API_KEY)
103
+ model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(initial_image_path)
104
+ print("Gerando roteiro com análise de visão integrada...")
105
+ response = model.generate_content([director_prompt, img])
106
+ try:
107
+ storyboard_data = robust_json_parser(response.text)
108
+ storyboard = storyboard_data.get("scene_storyboard", [])
109
+ 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)}")
110
+ return storyboard
111
+ except Exception as e: raise gr.Error(f"O Roteirista (Gemini) falhou ao criar o roteiro: {e}. Resposta recebida: {response.text}")
112
+
113
+ def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
114
+ genai.configure(api_key=GEMINI_API_KEY)
115
+ prompt_file = "prompts/img2img_evolution_prompt.txt"
116
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
117
+ director_prompt = template.format(target_scene_description=target_scene_description)
118
+ model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(previous_image_path)
119
+ response = model.generate_content([director_prompt, "Previous Image:", img])
120
+ return response.text.strip().replace("\"", "")
121
+
122
+ @spaces.GPU(duration=180) # Ativa a GPU para esta função com timeout de 3 minutos
123
+ def run_keyframe_generation(storyboard, ref_images_tasks, progress=gr.Progress()):
124
+ if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
125
+ initial_ref_image_path = ref_images_tasks[0]['image']
126
+ if not initial_ref_image_path or not os.path.exists(initial_ref_image_path): raise gr.Error("A imagem de referência principal (à esquerda) é obrigatória.")
127
+ log_history = ""; generated_images_for_gallery = []
128
+ try:
129
+ dreamo_generator_singleton.to_gpu() # Move o modelo para a GPU ativada
130
+ with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
131
+ keyframe_paths, current_ref_image_path = [initial_ref_image_path], initial_ref_image_path
132
+ for i, scene_description in enumerate(storyboard):
133
+ progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
134
+ log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
135
+ dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
136
+ reference_items = []
137
+ fixed_references_basenames = [os.path.basename(item['image']) for item in ref_images_tasks if item['image']]
138
+ for item in ref_images_tasks:
139
+ if item['image']:
140
+ reference_items.append({'image_np': np.array(Image.open(item['image']).convert("RGB")), 'task': item['task']})
141
+ dynamic_references_paths = keyframe_paths[-3:]
142
+ for ref_path in dynamic_references_paths:
143
+ if os.path.basename(ref_path) not in fixed_references_basenames:
144
+ reference_items.append({'image_np': np.array(Image.open(ref_path).convert("RGB")), 'task': 'ip'})
145
+ log_history += f" - Roteiro: '{scene_description}'\n - Usando {len(reference_items)} referências visuais.\n - Prompt do D.A.: \"{dreamo_prompt}\"\n"
146
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
147
+ output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
148
+ image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=reference_items, prompt=dreamo_prompt, width=width, height=height)
149
+ image.save(output_path)
150
+ keyframe_paths.append(output_path); generated_images_for_gallery.append(output_path); current_ref_image_path = output_path
151
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
152
+ except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
153
+ finally:
154
+ dreamo_generator_singleton.to_cpu() # Libera a VRAM da GPU
155
+ gc.collect()
156
+ torch.cuda.empty_cache()
157
+ log_history += "\nPintura de todos os keyframes concluída.\n"
158
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery), keyframe_images_state: keyframe_paths}
159
+
160
+ def get_initial_motion_prompt(user_prompt: str, start_image_path: str, destination_image_path: str, dest_scene_desc: str):
161
+ if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
162
+ try:
163
+ genai.configure(api_key=GEMINI_API_KEY); model = genai.GenerativeModel('gemini-1.5-flash'); prompt_file = "prompts/initial_motion_prompt.txt"
164
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
165
+ cinematographer_prompt = template.format(user_prompt=user_prompt, destination_scene_description=dest_scene_desc)
166
+ start_img, dest_img = Image.open(start_image_path), Image.open(destination_image_path)
167
+ model_contents = ["START Image:", start_img, "DESTINATION Image:", dest_img, cinematographer_prompt]
168
+ response = model.generate_content(model_contents)
169
+ return response.text.strip()
170
+ except Exception as e: raise gr.Error(f"O Cineasta de IA (Inicial) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
171
+
172
+ def get_dynamic_motion_prompt(user_prompt, story_history, memory_media_path, path_image_path, destination_image_path, path_scene_desc, dest_scene_desc):
173
+ if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
174
+ try:
175
+ genai.configure(api_key=GEMINI_API_KEY); model = genai.GenerativeModel('gemini-1.5-flash'); prompt_file = "prompts/dynamic_motion_prompt.txt"
176
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
177
+ cinematographer_prompt = template.format(user_prompt=user_prompt, story_history=story_history, midpoint_scene_description=path_scene_desc, destination_scene_description=dest_scene_desc)
178
+
179
+ with imageio.get_reader(memory_media_path) as reader:
180
+ mem_img = Image.fromarray(reader.get_data(0))
181
+
182
+ path_img, dest_img = Image.open(path_image_path), Image.open(destination_image_path)
183
+ model_contents = ["START Image (from Kinetic Echo):", mem_img, "MIDPOINT Image (Path):", path_img, "DESTINATION Image (Destination):", dest_img, cinematographer_prompt]
184
+ response = model.generate_content(model_contents)
185
+ return response.text.strip()
186
+ except Exception as e: raise gr.Error(f"O Cineasta de IA (Dinâmico) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
187
+
188
+ @spaces.GPU(duration=360) # Ativa a GPU com timeout de 6 minutos para a geração de vídeo
189
+ def run_video_production(
190
+ video_duration_seconds, video_fps, eco_video_frames, use_attention_slicing,
191
+ fragment_duration_frames, mid_cond_strength, num_inference_steps,
192
+ prompt_geral, keyframe_images_state, scene_storyboard, cfg,
193
+ progress=gr.Progress()
194
+ ):
195
+ video_total_frames = int(video_duration_seconds * video_fps)
196
+ if not keyframe_images_state or len(keyframe_images_state) < 3: raise gr.Error("Pinte pelo menos 2 keyframes para produzir uma transição.")
197
+ if int(fragment_duration_frames) > video_total_frames:
198
+ raise gr.Error(f"A 'Duração de Cada Fragmento' ({fragment_duration_frames} frames) não pode ser maior que a 'Duração da Geração Bruta' ({video_total_frames} frames).")
199
+
200
+ log_history = "\n--- FASE 3/4: Iniciando Produção (Eco + Déjà Vu)...\n"
201
+ yield {
202
+ production_log_output: log_history,
203
+ video_gallery_glitch: [],
204
+ prod_media_start_output: gr.update(value=None),
205
+ prod_media_mid_output: gr.update(value=None, visible=False),
206
+ prod_media_end_output: gr.update(value=None),
207
+ }
208
+
209
+ seed = int(time.time())
210
+ target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
211
+ try:
212
+ pipeline_instance.to(target_device)
213
+ video_fragments, story_history = [], ""; kinetic_memory_path = None
214
+ with Image.open(keyframe_images_state[1]) as img: width, height = img.size
215
+
216
+ num_transitions = len(keyframe_images_state) - 2
217
+ for i in range(num_transitions):
218
+ fragment_num = i + 1
219
+ progress(i / num_transitions, desc=f"Preparando Fragmento {fragment_num}...")
220
+ log_history += f"\n--- FRAGMENTO {fragment_num}/{num_transitions} ---\n"
221
+
222
+ if i == 0:
223
+ start_path, destination_path = keyframe_images_state[1], keyframe_images_state[2]
224
+ dest_scene_desc = scene_storyboard[1]
225
+ log_history += f" - Início (Big Bang): {os.path.basename(start_path)}\n - Destino: {os.path.basename(destination_path)}\n"
226
+ current_motion_prompt = get_initial_motion_prompt(prompt_geral, start_path, destination_path, dest_scene_desc)
227
+ conditioning_items_data = [(start_path, 0, 1.0), (destination_path, int(video_total_frames), 1.0)]
228
+
229
+ yield {
230
+ production_log_output: gr.update(value=log_history),
231
+ prod_media_start_output: gr.update(value=start_path),
232
+ prod_media_mid_output: gr.update(value=None, visible=False),
233
+ prod_media_end_output: gr.update(value=destination_path),
234
+ }
235
+ else:
236
+ memory_path, path_path, destination_path = kinetic_memory_path, keyframe_images_state[i+1], keyframe_images_state[i+2]
237
+ path_scene_desc, dest_scene_desc = scene_storyboard[i], scene_storyboard[i+1]
238
+ log_history += f" - Memória Cinética (Vídeo): {os.path.basename(memory_path)}\n - Caminho: {os.path.basename(path_path)}\n - Destino: {os.path.basename(destination_path)}\n"
239
+
240
+ mid_cond_frame_calculated = int(video_total_frames - fragment_duration_frames + eco_video_frames)
241
+ log_history += f" - Frame de Condicionamento do 'Caminho' calculado: {mid_cond_frame_calculated}\n"
242
+
243
+ current_motion_prompt = get_dynamic_motion_prompt(prompt_geral, story_history, memory_path, path_path, destination_path, path_scene_desc, dest_scene_desc)
244
+ conditioning_items_data = [(memory_path, 0, 1.0), (path_path, mid_cond_frame_calculated, mid_cond_strength), (destination_path, int(video_total_frames), 1.0)]
245
+
246
+ yield {
247
+ production_log_output: gr.update(value=log_history),
248
+ prod_media_start_output: gr.update(value=memory_path),
249
+ prod_media_mid_output: gr.update(value=path_path, visible=True),
250
+ prod_media_end_output: gr.update(value=destination_path),
251
+ }
252
+
253
+ story_history += f"\n- Ato {fragment_num + 1}: {current_motion_prompt}"
254
+ log_history += f" - Instrução do Cineasta: '{current_motion_prompt}'\n"; yield {production_log_output: log_history}
255
+
256
+ progress(i / num_transitions, desc=f"Filmando Fragmento {fragment_num}...")
257
+ full_fragment_path, actual_frames_generated = run_ltx_animation(
258
+ current_fragment_index=fragment_num, motion_prompt=current_motion_prompt,
259
+ conditioning_items_data=conditioning_items_data, width=width, height=height,
260
+ seed=seed, cfg=cfg, progress=progress,
261
+ video_total_frames=video_total_frames, video_fps=video_fps,
262
+ use_attention_slicing=use_attention_slicing, num_inference_steps=num_inference_steps
263
+ )
264
+
265
+ log_history += f" - LOG: Gerei o fragmento_{fragment_num} bruto com {actual_frames_generated} frames.\n"
266
+ yield {production_log_output: log_history}
267
+
268
+ trimmed_fragment_path = os.path.join(WORKSPACE_DIR, f"fragment_{fragment_num}_trimmed.mp4")
269
+ trim_video_to_frames(full_fragment_path, trimmed_fragment_path, int(fragment_duration_frames))
270
+
271
+ log_history += f" - LOG: Reduzi o fragmento_{fragment_num} para {int(fragment_duration_frames)} frames.\n"
272
+ yield {production_log_output: log_history}
273
+
274
+ is_last_fragment = (i == num_transitions - 1)
275
+ if not is_last_fragment:
276
+ eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_from_frag_{fragment_num}.mp4")
277
+ kinetic_memory_path = extract_last_n_frames_as_video(trimmed_fragment_path, eco_output_path, int(eco_video_frames))
278
+ log_history += f" - LOG: Gerei o eco com {int(eco_video_frames)} frames a partir do final do fragmento reduzido.\n"
279
+ log_history += f" - Novo Eco Cinético (Vídeo) criado: {os.path.basename(kinetic_memory_path)}\n"
280
+ else:
281
+ log_history += f" - Este é o último fragmento, não é necessário gerar um eco.\n"
282
+
283
+ video_fragments.append(trimmed_fragment_path)
284
+ yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
285
+
286
+ progress(1.0, desc="Produção Concluída.")
287
+ log_history += "\nProdução de todos os fragmentos concluída.\n"
288
+ yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
289
+ finally:
290
+ pipeline_instance.to('cpu')
291
+ gc.collect()
292
+ torch.cuda.empty_cache()
293
+
294
+ def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
295
+ if not image_path: return None
296
+ try:
297
+ img = Image.open(image_path).convert("RGB"); img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
298
+ output_path = os.path.join(WORKSPACE_DIR, f"initial_ref_{size}x{size}.png"); img_square.save(output_path)
299
+ return output_path
300
+ except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
301
+
302
+ def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
303
+ if media_path.lower().endswith(('.mp4', '.mov', '.avi')):
304
+ with imageio.get_reader(media_path) as reader:
305
+ first_frame_np = reader.get_data(0)
306
+ temp_img_path = os.path.join(WORKSPACE_DIR, f"temp_frame_from_{os.path.basename(media_path)}.png")
307
+ Image.fromarray(first_frame_np).save(temp_img_path)
308
+ return load_image_to_tensor_with_resize_and_crop(temp_img_path, height, width)
309
+ else:
310
+ return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
311
+
312
+ def run_ltx_animation(
313
+ current_fragment_index, motion_prompt, conditioning_items_data,
314
+ width, height, seed, cfg, progress,
315
+ video_total_frames, video_fps, use_attention_slicing, num_inference_steps
316
+ ):
317
+ progress(0, desc=f"[Câmera LTX] Filmando Cena {current_fragment_index}...");
318
+ output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4")
319
+ target_device = pipeline_instance.device # A pipeline já estará no dispositivo correto (cuda)
320
+ try:
321
+ if use_attention_slicing: pipeline_instance.enable_attention_slicing()
322
+
323
+ conditioning_items = [ConditioningItem(load_conditioning_tensor(p, height, width).to(target_device), s, t) for p, s, t in conditioning_items_data]
324
+
325
+ actual_num_frames = int(round((float(video_total_frames) - 1.0) / 8.0) * 8 + 1)
326
+ padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
327
+ padding_vals = calculate_padding(height, width, padded_h, padded_w)
328
+ for item in conditioning_items: item.media_item = torch.nn.functional.pad(item.media_item, padding_vals)
329
+
330
+ first_pass_config = PIPELINE_CONFIG_YAML.get("first_pass", {}).copy()
331
+ first_pass_config['num_inference_steps'] = int(num_inference_steps)
332
+
333
+ 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": first_pass_config.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"), "enhance_prompt": False, "decode_every": 4, "num_inference_steps": int(num_inference_steps)}
334
+
335
+ result_tensor = pipeline_instance(**kwargs).images
336
+
337
+ 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
338
+
339
+ cropped_tensor = result_tensor[:, :, :actual_num_frames, pad_t:slice_h, pad_l:slice_w]
340
+ video_np = (cropped_tensor[0].permute(1, 2, 3, 0).cpu().float().numpy() * 255).astype(np.uint8)
341
+
342
+ with imageio.get_writer(output_path, fps=video_fps, codec='libx264', quality=8) as writer:
343
+ for i, frame in enumerate(video_np): writer.append_data(frame)
344
+ return output_path, actual_num_frames
345
+ finally:
346
+ if use_attention_slicing: pipeline_instance.disable_attention_slicing()
347
+ # Não movemos a pipeline para a CPU aqui; isso é feito no final da função `run_video_production`
348
+
349
+ def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
350
+ try:
351
+ 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)
352
+ return output_path
353
+ except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao cortar vídeo: {e.stderr}")
354
+
355
+ def extract_last_n_frames_as_video(input_path: str, output_path: str, n_frames: int) -> str:
356
+ try:
357
+ cmd_probe = f"ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 \"{input_path}\""
358
+ result = subprocess.run(cmd_probe, shell=True, check=True, text=True, capture_output=True)
359
+ total_frames = int(result.stdout.strip())
360
+
361
+ if n_frames >= total_frames:
362
+ shutil.copyfile(input_path, output_path)
363
+ return output_path
364
+
365
+ start_frame = total_frames - n_frames
366
+ cmd_ffmpeg = f"ffmpeg -y -v error -i \"{input_path}\" -vf \"select='gte(n,{start_frame})'\" -vframes {n_frames} -an \"{output_path}\""
367
+ subprocess.run(cmd_ffmpeg, shell=True, check=True, text=True)
368
+ return output_path
369
+ except (subprocess.CalledProcessError, ValueError) as e:
370
+ raise gr.Error(f"FFmpeg falhou ao extrair os últimos {n_frames} frames: {getattr(e, 'stderr', str(e))}")
371
+
372
+ def concatenate_and_trim_masterpiece(fragment_paths: list, fragment_duration_frames: int, eco_video_frames: int, progress=gr.Progress()):
373
+ if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
374
+ progress(0.1, desc="Preparando fragmentos para montagem final...");
375
+
376
+ try:
377
+ list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt")
378
+ final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
379
+ temp_files_for_concat = []
380
+
381
+ final_clip_len = int(fragment_duration_frames - eco_video_frames)
382
+
383
+ for i, p in enumerate(fragment_paths):
384
+ if i == len(fragment_paths) - 1:
385
+ temp_files_for_concat.append(os.path.abspath(p))
386
+ progress(0.1 + (i / len(fragment_paths)) * 0.8, desc=f"Mantendo último fragmento: {os.path.basename(p)}")
387
+ else:
388
+ temp_path = os.path.join(WORKSPACE_DIR, f"temp_concat_{i}.mp4")
389
+ progress(0.1 + (i / len(fragment_paths)) * 0.8, desc=f"Cortando {os.path.basename(p)} para {final_clip_len} frames")
390
+ trim_video_to_frames(p, temp_path, final_clip_len)
391
+ temp_files_for_concat.append(temp_path)
392
+
393
+ progress(0.9, desc="Concatenando clipes...")
394
+ with open(list_file_path, "w") as f:
395
+ for p_temp in temp_files_for_concat:
396
+ f.write(f"file '{p_temp}'\n")
397
+
398
+ 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)
399
+ progress(1.0, desc="Montagem concluída!")
400
+ return final_output_path
401
+ except subprocess.CalledProcessError as e:
402
+ raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
403
+
404
+ # --- Ato 5: A Interface com o Mundo (UI) ---
405
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
406
+ gr.Markdown("# NOVIM-6.1 (Painel de Controle do Diretor)\n*By Carlex & Gemini & DreamO - Versão HF Spaces*")
407
+ if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
408
+ os.makedirs(WORKSPACE_DIR); Path("prompts").mkdir(exist_ok=True)
409
+
410
+ scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
411
+ prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
412
+
413
+ gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
414
+ with gr.Row():
415
+ with gr.Column(scale=1):
416
+ prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
417
+ num_fragments_input = gr.Slider(2, 5, 4, step=1, label="Número de Atos (Keyframes)")
418
+ image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
419
+ director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
420
+ with gr.Column(scale=2): storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado (em Inglês)")
421
+
422
+ gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
423
+ with gr.Row():
424
+ with gr.Column(scale=2):
425
+ gr.Markdown("Forneça referências para guiar a IA. A Principal é obrigatória. A Secundária é opcional (ex: para estilo ou uma segunda pessoa).")
426
+ with gr.Row():
427
+ with gr.Column():
428
+ ref1_image = gr.Image(label="Referência Principal (Conteúdo/ID)", type="filepath")
429
+ ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Ref. Principal")
430
+ with gr.Column():
431
+ ref2_image = gr.Image(label="Referência Secundária (Opcional)", type="filepath")
432
+ ref2_task = gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa da Ref. Secundária")
433
+ photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
434
+ with gr.Column(scale=1):
435
+ keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
436
+ keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
437
+
438
+ gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
439
+ with gr.Row():
440
+ with gr.Column(scale=1):
441
+ cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
442
+ with gr.Accordion("Controles Avançados de Timing e Performance", open=False):
443
+ video_duration_slider = gr.Slider(label="Duração da Geração Bruta (segundos)", minimum=2.0, maximum=10.0, value=6.0, step=0.5)
444
+ video_fps_slider = gr.Slider(label="FPS do Vídeo", minimum=12, maximum=30, value=30, step=1)
445
+ num_inference_steps_slider = gr.Slider(label="Etapas de Inferência", minimum=10, maximum=50, value=30, step=1)
446
+ slicing_checkbox = gr.Checkbox(label="Usar Attention Slicing (Economiza VRAM)", value=True)
447
+ gr.Markdown("---"); gr.Markdown("#### Controles de Duração (Arquitetura Eco + Déjà Vu)")
448
+ fragment_duration_slider = gr.Slider(label="Duração de Cada Fragmento (Frames)", minimum=30, maximum=300, value=90, step=1)
449
+ eco_frames_slider = gr.Slider(label="Tamanho do Eco Cinético (Frames)", minimum=4, maximum=48, value=8, step=1)
450
+ mid_cond_strength_slider = gr.Slider(label="Força do 'Caminho'", minimum=0.1, maximum=1.0, value=0.5, step=0.05)
451
+ gr.Markdown(
452
+ """
453
+ **Instruções (Nova Arquitetura):**
454
+ - **Duração da Geração Bruta:** Tempo total que a IA tem para criar a transição. Deve ser MAIOR que a Duração do Fragmento.
455
+ - **Duração de Cada Fragmento:** O comprimento final de cada clipe de vídeo que será gerado.
456
+ - **Tamanho do Eco Cinético:** Quantos frames do *final* de um fragmento serão passados para o próximo para garantir continuidade.
457
+ - **Força do Caminho:** Define o quão forte a imagem-chave intermediária ('Caminho') influencia a transição.
458
+ """
459
+ )
460
+ animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
461
+ with gr.Accordion("Visualização das Mídias de Condicionamento (Ao Vivo)", open=True):
462
+ with gr.Row():
463
+ prod_media_start_output = gr.Video(label="Mídia Inicial (Eco/K1)", interactive=False)
464
+ prod_media_mid_output = gr.Image(label="Mídia do Caminho (K_i-1)", interactive=False, visible=False)
465
+ prod_media_end_output = gr.Image(label="Mídia de Destino (K_i)", interactive=False)
466
+ production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
467
+ with gr.Column(scale=1): video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados (Versões Cortadas)", object_fit="contain", height="auto", type="video")
468
+
469
+ fragment_duration_state = gr.State()
470
+ eco_frames_state = gr.State()
471
+
472
+ gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
473
+ editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
474
+ final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
475
+
476
+ gr.Markdown(
477
+ """
478
+ ---
479
+ ### A Arquitetura: Eco + Déjà Vu
480
+ A geração começa com um "Big Bang" entre os dois primeiros keyframes. A partir daí, a mágica acontece.
481
+ * **O Eco (A Memória Física):** No final de cada cena, os últimos frames são capturados e salvos como um pequeno vídeo, o `Eco`. Ele carrega a "energia cinética" do movimento, iluminação e atmosfera da cena que acabou.
482
+ * **O Déjà Vu (A Memória Conceitual):** Para criar a próxima cena, o Cineasta de IA (Gemini) assiste ao `Eco`, olha para o keyframe do "caminho" e o keyframe do "destino". Com essa visão tripla, ele tem um "déjà vu", uma memória do que acabou de acontecer que o inspira a escrever uma instrução de câmera precisa para conectar o passado ao futuro de forma fluida e coerente.
483
+ """
484
+ )
485
+
486
+ # --- Ato 6: A Regência (Lógica de Conexão dos Botões) ---
487
+ def process_and_update_storyboard(num_fragments, prompt, image_path):
488
+ processed_path = process_image_to_square(image_path)
489
+ if not processed_path: raise gr.Error("A imagem de referência é inválida ou não foi fornecida.")
490
+ storyboard = run_storyboard_generation(num_fragments, prompt, processed_path)
491
+ return storyboard, prompt, processed_path
492
+
493
+ director_button.click(
494
+ fn=process_and_update_storyboard,
495
+ inputs=[num_fragments_input, prompt_input, image_input],
496
+ outputs=[scene_storyboard_state, prompt_geral_state, processed_ref_path_state]
497
+ ).success(
498
+ fn=lambda s, p: (s, p),
499
+ inputs=[scene_storyboard_state, processed_ref_path_state],
500
+ outputs=[storyboard_to_show, ref1_image]
501
+ )
502
+
503
+ @photographer_button.click(
504
+ inputs=[scene_storyboard_state, ref1_image, ref1_task, ref2_image, ref2_task],
505
+ outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
506
+ )
507
+ def run_keyframe_generation_wrapper(storyboard, ref1_img, ref1_tsk, ref2_img, ref2_tsk, progress=gr.Progress()):
508
+ ref_data = [
509
+ {'image': ref1_img, 'task': ref1_tsk},
510
+ {'image': ref2_img, 'task': ref2_tsk}
511
+ ]
512
+ # Esta chamada agora invoca a função decorada com @spaces.GPU
513
+ yield from run_keyframe_generation(storyboard, ref_data, progress)
514
+
515
+ animator_button.click(
516
+ fn=lambda frag_dur, eco_dur: (frag_dur, eco_dur),
517
+ inputs=[fragment_duration_slider, eco_frames_slider],
518
+ outputs=[fragment_duration_state, eco_frames_state]
519
+ ).then(
520
+ fn=run_video_production, # Esta função é decorada com @spaces.GPU
521
+ inputs=[
522
+ video_duration_slider, video_fps_slider, eco_frames_slider, slicing_checkbox,
523
+ fragment_duration_slider, mid_cond_strength_slider,
524
+ num_inference_steps_slider,
525
+ prompt_geral_state, keyframe_images_state, scene_storyboard_state, cfg_slider
526
+ ],
527
+ outputs=[
528
+ production_log_output, video_gallery_glitch, fragment_list_state,
529
+ prod_media_start_output, prod_media_mid_output, prod_media_end_output
530
+ ]
531
+ )
532
+
533
+ editor_button.click(
534
+ fn=concatenate_and_trim_masterpiece,
535
+ inputs=[fragment_list_state, fragment_duration_state, eco_frames_state],
536
+ outputs=[final_video_output]
537
+ )
538
+
539
+ if __name__ == "__main__":
540
+ demo.queue().launch(server_name="0.0.0.0", share=True)