Carlexx commited on
Commit
bd17f20
·
verified ·
1 Parent(s): 2ea54e5

Upload ai_studio_code (99).py

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