Carlexx commited on
Commit
a5af709
·
verified ·
1 Parent(s): b68c001

Upload ai_studio_code (82).py

Browse files
Files changed (1) hide show
  1. ai_studio_code (82).py +284 -0
ai_studio_code (82).py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ... (cabeçalho completo)
4
+
5
+ # --- app.py (NOVIM-5.5: O Fator Humano) ---
6
+
7
+ # --- Ato 1: A Convocação da Orquestra (Importações) ---
8
+ import gradio as gr
9
+ import torch
10
+ import os
11
+ import yaml
12
+ from PIL import Image, ImageOps, ExifTags
13
+ import shutil
14
+ import gc
15
+ import subprocess
16
+ import google.generativeai as genai
17
+ import numpy as np
18
+ import imageio
19
+ from pathlib import Path
20
+ import huggingface_hub
21
+ import json
22
+ import time
23
+
24
+ from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
25
+ from dreamo_helpers import dreamo_generator_singleton
26
+
27
+ # --- Ato 2: A Preparação do Palco (Configurações) ---
28
+ config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
29
+ with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
30
+
31
+ LTX_REPO = "Lightricks/LTX-Video"
32
+ models_dir = "downloaded_models_gradio"
33
+ Path(models_dir).mkdir(parents=True, exist_ok=True)
34
+ WORKSPACE_DIR = "aduc_workspace"
35
+ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
36
+
37
+ VIDEO_FPS = 24
38
+ TARGET_RESOLUTION = 420
39
+ MAX_KEYFRAMES_UI = 10 # Limite de abas de keyframe na UI
40
+
41
+ print("Criando pipelines LTX na CPU (estado de repouso)...")
42
+ 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)
43
+ pipeline_instance = create_ltx_video_pipeline(
44
+ ckpt_path=distilled_model_actual_path,
45
+ precision=PIPELINE_CONFIG_YAML["precision"],
46
+ text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
47
+ sampler=PIPELINE_CONFIG_YAML["sampler"],
48
+ device='cpu'
49
+ )
50
+ print("Modelos LTX prontos (na CPU).")
51
+
52
+
53
+ # --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
54
+
55
+ def robust_json_parser(raw_text: str) -> dict:
56
+ try:
57
+ start_index = raw_text.find('{'); end_index = raw_text.rfind('}')
58
+ if start_index != -1 and end_index != -1 and end_index > start_index:
59
+ json_str = raw_text[start_index : end_index + 1]; return json.loads(json_str)
60
+ else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
61
+ except json.JSONDecodeError as e: raise ValueError(f"Falha ao decodificar JSON: {e}")
62
+
63
+ def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
64
+ if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
65
+ if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
66
+ prompt_file = "prompts/unified_storyboard_prompt.txt"
67
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
68
+ director_prompt = template.format(user_prompt=prompt, num_fragments=int(num_fragments), image_metadata="")
69
+ genai.configure(api_key=GEMINI_API_KEY)
70
+ model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(initial_image_path)
71
+ response = model.generate_content([director_prompt, img])
72
+ try:
73
+ storyboard_data = robust_json_parser(response.text)
74
+ storyboard = storyboard_data.get("scene_storyboard", [])
75
+ 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)}")
76
+ return storyboard
77
+ except Exception as e: raise gr.Error(f"O Roteirista (Gemini) falhou: {e}. Resposta: {response.text}")
78
+
79
+ def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str) -> str:
80
+ genai.configure(api_key=GEMINI_API_KEY)
81
+ prompt_file = "prompts/img2img_evolution_prompt.txt"
82
+ with open(os.path.join(os.path.dirname(__file__), prompt_file), "r", encoding="utf-8") as f: template = f.read()
83
+ director_prompt = template.format(target_scene_description=target_scene_description)
84
+ model = genai.GenerativeModel('gemini-1.5-flash'); img = Image.open(previous_image_path)
85
+ response = model.generate_content([director_prompt, "Previous Image:", img])
86
+ return response.text.strip().replace("\"", "")
87
+
88
+ def run_keyframe_generation(storyboard, ref_images_tasks, progress=gr.Progress()):
89
+ if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
90
+ initial_ref_image_path = ref_images_tasks[0]['image']
91
+ 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.")
92
+ log_history = ""; keyframe_paths = []
93
+ try:
94
+ pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
95
+ dreamo_generator_singleton.to_gpu()
96
+ with Image.open(initial_ref_image_path) as img: width, height = (img.width // 32) * 32, (img.height // 32) * 32
97
+ current_ref_image_path = initial_ref_image_path
98
+ for i, scene_description in enumerate(storyboard):
99
+ progress(i / len(storyboard), desc=f"Pintando Keyframe {i+1}/{len(storyboard)}")
100
+ log_history += f"\n--- PINTANDO KEYFRAME {i+1}/{len(storyboard)} ---\n"
101
+ dreamo_prompt = get_dreamo_prompt_for_transition(current_ref_image_path, scene_description)
102
+ reference_items = []
103
+ for item in ref_images_tasks:
104
+ if item['image'] and os.path.exists(item['image']):
105
+ reference_items.append({'image_np': np.array(Image.open(item['image']).convert("RGB")), 'task': item['task']})
106
+ log_history += f" - Roteiro: '{scene_description}'\n - Usando {len(reference_items)} referências visuais.\n - Prompt do D.A.: \"{dreamo_prompt}\"\n"
107
+ yield {keyframe_log_output: gr.update(value=log_history)}
108
+ output_path = os.path.join(WORKSPACE_DIR, f"keyframe_{i+1}.png")
109
+ image = dreamo_generator_singleton.generate_image_with_gpu_management(reference_items=reference_items, prompt=dreamo_prompt, width=width, height=height)
110
+ image.save(output_path)
111
+ keyframe_paths.append(output_path); current_ref_image_path = output_path
112
+ except Exception as e: raise gr.Error(f"O Pintor (DreamO) ou Diretor de Arte (Gemini) falhou: {e}")
113
+ finally: dreamo_generator_singleton.to_cpu(); gc.collect(); torch.cuda.empty_cache()
114
+ log_history += "\nPintura de todos os keyframes concluída.\n"
115
+ yield {keyframe_log_output: gr.update(value=log_history), keyframe_images_state: keyframe_paths}
116
+
117
+ def get_motion_prompt(user_prompt, start_path, end_path, scene_desc):
118
+ return f"A smooth, cinematic transition from the start image towards the end image, focusing on: {scene_desc}"
119
+
120
+ def run_video_production(
121
+ video_duration_seconds, video_fps, end_cond_strength,
122
+ prompt_geral, keyframe_paths_from_ui, scene_storyboard, cfg,
123
+ progress=gr.Progress()
124
+ ):
125
+ valid_keyframes = [p for p in keyframe_paths_from_ui if p is not None and os.path.exists(p)]
126
+ if not valid_keyframes or len(valid_keyframes) < 2: raise gr.Error("São necessários pelo menos 2 keyframes válidos para produzir um vídeo.")
127
+
128
+ log_history = "\n--- FASE 3: Iniciando Produção...\n"
129
+ yield {production_log_output: log_history, video_gallery_glitch: []}
130
+
131
+ video_total_frames = int(video_duration_seconds * video_fps)
132
+ seed = int(time.time())
133
+ try:
134
+ pipeline_instance.to('cuda')
135
+ video_fragments = []; kinetic_memory_path = valid_keyframes[0]
136
+ with Image.open(kinetic_memory_path) as img: width, height = img.size
137
+
138
+ for i in range(len(valid_keyframes) - 1):
139
+ fragment_num = i + 1
140
+ progress(i / (len(valid_keyframes) - 1), desc=f"Filmando Fragmento {fragment_num}")
141
+
142
+ start_path = kinetic_memory_path
143
+ destination_path = valid_keyframes[i+1]
144
+
145
+ motion_prompt = get_motion_prompt(prompt_geral, start_path, destination_path, scene_storyboard[i])
146
+
147
+ conditioning_items_data = [(start_path, 0, 1.0), (destination_path, video_total_frames - 1, end_cond_strength)]
148
+
149
+ fragment_path, _ = run_ltx_animation(
150
+ current_fragment_index=fragment_num, motion_prompt=motion_prompt,
151
+ conditioning_items_data=conditioning_items_data, width=width, height=height,
152
+ seed=seed, cfg=cfg, progress=progress,
153
+ video_total_frames=video_total_frames, video_fps=video_fps, use_attention_slicing=True, num_inference_steps=30
154
+ )
155
+
156
+ video_fragments.append(fragment_path)
157
+ eco_output_path = os.path.join(WORKSPACE_DIR, f"eco_from_frag_{fragment_num}.png")
158
+ kinetic_memory_path = extract_last_frame_as_image(fragment_path, eco_output_path)
159
+
160
+ log_history += f"Fragmento {fragment_num} concluído.\n"
161
+ yield {production_log_output: log_history, video_gallery_glitch: video_fragments}
162
+
163
+ yield {production_log_output: log_history + "\nProdução concluída.", video_gallery_glitch: video_fragments, fragment_list_state: video_fragments}
164
+ finally:
165
+ pipeline_instance.to('cpu'); gc.collect(); torch.cuda.empty_cache()
166
+
167
+ def concatenate_and_trim_masterpiece(fragment_paths: list, progress=gr.Progress()):
168
+ if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
169
+ progress(0.5, desc="Montando a obra-prima final...");
170
+ try:
171
+ list_file_path = os.path.join(WORKSPACE_DIR, "concat_list.txt"); final_output_path = os.path.join(WORKSPACE_DIR, "masterpiece_final.mp4")
172
+ with open(list_file_path, "w") as f:
173
+ for p in fragment_paths: f.write(f"file '{os.path.abspath(p)}'\n")
174
+ 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)
175
+ progress(1.0, desc="Montagem concluída!")
176
+ return final_output_path
177
+ except subprocess.CalledProcessError as e: raise gr.Error(f"FFmpeg falhou na concatenação final: {e.stderr}")
178
+
179
+ # ... (Outras funções utilitárias como process_image_to_square, run_ltx_animation, etc. aqui)
180
+
181
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
182
+ gr.Markdown("# NOVIM-5.5 (O Fator Humano)\n*By Carlex & Gemini & DreamO*")
183
+ if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
184
+ os.makedirs(WORKSPACE_DIR)
185
+
186
+ scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
187
+ prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
188
+
189
+ gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
190
+ with gr.Row():
191
+ with gr.Column(scale=1):
192
+ prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
193
+ num_fragments_input = gr.Slider(2, MAX_KEYFRAMES_UI, 4, step=1, label="Número de Atos (Keyframes)")
194
+ image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
195
+ director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
196
+ with gr.Column(scale=2):
197
+ storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado")
198
+
199
+ gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
200
+ with gr.Row():
201
+ with gr.Column(scale=2):
202
+ with gr.Row():
203
+ ref1_image = gr.Image(label="Referência Principal (Conteúdo/ID)", type="filepath")
204
+ ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Ref. Principal")
205
+ with gr.Row():
206
+ ref2_image = gr.Image(label="Referência Secundária (Opcional)", type="filepath")
207
+ ref2_task = gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa da Ref. Secundária")
208
+ photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
209
+ keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=10, interactive=False)
210
+ with gr.Column(scale=1):
211
+ gr.Markdown("### Painel de Edição de Keyframes")
212
+ keyframe_ui_slots = []
213
+ keyframe_ui_tabs_visibility = []
214
+ with gr.Tabs() as keyframe_tabs:
215
+ for i in range(MAX_KEYFRAMES_UI):
216
+ with gr.TabItem(f"Keyframe {i+1}", visible=(i<2)) as keyframe_tab:
217
+ keyframe_ui_slots.append(gr.Image(label=f"Conteúdo do Keyframe {i+1}", type="filepath", interactive=True))
218
+ keyframe_ui_tabs_visibility.append(keyframe_tab)
219
+
220
+ gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
221
+ with gr.Row():
222
+ with gr.Column(scale=1):
223
+ cfg_slider = gr.Slider(1.0, 10.0, 7.5, step=0.1, label="CFG")
224
+ end_cond_strength_slider = gr.Slider(label="Força de Convergência do Destino", minimum=0.1, maximum=1.0, value=1.0, step=0.05)
225
+ with gr.Accordion("Controles Avançados de Timing", open=False):
226
+ video_duration_slider = gr.Slider(label="Duração da Cena (segundos)", minimum=2.0, maximum=10.0, value=4.0, step=0.5)
227
+ video_fps_slider = gr.Slider(label="FPS do Vídeo", minimum=12, maximum=36, value=VIDEO_FPS, step=1)
228
+ animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
229
+ production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
230
+ with gr.Column(scale=1):
231
+ video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados", object_fit="contain", height="auto", type="video")
232
+
233
+ gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
234
+ editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
235
+ final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
236
+
237
+ def process_and_update_storyboard(num_fragments, prompt, image_path):
238
+ processed_path = process_image_to_square(image_path)
239
+ if not processed_path: raise gr.Error("A imagem de referência é inválida.")
240
+ storyboard = run_storyboard_generation(num_fragments, prompt, processed_path)
241
+ tab_updates = [gr.update(visible=(i < num_fragments)) for i in range(MAX_KEYFRAMES_UI)]
242
+ return storyboard, prompt, processed_path, storyboard, processed_path, *tab_updates
243
+
244
+ director_button.click(
245
+ fn=process_and_update_storyboard,
246
+ inputs=[num_fragments_input, prompt_input, image_input],
247
+ outputs=[scene_storyboard_state, prompt_geral_state, processed_ref_path_state, storyboard_to_show, ref1_image] + keyframe_ui_tabs_visibility
248
+ )
249
+
250
+ def run_keyframe_generation_wrapper(storyboard, ref1_img, ref1_tsk, ref2_img, ref2_tsk, progress=gr.Progress()):
251
+ ref_data = [{'image': ref1_img, 'task': ref1_tsk}, {'image': ref2_img, 'task': ref2_tsk}]
252
+ final_update = {}
253
+ for update in run_keyframe_generation(storyboard, ref_data, progress):
254
+ final_update = update
255
+ final_paths = final_update.get('keyframe_images_state', [])
256
+ updates = [gr.update(value=final_paths[i] if i < len(final_paths) else None) for i in range(MAX_KEYFRAMES_UI)]
257
+ return final_update.get('keyframe_log_output', ''), final_paths, *updates
258
+
259
+ photographer_button.click(
260
+ fn=run_keyframe_generation_wrapper,
261
+ inputs=[scene_storyboard_state, ref1_image, ref1_task, ref2_image, ref2_task],
262
+ outputs=[keyframe_log_output, keyframe_images_state] + keyframe_ui_slots
263
+ )
264
+
265
+ # Coleta os inputs para a produção de vídeo, incluindo os keyframes das abas
266
+ video_prod_inputs = [
267
+ video_duration_slider, video_fps_slider, end_cond_strength_slider,
268
+ prompt_geral_state, scene_storyboard_state, cfg_slider
269
+ ] + keyframe_ui_slots
270
+
271
+ animator_button.click(
272
+ fn=lambda *args: run_video_production(*args),
273
+ inputs=video_prod_inputs,
274
+ outputs=[production_log_output, video_gallery_glitch, fragment_list_state]
275
+ )
276
+
277
+ editor_button.click(
278
+ fn=concatenate_and_trim_masterpiece,
279
+ inputs=[fragment_list_state],
280
+ outputs=[final_video_output]
281
+ )
282
+
283
+ if __name__ == "__main__":
284
+ demo.queue().launch(server_name="0.0.0.0", share=True)