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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -559
app.py DELETED
@@ -1,559 +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
- # carlex22@gmail.com
7
- # Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
8
- #
9
- # Repositórios e Projetos Relacionados:
10
- # GitHub: https://github.com/carlex22/Aduc-sdr
11
- # Hugging Face: https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
12
- # Hugging Face: https://huggingface.co/spaces/Carlexxx/Novinho/
13
- #
14
- # Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
15
- # sob os termos da Licença Pública Geral Affero da GNU como publicada pela
16
- # Free Software Foundation, seja a versão 3 da Licença, ou
17
- # (a seu critério) qualquer versão posterior.
18
- #
19
- # Este programa é distribuído na esperança de que seja útil,
20
- # mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
21
- # COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
22
- # Licença Pública Geral Affero da GNU para mais detalhes.
23
- #
24
- # Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
25
- # junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
26
-
27
- # --- app.py (NOVINHO-4.4: O Piloto de Testes - Vetor de Frames) ---
28
-
29
- # --- Ato 1: A Convocação da Orquestra (Importações) ---
30
- import gradio as gr
31
- import torch
32
- import os
33
- import yaml
34
- from PIL import Image, ImageOps
35
- import shutil
36
- import gc
37
- import subprocess
38
- import google.generativeai as genai
39
- import numpy as np
40
- import imageio
41
- from pathlib import Path
42
- import huggingface_hub
43
- import json
44
- import time
45
- from typing import Union, List
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_cpu_init"
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 = 36
61
- VIDEO_DURATION_SECONDS = 4
62
- VIDEO_TOTAL_FRAMES = VIDEO_DURATION_SECONDS * VIDEO_FPS
63
- CONVERGENCE_FRAMES = 8
64
- TARGET_RESOLUTION = 720
65
- MAX_REFS = 4
66
-
67
- print("Baixando e criando pipelines LTX na CPU...")
68
- 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)
69
- pipeline_instance = create_ltx_video_pipeline(
70
- ckpt_path=distilled_model_actual_path,
71
- precision=PIPELINE_CONFIG_YAML["precision"],
72
- text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
73
- sampler=PIPELINE_CONFIG_YAML["sampler"],
74
- device='cpu'
75
- )
76
- print("Modelos LTX prontos (na CPU).")
77
-
78
-
79
- # --- Ato 3: As Partituras dos Músicos (Funções Corrigidas e Documentadas) ---
80
-
81
- def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
82
- if not media_path: raise ValueError("Caminho da mídia de condicionamento não pode ser nulo.")
83
- return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
84
-
85
- def run_ltx_animation(current_fragment_index, motion_prompt, conditioning_items_data, width, height, seed, cfg, progress=gr.Progress()):
86
- progress(0, desc=f"[TECPIX 5000] Filmando Cena {current_fragment_index}...");
87
- output_path = os.path.join(WORKSPACE_DIR, f"fragment_{current_fragment_index}.mp4"); target_device = 'cuda' if torch.cuda.is_available() else 'cpu'
88
- try:
89
- pipeline_instance.to(target_device)
90
- conditioning_items = []
91
- for (path, start_frame, strength) in conditioning_items_data:
92
- tensor = load_conditioning_tensor(path, height, width)
93
- conditioning_items.append(ConditioningItem(tensor.to(target_device), start_frame, strength))
94
-
95
- n_val = round((float(VIDEO_TOTAL_FRAMES) - 1.0) / 8.0); actual_num_frames = int(n_val * 8 + 1)
96
- padded_h, padded_w = ((height - 1) // 32 + 1) * 32, ((width - 1) // 32 + 1) * 32
97
- padding_vals = calculate_padding(height, width, padded_h, padded_w)
98
- for cond_item in conditioning_items: cond_item.media_item = torch.nn.functional.pad(cond_item.media_item, padding_vals)
99
- kwargs = {"prompt": motion_prompt, "negative_prompt": "blurry, distorted, bad quality, artifacts", "height": padded_h, "width": padded_w, "num_frames": actual_num_frames, "frame_rate": VIDEO_FPS, "generator": torch.Generator(device=target_device).manual_seed(int(seed) + current_fragment_index), "output_type": "pt", "guidance_scale": float(cfg), "timesteps": PIPELINE_CONFIG_YAML.get("first_pass", {}).get("timesteps"), "conditioning_items": conditioning_items, "decode_timestep": PIPELINE_CONFIG_YAML.get("decode_timestep"), "decode_noise_scale": PIPELINE_CONFIG_YAML.get("decode_noise_scale"), "stochastic_sampling": PIPELINE_CONFIG_YAML.get("stochastic_sampling"), "image_cond_noise_scale": 0.15, "is_video": True, "vae_per_channel_normalize": True, "mixed_precision": (PIPELINE_CONFIG_YAML.get("precision") == "mixed_precision"), "offload_to_cpu": False, "enhance_prompt": False}
100
- result_tensor = pipeline_instance(**kwargs).images
101
- 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
102
- 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)
103
- with imageio.get_writer(output_path, fps=VIDEO_FPS, codec='libx264', quality=8) as writer:
104
- for i, frame in enumerate(video_np): progress(i / len(video_np), desc=f"Renderizando frame {i+1}/{len(video_np)}..."); writer.append_data(frame)
105
- return output_path
106
- finally:
107
- pipeline_instance.to('cpu'); gc.collect()
108
- if torch.cuda.is_available(): torch.cuda.empty_cache()
109
-
110
- def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
111
- if not image_path or not os.path.exists(image_path): return None
112
- try:
113
- img = Image.open(image_path).convert("RGB")
114
- img_square = ImageOps.fit(img, (size, size), Image.Resampling.LANCZOS)
115
- output_filename = f"initial_ref_{size}x{size}.png"
116
- output_path = os.path.join(WORKSPACE_DIR, output_filename)
117
- img_square.save(output_path)
118
- return output_path
119
- except Exception as e: raise gr.Error(f"Falha ao processar a imagem de referência: {e}")
120
-
121
- def get_static_scenes_storyboard(num_fragments: int, prompt: str, initial_image_path: str):
122
- if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
123
- if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
124
- genai.configure(api_key=GEMINI_API_KEY)
125
- prompt_file = "prompts/photographer_prompt.txt"
126
- with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
127
- director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments))
128
- model = genai.GenerativeModel('gemini-2.0-flash'); img = Image.open(initial_image_path)
129
- response = model.generate_content([director_prompt, img])
130
- try:
131
- cleaned_response = response.text.strip().replace("```json", "").replace("```", "")
132
- storyboard_data = json.loads(cleaned_response)
133
- return storyboard_data.get("scene_storyboard", [])
134
- except Exception as e: raise gr.Error(f"O Sonhador (Gemini) falhou ao criar o roteiro: {e}. Resposta: {response.text}")
135
-
136
- def run_keyframe_generation(storyboard, initial_ref_image_path, *reference_args):
137
- # ... (código inalterado) ...
138
- if not storyboard:
139
- raise gr.Error("Nenhum roteiro para gerar imagens-chave.")
140
- if not initial_ref_image_path or not os.path.exists(initial_ref_image_path):
141
- raise gr.Error("A imagem de referência principal é obrigatória para iniciar a pintura.")
142
-
143
- num_total_refs = MAX_REFS + 1
144
- ref_paths = list(reference_args[:num_total_refs])
145
- ref_tasks = list(reference_args[num_total_refs:])
146
-
147
- with Image.open(initial_ref_image_path) as img:
148
- width, height = img.size
149
- width, height = (width // 32) * 32, (height // 32) * 32
150
-
151
- keyframe_paths = []
152
- log_history = ""
153
-
154
- try:
155
- dreamo_generator_singleton.to_gpu()
156
-
157
- log_history += f"Pintando Keyframe Inicial (Cena 1/{len(storyboard)})...\n"
158
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
159
-
160
- references_for_first_frame = []
161
- references_for_first_frame.append({'image_np': np.array(Image.open(initial_ref_image_path).convert("RGB")), 'task': 'ip'})
162
- log_history += f" - Usando imagem de referência principal '{os.path.basename(initial_ref_image_path)}' (Tarefa: ip)\n"
163
-
164
- for j in range(1, num_total_refs):
165
- aux_path, aux_task = ref_paths[j], ref_tasks[j]
166
- if aux_path and os.path.exists(aux_path):
167
- references_for_first_frame.append({'image_np': np.array(Image.open(aux_path).convert("RGB")), 'task': aux_task})
168
- log_history += f" - Usando ref. auxiliar: {os.path.basename(aux_path)} (Tarefa: {aux_task})\n"
169
-
170
- first_prompt = storyboard[0]
171
- output_path = os.path.join(WORKSPACE_DIR, "keyframe_1.png")
172
- image = dreamo_generator_singleton.generate_image_with_gpu_management(
173
- reference_items=references_for_first_frame, prompt=first_prompt, width=width, height=height
174
- )
175
- image.save(output_path)
176
- keyframe_paths.append(output_path)
177
- current_ref_image_path = output_path
178
-
179
- for i, prompt in enumerate(storyboard[1:], start=1):
180
- log_history += f"\nPintando Cena Sequencial {i+1}/{len(storyboard)}...\n"
181
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths)}
182
-
183
- reference_items_for_dreamo = []
184
- sequential_ref_task = ref_tasks[0]
185
- reference_items_for_dreamo.append({'image_np': np.array(Image.open(current_ref_image_path).convert("RGB")), 'task': sequential_ref_task})
186
- log_history += f" - Usando ref. sequencial: {os.path.basename(current_ref_image_path)} (Tarefa: {sequential_ref_task})\n"
187
-
188
- for j in range(1, num_total_refs):
189
- aux_path, aux_task = ref_paths[j], ref_tasks[j]
190
- if aux_path and os.path.exists(aux_path):
191
- reference_items_for_dreamo.append({'image_np': np.array(Image.open(aux_path).convert("RGB")), 'task': aux_task})
192
- log_history += f" - Usando ref. auxiliar: {os.path.basename(aux_path)} (Tarefa: {aux_task})\n"
193
-
194
- output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
195
- image = dreamo_generator_singleton.generate_image_with_gpu_management(
196
- reference_items=reference_items_for_dreamo, prompt=prompt, width=width, height=height
197
- )
198
- image.save(output_path)
199
- keyframe_paths.append(output_path)
200
- current_ref_image_path = output_path
201
-
202
- except Exception as e:
203
- raise gr.Error(f"O Pintor (DreamO) encontrou um erro: {e}")
204
- finally:
205
- dreamo_generator_singleton.to_cpu()
206
-
207
- log_history += "\nPintura de todos os keyframes concluída.\n"
208
- yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=keyframe_paths), keyframe_images_state: keyframe_paths}
209
-
210
- ####
211
- # Gera um prompt de movimento para uma transição.
212
- # Agora é flexível: aceita uma única imagem de partida ou uma lista de frames de contexto.
213
- ####
214
- def get_single_motion_prompt(user_prompt: str, story_history: str, start_media_paths: Union[str, List[str]], end_keyframe_path: str, prompt_filename: str):
215
- if not GEMINI_API_KEY:
216
- raise gr.Error("Chave da API Gemini não configurada!")
217
-
218
- if isinstance(start_media_paths, str):
219
- start_media_paths = [start_media_paths]
220
-
221
- uploaded_files = []
222
- try:
223
- genai.configure(api_key=GEMINI_API_KEY)
224
- model = genai.GenerativeModel('gemini-2.0-flash')
225
-
226
- for path in start_media_paths:
227
- print(f"Cineasta: Fazendo upload do arquivo de contexto '{path}'...")
228
- file_to_upload = genai.upload_file(path)
229
-
230
- print(f"Cineasta: Aguardando arquivo '{file_to_upload.name}' ficar ATIVO...")
231
- timeout_seconds = 180
232
- start_time = time.time()
233
-
234
- while file_to_upload.state.name == "PROCESSING":
235
- if time.time() - start_time > timeout_seconds:
236
- raise TimeoutError(f"Tempo de espera para '{file_to_upload.name}' excedido.")
237
- time.sleep(2)
238
- file_to_upload = genai.get_file(name=file_to_upload.name)
239
-
240
- if file_to_upload.state.name != "ACTIVE":
241
- raise gr.Error(f"O arquivo de mídia '{file_to_upload.name}' falhou no processamento. Estado: {file_to_upload.state.name}")
242
-
243
- uploaded_files.append(file_to_upload)
244
-
245
- print(f"Cineasta: Todos os {len(uploaded_files)} arquivos de contexto estão ATIVOS. Gerando prompt...")
246
- end_media = Image.open(end_keyframe_path)
247
-
248
- prompt_file_path = os.path.join(os.path.dirname(__file__), "prompts", prompt_filename)
249
- with open(prompt_file_path, "r", encoding="utf-8") as f:
250
- template = f.read()
251
-
252
- director_prompt = template.format(user_prompt=user_prompt, story_history=story_history)
253
-
254
- model_contents = [director_prompt] + uploaded_files + [end_media]
255
- response = model.generate_content(model_contents)
256
-
257
- cleaned_text = response.text.strip().replace("```json", "").replace("```", "")
258
- motion_data = json.loads(cleaned_text)
259
- return motion_data.get("motion_prompt", "")
260
-
261
- except Exception as e:
262
- response_text = getattr(e, 'text', 'Nenhuma resposta de texto disponível.')
263
- raise gr.Error(f"O Cineasta (Gemini) falhou ao criar o prompt de movimento: {e}. Resposta: {response_text}")
264
-
265
- finally:
266
- for f in uploaded_files:
267
- try:
268
- genai.delete_file(f.name)
269
- except Exception as delete_e:
270
- print(f"Aviso: Falha ao deletar o arquivo temporário {f.name} da API Gemini. Erro: {delete_e}")
271
-
272
- ####
273
- # NOVA FUNÇÃO: Extrai os 3 frames de contexto (vetor de movimento) de um vídeo.
274
- ####
275
- def extract_context_frames(input_video_path: str, fragment_index: int) -> List[str]:
276
- print(f"Editor: Extraindo vetor de frames do fragmento {fragment_index}...")
277
- output_paths = []
278
- try:
279
- command_probe = f"ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=noprint_wrappers=1:nokey=1 \"{input_video_path}\""
280
- result_probe = subprocess.run(command_probe, shell=True, check=True, capture_output=True, text=True)
281
- total_frames = int(result_probe.stdout.strip())
282
-
283
- if total_frames <= CONVERGENCE_FRAMES:
284
- # Se o vídeo for muito curto, apenas retorna o último frame 3 vezes.
285
- frame_indices = [total_frames - 1] * 3
286
- else:
287
- # Frame final, frame a 8 frames de distância, frame a 16 frames de distância
288
- frame_indices = [total_frames - 1 - CONVERGENCE_FRAMES, total_frames - 1 - (CONVERGENCE_FRAMES // 2), total_frames - 1]
289
-
290
- for i, frame_idx in enumerate(frame_indices):
291
- output_path = os.path.join(WORKSPACE_DIR, f"context_{fragment_index}_frame_{i+1}.png")
292
- command_extract = f"ffmpeg -y -v error -i \"{input_video_path}\" -vf \"select='eq(n,{frame_idx})'\" -frames:v 1 \"{output_path}\""
293
- subprocess.run(command_extract, shell=True, check=True)
294
- output_paths.append(output_path)
295
-
296
- print(f"Editor: Vetor de frames extraído para: {output_paths}")
297
- return output_paths
298
- except Exception as e:
299
- error_message = f"Editor Mágico (FFmpeg) falhou ao extrair os frames de contexto: {e}"
300
- if hasattr(e, 'stderr'): error_message += f"\nDetalhes: {e.stderr}"
301
- raise gr.Error(error_message)
302
-
303
- ####
304
- # Orquestra a produção de todos os fragmentos de vídeo com a nova lógica de vetor de frames.
305
- ####
306
- def run_video_production(prompt_geral, keyframe_image_paths, scene_storyboard, seed, cfg, progress=gr.Progress()):
307
- if not keyframe_image_paths or len(keyframe_image_paths) < 2:
308
- raise gr.Error("Pinte pelo menos 2 keyframes na Etapa 2 para produzir as transições.")
309
-
310
- log_history = "\n--- FASE 3/4: A Câmera e o Cineasta estão filmando em sequência just-in-time...\n"
311
- yield {production_log_output: log_history, video_gallery_glitch: []}
312
-
313
- video_fragments = []
314
- start_media_for_prompt = keyframe_image_paths[0]
315
- previous_media_for_ltx = keyframe_image_paths[0]
316
-
317
- story_history = ""
318
- with Image.open(keyframe_image_paths[0]) as img:
319
- width, height = img.size
320
-
321
- num_transitions = len(keyframe_image_paths) - 1
322
- for i in range(num_transitions):
323
- end_keyframe_path = keyframe_image_paths[i+1]
324
- is_first_fragment = (i == 0)
325
- fragment_num = i + 1
326
-
327
- progress(i / num_transitions, desc=f"Planejando Fragmento {fragment_num}/{num_transitions}")
328
-
329
- log_history += f"\n--- FRAGMENTO {fragment_num} ---\n"
330
- log_history += "Cineasta (Gemini) está analisando o contexto de movimento...\n"
331
- yield {production_log_output: log_history}
332
-
333
- if is_first_fragment:
334
- prompt_filename_to_use = "director_motion_prompt.txt"
335
- story_history = f"A história começa com a transição da cena '{scene_storyboard[0]}' para '{scene_storyboard[1]}'."
336
- else:
337
- prompt_filename_to_use = "director_motion_prompt_vector.txt"
338
- story_history += f"\n- Em seguida, a cena muda de '{scene_storyboard[i]}' para '{scene_storyboard[i+1]}'."
339
-
340
- current_motion_prompt = get_single_motion_prompt(prompt_geral, story_history, start_media_for_prompt, end_keyframe_path, prompt_filename_to_use)
341
-
342
- log_history += f"Instrução do Cineasta ({prompt_filename_to_use}): '{current_motion_prompt}'\n"
343
- log_history += f"Filmando transição de '{os.path.basename(previous_media_for_ltx)}' para '{os.path.basename(end_keyframe_path)}'...\n"
344
- yield {production_log_output: log_history}
345
-
346
- # LTX ainda usa apenas uma imagem de partida (o último frame do vídeo anterior)
347
- end_frame_index = VIDEO_TOTAL_FRAMES - CONVERGENCE_FRAMES
348
- conditioning_items_data = [(previous_media_for_ltx, 0, 1.0), (end_keyframe_path, end_frame_index, 1.0)]
349
-
350
- fragment_path = run_ltx_animation(fragment_num, current_motion_prompt, conditioning_items_data, width, height, seed, cfg, progress)
351
- video_fragments.append(fragment_path)
352
-
353
- log_history += f"Fragmento {fragment_num} filmado. Preparando contexto para a próxima cena...\n"
354
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
355
-
356
- # Prepara as entradas para a PRÓXIMA iteração
357
- context_frames = extract_context_frames(fragment_path, fragment_num)
358
- start_media_for_prompt = context_frames # Gemini usará os 3 frames
359
- previous_media_for_ltx = context_frames[-1] # LTX usará apenas o último frame
360
-
361
- log_history += "\nFilmagem de todos os fragmentos de transição concluída.\n"
362
- progress(1.0, desc="Produção Concluída.")
363
- yield {production_log_output: log_history, video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
364
-
365
- def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
366
- # ... (código inalterado) ...
367
- if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
368
- progress(0.2, desc="Aparando fragmentos para transições suaves...");
369
- trimmed_dir = os.path.join(WORKSPACE_DIR, "trimmed"); os.makedirs(trimmed_dir, exist_ok=True)
370
- paths_for_concat = []
371
- try:
372
- for i, path in enumerate(fragment_paths):
373
- if i == len(fragment_paths) - 1:
374
- paths_for_concat.append(path)
375
- continue
376
-
377
- trimmed_path = os.path.join(trimmed_dir, f"fragment_{i}_trimmed.mp4")
378
- probe_cmd = f"ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=noprint_wrappers=1:nokey=1 \"{path}\""
379
- result = subprocess.run(probe_cmd, shell=True, check=True, capture_output=True, text=True)
380
- total_frames = int(result.stdout.strip())
381
- frames_to_keep = total_frames - CONVERGENCE_FRAMES
382
- if frames_to_keep <= 0:
383
- shutil.copyfile(path, trimmed_path)
384
- paths_for_concat.append(trimmed_path)
385
- continue
386
-
387
- trim_cmd = f"ffmpeg -y -v error -i \"{path}\" -vf \"select='lt(n,{frames_to_keep})'\" -c:v libx264 -preset ultrafast -an \"{trimmed_path}\""
388
- subprocess.run(trim_cmd, shell=True, check=True, capture_output=True, text=True)
389
- paths_for_concat.append(trimmed_path)
390
-
391
- progress(0.6, desc="Montando a obra-prima final...")
392
- list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "obra_prima_final.mp4")
393
- with open(list_file_path, "w") as f:
394
- for p in paths_for_concat: f.write(f"file '{os.path.abspath(p)}'\n")
395
- concat_cmd = f"ffmpeg -y -v error -f concat -safe 0 -i \"{list_file_path}\" -c copy \"{final_output_path}\""
396
- subprocess.run(concat_cmd, shell=True, check=True, capture_output=True, text=True)
397
- return final_output_path
398
- except (subprocess.CalledProcessError, ValueError) as e:
399
- error_message = f"FFmpeg falhou durante a pós-produção (corte e concatenação): {e}"
400
- if hasattr(e, 'stderr'): error_message += f"\nDetalhes do erro do FFmpeg: {e.stderr}"
401
- raise gr.Error(error_message)
402
-
403
-
404
- # --- Ato 5: A Interface com o Mundo ---
405
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
406
- gr.Markdown("# NOVINHO-4.4 (Piloto de Testes - Vetor de Frames)\n*By Carlex & Gemini & DreamO*")
407
-
408
- # ... (Interface inalterada) ...
409
- if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
410
- os.makedirs(WORKSPACE_DIR)
411
- Path("examples").mkdir(exist_ok=True)
412
-
413
- scene_storyboard_state = gr.State([])
414
- keyframe_images_state = gr.State([])
415
- fragment_list_state = gr.State([])
416
- prompt_geral_state = gr.State("")
417
- processed_ref_path_state = gr.State("")
418
- visible_references_state = gr.State(0)
419
-
420
- # --- ETAPA 1: O ROTEIRO ---
421
- gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (Sonhador)")
422
- with gr.Row():
423
- with gr.Column(scale=1):
424
- prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
425
- num_fragments_input = gr.Slider(2, 10, 4, step=1, label="Número de Cenas")
426
- image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
427
- director_button = gr.Button("▶️ 1. Gerar Roteiro de Cenas", variant="primary")
428
- with gr.Column(scale=2):
429
- storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado")
430
-
431
- # --- ETAPA 2: OS KEYFRAMES ---
432
- gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (Pintor)")
433
- with gr.Row():
434
- with gr.Column(scale=2):
435
- gr.Markdown("### Controles do Pintor (DreamO)")
436
- gr.Markdown("**Tarefas:** `style` (estilo), `ip` (conteúdo), `id` (identidade).")
437
- ref_image_inputs, ref_task_inputs, aux_ref_rows = [], [], []
438
- with gr.Group():
439
- with gr.Row():
440
- ref_image_inputs.append(gr.Image(label="Referência Sequencial (Automática)", type="filepath", interactive=False))
441
- ref_task_inputs.append(gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa Seq."))
442
- for i in range(MAX_REFS):
443
- with gr.Row(visible=False) as ref_row_aux:
444
- ref_image_inputs.append(gr.Image(label=f"Ref. Auxiliar {i+1}", type="filepath"))
445
- ref_task_inputs.append(gr.Dropdown(choices=["ip", "id", "style"], value="ip", label=f"Tarefa Aux. {i+1}"))
446
- aux_ref_rows.append(ref_row_aux)
447
- with gr.Row():
448
- add_ref_button = gr.Button("➕ Add Ref.")
449
- remove_ref_button = gr.Button("➖ Rem. Ref.")
450
- photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave", variant="primary")
451
- with gr.Column(scale=1):
452
- keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
453
- keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
454
-
455
- # --- ETAPA 3: A PRODUÇÃO ---
456
- gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (Cineasta e Câmera)")
457
- with gr.Row():
458
- with gr.Column(scale=1):
459
- with gr.Row():
460
- seed_number = gr.Number(42, label="Seed")
461
- cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
462
- animator_button = gr.Button("▶️ 3. Produzir Cenas em Vídeo", variant="primary")
463
- production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
464
- with gr.Column(scale=1):
465
- video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados (com sobreposição)", object_fit="contain", height="auto", type="video")
466
-
467
- # --- ETAPA 4: PÓS-PRODUÇÃO ---
468
- gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
469
- editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
470
- final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
471
-
472
- # --- Rodapé Filosófico ---
473
- gr.Markdown(
474
- """
475
- ---
476
- ### A Arquitetura ADUC-SDR: O Esquema Matemático
477
- A geração de vídeo é governada por uma função seccional que define como cada fragmento (`V_i`) é criado, operando em dois regimes distintos:
478
-
479
- ---
480
- #### **FÓRMULA 1: O FRAGMENTO INICIAL (Gênesis, `i=1`)**
481
- *Define a criação do primeiro clipe a partir de imagens estáticas.*
482
-
483
- **Planejamento:** `P_1 = Γ_initial( K_1, K_2, P_geral )`
484
-
485
- **Execução:** `V_1 = Ψ( { (K_1, F_start), (K_2, F_end) }, P_1 )`
486
-
487
- ---
488
- #### **FÓRMULA 2: A CADEIA CAUSAL (Momentum, `i > 1`)**
489
- *Define a criação dos fragmentos subsequentes, garantindo a continuidade através do "eco".*
490
-
491
- **Destilação:** `C_(i-1) = Δ(V_(i-1))`
492
-
493
- **Planejamento:** `P_i = Γ_transition( C_(i-1), K_(i+1), P_geral, H_(i-1) )`
494
-
495
- **Execução:** `V_i = Ψ( { (C_(i-1), F_start), (K_(i+1), F_end) }, P_i )`
496
-
497
- ---
498
- #### **Componentes (O Léxico da Arquitetura):**
499
- - **`V_i`**: Fragmento de Vídeo
500
- - **`K_i`**: Keyframe (Imagem Estática)
501
- - **`C_i`**: "Eco" Causal (Clipe de Vídeo)
502
- - **`P_i`**: Prompt de Movimento
503
- - **`P_geral`**: Prompt Geral (Intenção do Diretor)
504
- - **`H_i`**: Histórico Narrativo
505
- - **`Γ`**: Cineasta (Gerador de Prompt)
506
- - **`Ψ`**: Câmera (Gerador de Vídeo)
507
- - **`Δ`**: Editor (Extrator de "Eco")
508
- - **`F_start`, `F_end`**: Constantes de Frame (Âncoras Temporais)
509
- """
510
- )
511
-
512
-
513
- # --- Ato 6: A Regência (Lógica de Conexão dos Botões) ---
514
- def update_reference_visibility(current_count, action):
515
- if action == "add": new_count = min(MAX_REFS, current_count + 1)
516
- else: new_count = max(0, current_count - 1)
517
- return [new_count] + [gr.update(visible=(i < new_count)) for i in range(MAX_REFS)]
518
-
519
- add_ref_button.click(fn=update_reference_visibility, inputs=[visible_references_state, gr.State("add")], outputs=[visible_references_state] + aux_ref_rows)
520
- remove_ref_button.click(fn=update_reference_visibility, inputs=[visible_references_state, gr.State("remove")], outputs=[visible_references_state] + aux_ref_rows)
521
-
522
- director_button.click(
523
- fn=get_static_scenes_storyboard,
524
- inputs=[num_fragments_input, prompt_input, image_input],
525
- outputs=[scene_storyboard_state]
526
- ).success(
527
- fn=lambda s, p: (s, p),
528
- inputs=[scene_storyboard_state, prompt_input],
529
- outputs=[storyboard_to_show, prompt_geral_state]
530
- ).success(
531
- fn=process_image_to_square,
532
- inputs=[image_input],
533
- outputs=[processed_ref_path_state]
534
- ).success(
535
- fn=lambda p: p,
536
- inputs=[processed_ref_path_state],
537
- outputs=[ref_image_inputs[0]]
538
- )
539
-
540
- photographer_button.click(
541
- fn=run_keyframe_generation,
542
- inputs=[scene_storyboard_state, processed_ref_path_state] + ref_image_inputs + ref_task_inputs,
543
- outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
544
- )
545
-
546
- animator_button.click(
547
- fn=run_video_production,
548
- inputs=[prompt_geral_state, keyframe_images_state, scene_storyboard_state, seed_number, cfg_slider],
549
- outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
550
- )
551
-
552
- editor_button.click(
553
- fn=concatenate_and_trim_masterpiece,
554
- inputs=[fragment_list_state],
555
- outputs=[final_video_output]
556
- )
557
-
558
- if __name__ == "__main__":
559
- demo.queue().launch(server_name="0.0.0.0", share=True)