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

Delete app.5.5.py

Browse files
Files changed (1) hide show
  1. app.5.5.py +0 -636
app.5.5.py DELETED
@@ -1,636 +0,0 @@
1
- # Euia-AducSdr: Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
2
- # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
- #
4
- # Contato:
5
- # Carlos Rodrigues dos Santos
6
7
- # Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
8
- #
9
- # Repositórios e Projetos Relacionados:
10
- # GitHub: https://github.com/carlex22/Aduc-sdr
11
- # Hugging Face: https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
12
- # Hugging Face: https://huggingface.co/spaces/Carlexxx/Novinho/
13
- #
14
- # Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
15
- # sob os termos da Licença Pública Geral Affero da GNU como publicada pela
16
- # Free Software Foundation, seja a versão 3 da Licença, ou
17
- # (a seu critério) qualquer versão posterior.
18
- #
19
- # Este programa é distribuído na esperança de que seja útil,
20
- # mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
21
- # COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
22
- # Licença Pública Geral Affero da GNU para mais detalhes.
23
- #
24
- # Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
25
- # junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
26
-
27
- # --- app.py (NOVINHO-5.2-DOCS: Otimização de Memória + Documentação Completa) ---
28
-
29
- # --- Ato 1: A Convocação da Orquestra (Importações) ---
30
- import gradio as gr
31
- import torch
32
- import os
33
- import yaml
34
- from PIL import Image, ImageOps, ExifTags
35
- import shutil
36
- import gc
37
- import subprocess
38
- import google.generativeai as genai
39
- import numpy as np
40
- import imageio
41
- from pathlib import Path
42
- import huggingface_hub
43
- import json
44
- import time
45
-
46
- from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
47
- from dreamo_helpers import dreamo_generator_singleton
48
-
49
- # --- Ato 2: A Preparação do Palco (Configurações) ---
50
- config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
51
- with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
52
-
53
- LTX_REPO = "Lightricks/LTX-Video"
54
- models_dir = "downloaded_models_gradio"
55
- Path(models_dir).mkdir(parents=True, exist_ok=True)
56
- WORKSPACE_DIR = "aduc_workspace"
57
- GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
58
-
59
- VIDEO_FPS = 24
60
- VIDEO_DURATION_SECONDS = 8.0
61
- VIDEO_TOTAL_FRAMES = int(VIDEO_DURATION_SECONDS * VIDEO_FPS)
62
- TARGET_RESOLUTION = 420
63
-
64
- print("Criando pipelines LTX na CPU (estado de repouso)...")
65
- distilled_model_actual_path = huggingface_hub.hf_hub_download(repo_id=LTX_REPO, filename=PIPELINE_CONFIG_YAML["checkpoint_path"], local_dir=models_dir, local_dir_use_symlinks=False)
66
- pipeline_instance = create_ltx_video_pipeline(
67
- ckpt_path=distilled_model_actual_path,
68
- precision=PIPELINE_CONFIG_YAML["precision"],
69
- text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
70
- sampler=PIPELINE_CONFIG_YAML["sampler"],
71
- device='cpu'
72
- )
73
- print("Modelos LTX prontos (na CPU).")
74
-
75
-
76
- # --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
77
- # AVISO: A documentação abaixo descreve a lógica de cada função.
78
- # NÃO APAGUE OU ALTERE ESTES COMENTÁRIOS SEM SOLICITAÇÃO EXPLÍCITA.
79
-
80
- # --- Funções da ETAPA 1 (Roteiro) ---
81
-
82
- def robust_json_parser(raw_text: str) -> dict:
83
- """
84
- Analisa uma string de texto bruto para encontrar e decodificar o primeiro objeto JSON válido.
85
- Esta função é crucial para lidar com as respostas das IAs, que podem incluir texto
86
- conversacional antes ou depois do bloco JSON.
87
-
88
- Args:
89
- raw_text (str): A string de texto completa retornada pela IA.
90
-
91
- Returns:
92
- dict: Um dicionário Python representando o objeto JSON encontrado.
93
-
94
- Raises:
95
- ValueError: Se nenhum objeto JSON for encontrado ou se a decodificação falhar.
96
- """
97
- try:
98
- start_index = raw_text.find('{')
99
- end_index = raw_text.rfind('}')
100
- if start_index != -1 and end_index != -1 and end_index > start_index:
101
- json_str = raw_text[start_index : end_index + 1]
102
- return json.loads(json_str)
103
- else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
104
- except json.JSONDecodeError as e:
105
- raise ValueError(f"Falha ao decodificar JSON: {e}")
106
-
107
- def extract_image_exif(image_path: str) -> str:
108
- """
109
- Extrai metadados EXIF relevantes de um arquivo de imagem.
110
- Foca em informações técnicas como modelo da câmera, lente e configurações de exposição.
111
-
112
- Args:
113
- image_path (str): O caminho para o arquivo de imagem.
114
-
115
- Returns:
116
- str: Uma string formatada contendo os metadados EXIF relevantes, ou uma mensagem
117
- indicando que nenhum metadado foi encontrado ou lido.
118
- """
119
- try:
120
- img = Image.open(image_path); exif_data = img._getexif()
121
- if not exif_data: return "No EXIF metadata found."
122
- exif = { ExifTags.TAGS[k]: v for k, v in exif_data.items() if k in ExifTags.TAGS }
123
- relevant_tags = ['DateTimeOriginal', 'Model', 'LensModel', 'FNumber', 'ExposureTime', 'ISOSpeedRatings', 'FocalLength']
124
- metadata_str = ", ".join(f"{key}: {exif[key]}" for key in relevant_tags if key in exif)
125
- return metadata_str if metadata_str else "No relevant EXIF metadata found."
126
- except Exception: return "Could not read EXIF data."
127
-
128
- def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
129
- """
130
- Orquestra a Etapa 1. Em uma única chamada à IA, combina a análise da imagem de referência
131
- com o prompt do usuário para gerar um roteiro de cenas (storyboard).
132
-
133
- Args:
134
- num_fragments (int): O número de atos (cenas) a serem criados.
135
- prompt (str): A "Ideia Geral" fornecida pelo usuário.
136
- initial_image_path (str): O caminho para a imagem de referência inicial.
137
-
138
- Returns:
139
- list: Uma lista de strings, onde cada string é a descrição de um ato do roteiro.
140
- """
141
- if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
142
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
143
- exif_metadata = extract_image_exif(initial_image_path)
144
- prompt_file = "prompts/unified_storyboard_prompt.txt"
145
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
146
- director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata=exif_metadata)
147
- genai.configure(api_key=GEMINI_API_KEY)
148
- model = genai.GenerativeModel('gemini-2.0-flash'); img = Image.open(initial_image_path)
149
- print("Gerando roteiro com análise de visão integrada...")
150
- response = model.generate_content([director_prompt, img])
151
- try:
152
- storyboard_data = robust_json_parser(response.text)
153
- storyboard = storyboard_data.get("scene_storyboard", [])
154
- 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)}")
155
- return storyboard
156
- except Exception as e: raise gr.Error(f"O Roteirista (Gemini) falhou ao criar o roteiro: {e}. Resposta recebida: {response.text}")
157
-
158
-
159
- # --- Funções da ETAPA 2 (Keyframes) ---
160
- def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
161
- """
162
- Chama a IA "Diretor de Arte" para criar um prompt de imagem dinâmico.
163
- A IA analisa a imagem anterior e a descrição da próxima cena para gerar um prompt
164
- que guiará o "Pintor" (DreamO) na criação do próximo keyframe.
165
-
166
- Args:
167
- previous_image_path (str): Caminho para a imagem de referência mais recente.
168
- target_scene_description (str): A descrição do ato do roteiro para a cena a ser criada.
169
-
170
- Returns:
171
- str: O prompt de imagem gerado.
172
- """
173
- genai.configure(api_key=GEMINI_API_KEY)
174
- prompt_file = "prompts/img2img_evolution_prompt.txt"
175
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
176
- director_prompt = template.format(target_scene_description=target_scene_description)
177
- model = genai.GenerativeModel('gemini-2.0-flash'); img = Image.open(previous_image_path)
178
- response = model.generate_content([director_prompt, "Previous Image:", img])
179
- return response.text.strip().replace("\"", "")
180
-
181
- def run_keyframe_generation(storyboard, initial_ref_image_path, sequential_ref_task, *additional_refs_and_tasks, progress=gr.Progress()):
182
- """
183
- Orquestra a Etapa 2. Gera a sequência de imagens-chave (keyframes) em um loop.
184
- Combina referências estáticas (fornecidas pelo usuário) com referências dinâmicas
185
- (os últimos keyframes gerados) para manter a consistência.
186
-
187
- Args:
188
- storyboard (list): A lista de atos do roteiro.
189
- initial_ref_image_path (str): Caminho para a imagem de referência inicial processada.
190
- sequential_ref_task (str): A tarefa de referência para a cadeia dinâmica de keyframes.
191
- *additional_refs_and_tasks: Tupla de imagens e tarefas de referência adicionais.
192
- progress (gr.Progress): Objeto do Gradio para atualizar a barra de progresso.
193
-
194
- Yields:
195
- dict: Atualizações para a UI (log, galeria) durante a geração.
196
-
197
- Returns:
198
- dict: O estado final dos componentes da UI e as listas de keyframes.
199
- """
200
- if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
201
- if not initial_ref_image_path: raise gr.Error("A imagem de referência principal é obrigatória.")
202
- log_history = ""; generated_images_for_gallery = []
203
-
204
- # Processar as referências estáticas fornecidas pelo usuário na UI
205
- base_reference_items = []
206
- num_pairs = len(additional_refs_and_tasks) // 2
207
- for i in range(num_pairs):
208
- img_path = additional_refs_and_tasks[i * 2]
209
- task = additional_refs_and_tasks[i * 2 + 1]
210
- if img_path: # Apenas processar se o usuário inseriu uma imagem
211
- base_reference_items.append({'image_np': np.array(Image.open(img_path).convert("RGB")), 'task': task})
212
-
213
- try:
214
- pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
215
- dreamo_generator_singleton.to_gpu()
216
- with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
217
- keyframe_paths, current_ref_image_path = [initial_ref_image_path], initial_ref_image_path
218
-
219
- for i, scene_description in enumerate(storyboard):
220
- progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
221
- log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
222
- dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
223
-
224
- # Criar as referências dinâmicas (últimos 3 keyframes gerados)
225
- recent_references_paths = keyframe_paths[-3:]
226
- sequential_reference_items = [{'image_np': np.array(Image.open(ref_path).convert("RGB")), 'task': sequential_ref_task} for ref_path in recent_references_paths]
227
-
228
- # Combinar referências estáticas e dinâmicas
229
- all_reference_items = base_reference_items + sequential_reference_items
230
-
231
- log_history += f" - Roteiro: '{scene_description}'\n"
232
- log_history += f" - Usando {len(base_reference_items)} refs fixas + {len(sequential_reference_items)} refs sequenciais ({[os.path.basename(p) for p in recent_references_paths]}).\n"
233
- log_history += f" - Prompt do D.A.: \"{dreamo_prompt}\"\n"
234
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
235
-
236
- output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
237
- image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=all_reference_items, prompt=dreamo_prompt, width=width, height=height)
238
- image.save(output_path)
239
- keyframe_paths.append(output_path); generated_images_for_gallery.append(output_path); current_ref_image_path = output_path
240
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery)}
241
- except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
242
- finally: dreamo_generator_singleton.to_cpu(); gc.collect(); torch.cuda.empty_cache()
243
-
244
- log_history += "\nPintura de todos os keyframes concluída.\n"
245
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery), keyframe_images_state: keyframe_paths}
246
-
247
-
248
- # --- Funções da ETAPA 3 (Produção de Vídeo) ---
249
- def get_initial_motion_prompt(user_prompt: str, start_image_path: str, destination_image_path: str, dest_scene_desc: str):
250
- """
251
- Gera o prompt de movimento para o primeiro fragmento de vídeo ("Big Bang").
252
- Este é um caso especial que lida com uma transição simples de (Início -> Fim).
253
-
254
- Args:
255
- user_prompt (str): A ideia geral para dar contexto.
256
- start_image_path (str): Caminho para o primeiro keyframe gerado (K_1).
257
- destination_image_path (str): Caminho para o segundo keyframe gerado (K_2).
258
- dest_scene_desc (str): A descrição do roteiro para a cena de destino (Ato 2).
259
-
260
- Returns:
261
- str: O prompt de movimento gerado para a transição inicial.
262
- """
263
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
264
- try:
265
- genai.configure(api_key=GEMINI_API_KEY)
266
- model = genai.GenerativeModel('gemini-2.0-flash')
267
- prompt_file = "prompts/initial_motion_prompt.txt"
268
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
269
- cinematographer_prompt = template.format(user_prompt=user_prompt, destination_scene_description=dest_scene_desc)
270
- start_img, dest_img = Image.open(start_image_path), Image.open(destination_image_path)
271
- model_contents = ["START Image:", start_img, "DESTINATION Image:", dest_img, cinematographer_prompt]
272
- response = model.generate_content(model_contents)
273
- return response.text.strip()
274
- except Exception as e: raise gr.Error(f"O Cineasta de IA (Inicial) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
275
-
276
- def get_dynamic_motion_prompt(user_prompt, story_history, memory_image_path, path_image_path, destination_image_path, path_scene_desc, dest_scene_desc):
277
- """
278
- Gera o prompt de movimento para os fragmentos subsequentes, usando a lógica "Handoff Cinético".
279
- A IA analisa 3 imagens (Memória, Caminho, Destino) para criar a instrução.
280
-
281
- Args:
282
- user_prompt (str): A ideia geral.
283
- story_history (str): Um resumo dos prompts de movimento anteriores.
284
- memory_image_path (str): O "Eco", último frame do fragmento anterior.
285
- path_image_path (str): O "Caminho", keyframe que define o contexto da transição.
286
- destination_image_path (str): O "Destino", keyframe que queremos alcançar.
287
- path_scene_desc (str): Descrição do roteiro para o "Caminho".
288
- dest_scene_desc (str): Descrição do roteiro para o "Destino".
289
-
290
- Returns:
291
- str: O prompt de movimento dinâmico gerado.
292
- """
293
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
294
- try:
295
- genai.configure(api_key=GEMINI_API_KEY)
296
- model = genai.GenerativeModel('gemini-2.0-flash')
297
- prompt_file = "prompts/dynamic_motion_prompt.txt"
298
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
299
- cinematographer_prompt = template.format(user_prompt=user_prompt, story_history=story_history, midpoint_scene_description=path_scene_desc, destination_scene_description=dest_scene_desc)
300
- mem_img, path_img, dest_img = Image.open(memory_image_path), Image.open(path_image_path), Image.open(destination_image_path)
301
- model_contents = ["START Image (Memory):", mem_img, "MIDPOINT Image (Path):", path_img, "DESTINATION Image (Destination):", dest_img, cinematographer_prompt]
302
- response = model.generate_content(model_contents)
303
- return response.text.strip()
304
- except Exception as e: raise gr.Error(f"O Cineasta de IA (Dinâmico) falhou: {e}. Resposta: {getattr(e, 'text', 'No text available.')}")
305
-
306
- def run_video_production(prompt_geral, keyframe_images_state, scene_storyboard, seed, cfg, cut_frames_value, progress=gr.Progress()):
307
- """
308
- Orquestra a Etapa 3. Gera todos os fragmentos de vídeo em um loop, aplicando a lógica
309
- "Big Bang" para o primeiro fragmento e "Handoff Cinético" para os demais.
310
-
311
- Args:
312
- prompt_geral (str): A ideia geral do usuário.
313
- keyframe_images_state (list): A lista completa de keyframes [K_0, ..., K_n].
314
- scene_storyboard (list): A lista de atos do roteiro.
315
- seed (int): A semente para a geração de números aleatórios.
316
- cfg (float): A escala de orientação do LTX.
317
- cut_frames_value (int): O número de frames a manter em cada fragmento cortado.
318
- progress (gr.Progress): Objeto do Gradio para a barra de progresso.
319
-
320
- Yields:
321
- dict: Atualizações para a UI durante o processo.
322
-
323
- Returns:
324
- dict: O estado final dos componentes da UI.
325
- """
326
- if not keyframe_images_state or len(keyframe_images_state) < 3: raise gr.Error("Pinte pelo menos 2 keyframes para produzir uma transição.")
327
- log_history = "\n--- FASE 3/4: Iniciando Produção com Lógica 'Big Bang'...\n"
328
- yield {production_log_output: log_history, video_gallery_glitch: []}
329
-
330
- MID_COND_FRAME, MID_COND_STRENGTH = 54, 0.5; END_COND_FRAME = VIDEO_TOTAL_FRAMES - 8
331
- target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
332
- try:
333
- pipeline_instance.to(target_device)
334
- video_fragments, story_history = [], ""; kinetic_memory_path = None
335
- with Image.open(keyframe_images_state[1]) as img: width, height = img.size
336
-
337
- num_transitions = len(keyframe_images_state) - 2
338
- for i in range(num_transitions):
339
- fragment_num = i + 1
340
- progress(i / num_transitions, desc=f"Filmando Fragmento {fragment_num}/{num_transitions}")
341
- log_history += f"\n--- FRAGMENTO {fragment_num} ---\n"
342
-
343
- if i == 0:
344
- start_path, destination_path = keyframe_images_state[1], keyframe_images_state[2]
345
- dest_scene_desc = scene_storyboard[1]
346
- log_history += f" - Início (Big Bang): {os.path.basename(start_path)}\n - Destino: {os.path.basename(destination_path)}\n"
347
- current_motion_prompt = get_initial_motion_prompt(prompt_geral, start_path, destination_path, dest_scene_desc)
348
- conditioning_items_data = [(start_path, int(0), 1.0), (destination_path, int(END_COND_FRAME), 1.0)]
349
- else:
350
- memory_path, path_path, destination_path = kinetic_memory_path, keyframe_images_state[i+1], keyframe_images_state[i+2]
351
- path_scene_desc, dest_scene_desc = scene_storyboard[i], scene_storyboard[i+1]
352
- log_history += f" - Memória Cinética: {os.path.basename(memory_path)}\n - Caminho: {os.path.basename(path_path)}\n - Destino: {os.path.basename(destination_path)}\n"
353
- current_motion_prompt = get_dynamic_motion_prompt(prompt_geral, story_history, memory_path, path_path, destination_path, path_scene_desc, dest_scene_desc)
354
- conditioning_items_data = [(memory_path, int(0), 1.0), (path_path, int(MID_COND_FRAME), MID_COND_STRENGTH), (destination_path, int(END_COND_FRAME), 1.0)]
355
-
356
- story_history += f"\n- Ato {fragment_num + 1}: {current_motion_prompt}"
357
- log_history += f" - Instrução do Cineasta: '{current_motion_prompt}'\n"; yield {production_log_output: log_history}
358
- full_fragment_path, _ = run_ltx_animation(fragment_num, current_motion_prompt, conditioning_items_data, width, height, seed, cfg, progress)
359
-
360
- is_last_fragment = (i == num_transitions - 1)
361
- if is_last_fragment:
362
- final_fragment_path = full_fragment_path
363
- log_history += " - Último fragmento gerado, mantendo a duração total para um final limpo.\n"
364
- else:
365
- final_fragment_path = os.path.join(WORKSPACE_DIR, f"fragment_{fragment_num}_trimmed.mp4")
366
- trim_video_to_frames(full_fragment_path, final_fragment_path, int(cut_frames_value))
367
- eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_from_frag_{fragment_num}.png")
368
- kinetic_memory_path = extract_last_frame_as_image(final_fragment_path, eco_output_path)
369
- log_history += f" - Gerado e cortado. Novo Eco Dinâmico criado: {os.path.basename(kinetic_memory_path)}\n"
370
-
371
- video_fragments.append(final_fragment_path)
372
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
373
-
374
- progress(1.0, desc="Produção Concluída.")
375
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
376
- finally:
377
- pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
378
-
379
-
380
- # --- Funções Utilitárias e de Pós-Produção ---
381
- def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
382
- """
383
- Processa a imagem de referência inicial: converte para RGB e redimensiona para um
384
- formato quadrado (TARGET_RESOLUTION x TARGET_RESOLUTION).
385
-
386
- Args:
387
- image_path (str): Caminho para a imagem original.
388
- size (int): A dimensão do lado do quadrado final.
389
-
390
- Returns:
391
- str: O caminho para a imagem processada e salva.
392
- """
393
- if not image_path: return None
394
- try:
395
- img = Image.open(image_path).convert("RGB"); img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
396
- output_path = os.path.join(WORKSPACE_DIR, f"initial_ref_{size}x{size}.png"); img_square.save(output_path)
397
- return output_path
398
- except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
399
-
400
- def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
401
- """
402
- Carrega uma imagem e a converte para o formato de tensor esperado pelo LTX.
403
-
404
- Args:
405
- media_path (str): Caminho para o arquivo de imagem.
406
- height (int): Altura do vídeo alvo.
407
- width (int): Largura do vídeo alvo.
408
-
409
- Returns:
410
- torch.Tensor: O tensor da imagem, pronto para ser usado como condicionamento.
411
- """
412
- return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
413
-
414
- def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg, progress=gr.Progress()):
415
- """
416
- Wrapper para a execução do pipeline do LTX. Gera um único fragmento de vídeo.
417
- Ativa o 'attention slicing' para economizar VRAM durante a execução.
418
-
419
- Args:
420
- current_fragment_index (int): O número do fragmento atual (para a seed).
421
- motion_prompt (str): O prompt de movimento do Cineasta de IA.
422
- conditioning_items_data (list): Lista de tuplas para os itens de condicionamento.
423
- width (int): Largura do vídeo.
424
- height (int): Altura do vídeo.
425
- seed (int): Semente de geração.
426
- cfg (float): Escala de orientação.
427
- progress (gr.Progress): Objeto do Gradio para a barra de progresso.
428
-
429
- Returns:
430
- tuple: (caminho_do_video_gerado, numero_de_frames_gerados)
431
- """
432
- progress(0, desc=f"[Câmera LTX] Filmando Cena {current_fragment_index}...");
433
- output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}_full.mp4"); target_device = pipeline_instance.device
434
-
435
- try:
436
- pipeline_instance.enable_attention_slicing()
437
-
438
- conditioning_items = [ConditioningItem(load_conditioning_tensor(p, height, width).to(target_device), s, t) for p, s, t in conditioning_items_data]
439
- actual_num_frames = int(round((float(VIDEO_TOTAL_FRAMES) - 1.0) / 8.0) * 8 + 1)
440
- padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
441
- padding_vals = calculate_padding(height, width, padded_h, padded_w)
442
- for item in conditioning_items: item.media_item = torch.nn.functional.pad(item.media_item, padding_vals)
443
- 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"), "enhance_prompt": False, "decode_every": 4}
444
- result_tensor = pipeline_instance(**kwargs).images
445
-
446
- 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
447
- 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)
448
- with imageio.get_writer(output_path, fps=VIDEO_FPS, codec='libx264', quality=8) as writer:
449
- for i, frame in enumerate(video_np): writer.append_data(frame)
450
-
451
- return output_path, actual_num_frames
452
- finally:
453
- pipeline_instance.disable_attention_slicing()
454
-
455
- def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
456
- """
457
- Usa o FFmpeg para cortar um vídeo, mantendo apenas um número específico de frames iniciais.
458
- Essencial para o "Corte Estratégico" do Handoff Cinético.
459
-
460
- Args:
461
- input_path (str): Caminho para o vídeo de entrada.
462
- output_path (str): Caminho para salvar o vídeo cortado.
463
- frames_to_keep (int): Número de frames a serem mantidos.
464
-
465
- Returns:
466
- str: O caminho para o vídeo cortado.
467
- """
468
- try:
469
- 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)
470
- return output_path
471
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao cortar vídeo: {e.stderr}")
472
-
473
- def extract_last_frame_as_image(video_path: str, output_image_path: str) -> str:
474
- """
475
- Usa o FFmpeg para extrair eficientemente o último frame de um vídeo.
476
- Esta é a função que cria o "Eco" para o Handoff Cinético.
477
-
478
- Args:
479
- video_path (str): Caminho para o vídeo de entrada.
480
- output_image_path (str): Caminho para salvar a imagem do frame extraído.
481
-
482
- Returns:
483
- str: O caminho para a imagem extraída.
484
- """
485
- try:
486
- subprocess.run(f"ffmpeg -y -v error -sseof -1 -i \"{video_path}\" -update 1 -q:v 1 \"{output_image_path}\"", shell=True, check=True, text=True)
487
- return output_image_path
488
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou ao extrair último frame: {e.stderr}")
489
-
490
- def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
491
- """
492
- Orquestra a Etapa 4. Usa o FFmpeg para concatenar todos os fragmentos de vídeo gerados
493
- em uma única obra-prima final.
494
-
495
- Args:
496
- fragment_paths (list): Uma lista dos caminhos para os fragmentos de vídeo.
497
- progress (gr.Progress): Objeto do Gradio para a barra de progresso.
498
-
499
- Returns:
500
- str: O caminho para o vídeo final montado.
501
- """
502
- if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
503
- progress(0.5, desc="Montando a obra-prima final...");
504
- try:
505
- list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
506
- with open(list_file_path, "w") as f:
507
- for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
508
- 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)
509
- progress(1.0, desc="Montagem concluída!")
510
- return final_output_path
511
- except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
512
-
513
- # --- Ato 5: A Interface com o Mundo (UI) ---
514
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
515
- gr.Markdown("# NOVINHO-5.2 (Otimização de Memória)\n*By Carlex & Gemini & DreamO*")
516
-
517
- if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
518
- os.makedirs(WORKSPACE_DIR); Path("prompts").mkdir(exist_ok=True)
519
-
520
- # State variables
521
- scene_storyboard_state = gr.State([])
522
- keyframe_images_state = gr.State([])
523
- fragment_list_state = gr.State([])
524
- prompt_geral_state = gr.State("")
525
- processed_ref_path_state = gr.State("")
526
-
527
- # UI Constants
528
- MAX_ADDITIONAL_REFS = 4
529
-
530
- gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
531
- with gr.Row():
532
- with gr.Column(scale=1):
533
- prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
534
- num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Atos (Keyframes)")
535
- image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
536
- director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
537
- with gr.Column(scale=2):
538
- storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado (em Inglês)")
539
-
540
- gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
541
- with gr.Row():
542
- with gr.Column(scale=2):
543
- gr.Markdown("O Diretor de Arte (IA) gerará prompts dinamicamente. O Pintor usará as referências abaixo + as **3 últimas imagens** geradas para criar a próxima.")
544
- with gr.Group():
545
- ref1_image = gr.Image(label="Referência Principal (Automática da Etapa 1)", type="filepath", interactive=False)
546
- ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa das Referências em Cadeia")
547
-
548
- # --- SEÇÃO DE REFERÊNCIAS ADICIONAIS (MODIFICADA) ---
549
- additional_ref_images = []
550
- additional_ref_tasks = []
551
- with gr.Accordion("Referências Adicionais do Pintor (Opcional)", open=False):
552
- with gr.Tabs():
553
- for i in range(MAX_ADDITIONAL_REFS):
554
- with gr.TabItem(f"Ref. Extra {i+1}"):
555
- with gr.Column():
556
- ref_img = gr.Image(label=f"Imagem de Referência Extra {i+1}", type="filepath", scale=2)
557
- ref_task = gr.Dropdown(choices=["ip", "id", "style"], value="style", label=f"Tarefa da Ref. Extra {i+1}")
558
- additional_ref_images.append(ref_img)
559
- additional_ref_tasks.append(ref_task)
560
-
561
- photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
562
- keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=10, interactive=False)
563
- with gr.Column(scale=1):
564
- keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
565
-
566
-
567
- gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
568
- with gr.Row():
569
- with gr.Column(scale=1):
570
- with gr.Row():
571
- seed_number = gr.Number(42, label="Seed")
572
- cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
573
- cut_frames_slider = gr.Slider(label="Duração do Fragmento (Frames)", minimum=60, maximum=VIDEO_TOTAL_FRAMES, value=150, step=1)
574
- animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
575
- production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=15, interactive=False)
576
- with gr.Column(scale=1):
577
- video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
578
-
579
- gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (IA Editor)")
580
- editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
581
- final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
582
-
583
- gr.Markdown(
584
- """
585
- ---
586
- ### A Arquitetura: Handoff Cinético & Big Bang
587
- A geração começa com um "Big Bang": a primeira transição de vídeo é entre o **Keyframe 1 e o Keyframe 2**. A imagem de referência original é usada apenas para criar o primeiro keyframe e depois é descartada do processo de vídeo.
588
-
589
- * **O Bastão (O `Eco`):** Após a primeira transição, o último frame do clipe cortado (o `Eco`) carrega a "energia cinética" da cena.
590
-
591
- * **O Handoff (A Geração):** Os fragmentos seguintes começam a partir deste `Eco` dinâmico, herdando a "física" do movimento e da iluminação.
592
-
593
- * **A Sincronização (Cineasta de IA):** Para cada Handoff, o Cineasta de IA (`Γ`) analisa o (`Eco`), o (`Keyframe` do caminho) e o (`Keyframe` do destino) para criar uma instrução de movimento precisa.
594
- """
595
- )
596
-
597
- # Event Handlers
598
- director_button.click(
599
- fn=run_storyboard_generation,
600
- inputs=[num_fragments_input, prompt_input, image_input],
601
- outputs=[scene_storyboard_state]
602
- ).success(
603
- fn=lambda s, p: (s, p),
604
- inputs=[scene_storyboard_state, prompt_input],
605
- outputs=[storyboard_to_show, prompt_geral_state]
606
- ).success(
607
- fn=process_image_to_square,
608
- inputs=[image_input],
609
- outputs=[processed_ref_path_state]
610
- ).success(
611
- fn=lambda p: p,
612
- inputs=[processed_ref_path_state],
613
- outputs=[ref1_image]
614
- )
615
-
616
- # Atualizado para incluir as referências adicionais
617
- photographer_button.click(
618
- fn=run_keyframe_generation,
619
- inputs=[scene_storyboard_state, ref1_image, ref1_task, *additional_ref_images, *additional_ref_tasks],
620
- outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
621
- )
622
-
623
- animator_button.click(
624
- fn=run_video_production,
625
- inputs=[prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider, cut_frames_slider],
626
- outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
627
- )
628
-
629
- editor_button.click(
630
- fn=concatenate_and_trim_masterpiece,
631
- inputs=[fragment_list_state],
632
- outputs=[final_video_output]
633
- )
634
-
635
- if __name__ == "__main__":
636
- demo.queue().launch(server_name="0.0.0.0", share=True)