Carlex22222 commited on
Commit
aabed75
·
verified ·
1 Parent(s): d4ae81a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -87
app.py CHANGED
@@ -2,8 +2,7 @@
2
  #
3
  # Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
4
  #
5
- # Versão 6.0.0 (Clean, Interactive & Consolidated UI)
6
- # + Seção de Teste para LlamaScoutManager
7
 
8
  import gradio as gr
9
  import yaml
@@ -13,18 +12,12 @@ import sys
13
  import shutil
14
  import time
15
  import json
16
- # --- NOVAS IMPORTAÇÕES PARA O TESTE ---
17
- import cv2
18
- from PIL import Image
19
- from typing import List
20
 
21
  # --- 1. IMPORTAÇÃO DO FRAMEWORK E CONFIGURAÇÃO ---
22
  import aduc_framework
23
  from aduc_framework.types import PreProductionParams, ProductionParams
24
- # --- IMPORTAÇÃO DO NOSSO NOVO MANAGER PARA TESTE ---
25
- from aduc_framework.managers import llama_scout_manager_singleton
26
 
27
- # (O resto da sua configuração de tema e logging permanece exatamente igual)
28
  cinematic_theme = gr.themes.Base(
29
  primary_hue=gr.themes.colors.indigo,
30
  secondary_hue=gr.themes.colors.purple,
@@ -40,6 +33,8 @@ cinematic_theme = gr.themes.Base(
40
  block_title_text_color="#FFFFFF", input_background_fill="#374151",
41
  input_border_color="#4B5563", input_placeholder_color="#9CA3AF",
42
  )
 
 
43
  LOG_FILE_PATH = "aduc_log.txt"
44
  if os.path.exists(LOG_FILE_PATH): os.remove(LOG_FILE_PATH)
45
  log_format = '%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s] - %(message)s'
@@ -64,13 +59,12 @@ except Exception as e:
64
  logger.critical(f"ERRO CRÍTICO durante a inicialização: {e}", exc_info=True)
65
  with gr.Blocks() as demo:
66
  gr.Markdown("# ERRO CRÍTICO NA INICIALIZAÇÃO")
67
- gr.Markdown("Não foi possível iniciar o Aduc Framework. Verifique os logs.")
68
  gr.Textbox(value=str(e), label="Detalhes do Erro", lines=10)
69
  demo.launch()
70
  exit()
71
 
72
- # --- 2. FUNÇÕES WRAPPER (UI <-> FRAMEWORK) - LÓGICA ORIGINAL ---
73
- # (Todas as suas funções wrapper originais permanecem aqui, inalteradas)
74
  def run_pre_production_wrapper(prompt, num_keyframes, ref_files, resolution_str, duration_per_fragment, progress=gr.Progress()):
75
  if not ref_files: raise gr.Error("Por favor, forneça pelo menos uma imagem de referência.")
76
  target_resolution = int(resolution_str.split('x')[0])
@@ -101,7 +95,6 @@ def run_original_production_wrapper(current_state_dict, trim_percent, handler_st
101
  generation_state_holder: updated_state.model_dump(),
102
  }
103
 
104
- # (As outras funções wrapper: run_upscaler, run_hd, run_audio, get_log_content continuam aqui...)
105
  def run_upscaler_wrapper(source_video, latent_paths, chunk_size, progress=gr.Progress()):
106
  if not source_video or not latent_paths: raise gr.Error("Fonte de vídeo ou latentes originais não encontrados para o Upscaler.")
107
  yield {final_video_output: gr.update(label="Pós-Produção: Upscaler Latente...")}
@@ -132,48 +125,8 @@ def get_log_content():
132
  with open(LOG_FILE_PATH, "r", encoding="utf-8") as f: return f.read()
133
  except FileNotFoundError: return "Arquivo de log ainda não criado."
134
 
135
- # --- NOVAS FUNÇÕES DE TESTE PARA O LLAMA SCOUT ---
136
- def extract_frames_from_video(video_path: str, fps: int) -> List[Image.Image]:
137
- if not video_path: return []
138
- frames = []
139
- cap = cv2.VideoCapture(video_path)
140
- if not cap.isOpened():
141
- logger.error(f"Não foi possível abrir o vídeo: {video_path}")
142
- return []
143
- video_fps_original = cap.get(cv2.CAP_PROP_FPS) or 30
144
- frame_interval = max(1, int(video_fps_original / fps))
145
- frame_count = 0
146
- while True:
147
- ret, frame = cap.read()
148
- if not ret: break
149
- if frame_count % frame_interval == 0:
150
- frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
151
- frame_count += 1
152
- cap.release()
153
- logger.info(f"Extraídos {len(frames)} frames do vídeo a {fps} FPS para teste.")
154
- return frames
155
-
156
- def analyze_video_wrapper(video_path, question, fps, progress=gr.Progress(track_tqdm=True)):
157
- if not video_path: return "Por favor, envie um vídeo para o teste."
158
- if not question: return "Por favor, digite uma pergunta para o teste."
159
-
160
- pil_images = extract_frames_from_video(video_path, int(fps))
161
- if not pil_images: return "Erro: Não foi possível extrair frames do vídeo de teste."
162
-
163
- return llama_scout_manager_singleton.analyze_sequence(pil_images, question, progress_callback=progress)
164
-
165
- def analyze_images_wrapper(image_paths, question, progress=gr.Progress(track_tqdm=True)):
166
- if not image_paths: return "Por favor, envie imagens para o teste."
167
- if not question: return "Por favor, digite uma pergunta para o teste."
168
-
169
- # Em Gradio, o componente File com file_count="multiple" e type="filepath" retorna uma lista de strings
170
- pil_images = [Image.open(path) for path in image_paths]
171
- return llama_scout_manager_singleton.analyze_sequence(pil_images, question, progress_callback=progress)
172
-
173
-
174
  # --- 3. DEFINIÇÃO DA UI ---
175
  with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
176
- # (Seus estados e a UI original do ADUC-SDR permanecem aqui, inalterados)
177
  generation_state_holder = gr.State(value={})
178
  original_latents_paths_state = gr.State(value=[])
179
  current_source_video_state = gr.State(value=None)
@@ -184,7 +137,7 @@ with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
184
  with gr.Row():
185
  lang_selector = gr.Radio(["🇧🇷", "🇺🇸", "🇨🇳"], value="🇧🇷", label="Idioma / Language")
186
  resolution_selector = gr.Radio(["512x512", "768x768", "1024x1024"], value="512x512", label="Resolução Base")
187
- ref_image_input = gr.File(label="Grupo de Imagens do Usuário", file_count="multiple", file_types=["image"])
188
  with gr.Row():
189
  num_keyframes_slider = gr.Slider(minimum=2, maximum=42, value=4, step=2, label="Número de Cenas-Chave (Par)")
190
  duration_per_fragment_slider = gr.Slider(label="Duração de cada Clipe (s)", minimum=2.0, maximum=10.0, value=4.0, step=0.1)
@@ -218,26 +171,7 @@ with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
218
  log_display = gr.Textbox(label="Log da Sessão", lines=20, interactive=False, autoscroll=True)
219
  update_log_button = gr.Button("Atualizar Log")
220
 
221
- # --- NOVA SEÇÃO DE TESTE PARA O LLAMA SCOUT ---
222
- with gr.Accordion("🧪 Playground de Teste do Llama Scout Manager", open=False) as scout_test_accordion:
223
- gr.Markdown("Esta seção é para testar o `LlamaScoutManager` de forma isolada, sem interferir no fluxo principal do ADUC-SDR.")
224
- with gr.Tabs():
225
- with gr.TabItem("Teste de Vídeo"):
226
- with gr.Row():
227
- scout_video_input = gr.Video(label="Vídeo para Teste")
228
- scout_fps_slider = gr.Slider(minimum=1, maximum=8, value=2, step=1, label="FPS para Análise")
229
- scout_video_question = gr.Textbox(label="Pergunta sobre o vídeo", placeholder="Ex: Analise a cinemática desta cena.")
230
- scout_video_button = gr.Button("Analisar Vídeo com Llama Scout", variant="secondary")
231
- scout_video_output = gr.Textbox(label="Resultado da Análise", lines=10)
232
-
233
- with gr.TabItem("Teste de Imagens"):
234
- scout_image_input = gr.File(label="Imagens para Teste", file_count="multiple", type="filepath", file_types=["image"])
235
- scout_image_question = gr.Textbox(label="Pergunta sobre as imagens", placeholder="Ex: Qual a progressão narrativa nestas imagens?")
236
- scout_image_button = gr.Button("Analisar Imagens com Llama Scout", variant="secondary")
237
- scout_image_output = gr.Textbox(label="Resultado da Análise", lines=10)
238
-
239
  # --- 4. CONEXÕES DE EVENTOS ---
240
- # (Conexões originais do ADUC-SDR)
241
  storyboard_and_keyframes_button.click(fn=run_pre_production_wrapper, inputs=[prompt_input, num_keyframes_slider, ref_image_input, resolution_selector, duration_per_fragment_slider], outputs=[generation_state_holder, storyboard_output, keyframe_gallery, step3_accordion])
242
  produce_original_button.click(fn=run_original_production_wrapper, inputs=[generation_state_holder, trim_percent_slider, handler_strength, dest_strength, guidance_scale_slider, stg_scale_slider, inference_steps_slider], outputs=[final_video_output, step4_accordion, original_latents_paths_state, current_source_video_state, generation_state_holder])
243
  run_upscaler_button.click(fn=run_upscaler_wrapper, inputs=[current_source_video_state, original_latents_paths_state, upscaler_chunk_size_slider], outputs=[final_video_output, current_source_video_state])
@@ -246,22 +180,9 @@ with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
246
  generation_state_holder.change(fn=lambda state: state, inputs=generation_state_holder, outputs=generation_data_output)
247
  update_log_button.click(fn=get_log_content, inputs=[], outputs=[log_display])
248
 
249
- # --- NOVAS CONEXÕES PARA O PLAYGROUND DE TESTE ---
250
- scout_video_button.click(
251
- fn=analyze_video_wrapper,
252
- inputs=[scout_video_input, scout_video_question, scout_fps_slider],
253
- outputs=scout_video_output
254
- )
255
- scout_image_button.click(
256
- fn=analyze_images_wrapper,
257
- inputs=[scout_image_input, scout_image_question],
258
- outputs=scout_image_output
259
- )
260
-
261
  # --- 5. INICIALIZAÇÃO DA APLICAÇÃO ---
262
  if __name__ == "__main__":
263
- if os.path.exists(WORKSPACE_DIR):
264
- shutil.rmtree(WORKSPACE_DIR)
265
  os.makedirs(WORKSPACE_DIR)
266
  logger.info("Aplicação Gradio iniciada. Lançando interface...")
267
  demo.queue().launch()
 
2
  #
3
  # Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
4
  #
5
+ # Versão 6.0.0 (Clean, Interactive & Consolidated UI) - Final
 
6
 
7
  import gradio as gr
8
  import yaml
 
12
  import shutil
13
  import time
14
  import json
 
 
 
 
15
 
16
  # --- 1. IMPORTAÇÃO DO FRAMEWORK E CONFIGURAÇÃO ---
17
  import aduc_framework
18
  from aduc_framework.types import PreProductionParams, ProductionParams
 
 
19
 
20
+ # Configuração de Tema Cinemático
21
  cinematic_theme = gr.themes.Base(
22
  primary_hue=gr.themes.colors.indigo,
23
  secondary_hue=gr.themes.colors.purple,
 
33
  block_title_text_color="#FFFFFF", input_background_fill="#374151",
34
  input_border_color="#4B5563", input_placeholder_color="#9CA3AF",
35
  )
36
+
37
+ # Configuração de Logging
38
  LOG_FILE_PATH = "aduc_log.txt"
39
  if os.path.exists(LOG_FILE_PATH): os.remove(LOG_FILE_PATH)
40
  log_format = '%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s] - %(message)s'
 
59
  logger.critical(f"ERRO CRÍTICO durante a inicialização: {e}", exc_info=True)
60
  with gr.Blocks() as demo:
61
  gr.Markdown("# ERRO CRÍTICO NA INICIALIZAÇÃO")
62
+ gr.Markdown("Não foi possível iniciar o Aduc Framework. Verifique os logs para mais detalhes.")
63
  gr.Textbox(value=str(e), label="Detalhes do Erro", lines=10)
64
  demo.launch()
65
  exit()
66
 
67
+ # --- 2. FUNÇÕES WRAPPER (UI <-> FRAMEWORK) ---
 
68
  def run_pre_production_wrapper(prompt, num_keyframes, ref_files, resolution_str, duration_per_fragment, progress=gr.Progress()):
69
  if not ref_files: raise gr.Error("Por favor, forneça pelo menos uma imagem de referência.")
70
  target_resolution = int(resolution_str.split('x')[0])
 
95
  generation_state_holder: updated_state.model_dump(),
96
  }
97
 
 
98
  def run_upscaler_wrapper(source_video, latent_paths, chunk_size, progress=gr.Progress()):
99
  if not source_video or not latent_paths: raise gr.Error("Fonte de vídeo ou latentes originais não encontrados para o Upscaler.")
100
  yield {final_video_output: gr.update(label="Pós-Produção: Upscaler Latente...")}
 
125
  with open(LOG_FILE_PATH, "r", encoding="utf-8") as f: return f.read()
126
  except FileNotFoundError: return "Arquivo de log ainda não criado."
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  # --- 3. DEFINIÇÃO DA UI ---
129
  with gr.Blocks(theme=cinematic_theme, css="style.css") as demo:
 
130
  generation_state_holder = gr.State(value={})
131
  original_latents_paths_state = gr.State(value=[])
132
  current_source_video_state = gr.State(value=None)
 
137
  with gr.Row():
138
  lang_selector = gr.Radio(["🇧🇷", "🇺🇸", "🇨🇳"], value="🇧🇷", label="Idioma / Language")
139
  resolution_selector = gr.Radio(["512x512", "768x768", "1024x1024"], value="512x512", label="Resolução Base")
140
+ ref_image_input = gr.File(label="Grupo de Imagens do Usuário", file_count="multiple", file_types=["image"], type="filepath")
141
  with gr.Row():
142
  num_keyframes_slider = gr.Slider(minimum=2, maximum=42, value=4, step=2, label="Número de Cenas-Chave (Par)")
143
  duration_per_fragment_slider = gr.Slider(label="Duração de cada Clipe (s)", minimum=2.0, maximum=10.0, value=4.0, step=0.1)
 
171
  log_display = gr.Textbox(label="Log da Sessão", lines=20, interactive=False, autoscroll=True)
172
  update_log_button = gr.Button("Atualizar Log")
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  # --- 4. CONEXÕES DE EVENTOS ---
 
175
  storyboard_and_keyframes_button.click(fn=run_pre_production_wrapper, inputs=[prompt_input, num_keyframes_slider, ref_image_input, resolution_selector, duration_per_fragment_slider], outputs=[generation_state_holder, storyboard_output, keyframe_gallery, step3_accordion])
176
  produce_original_button.click(fn=run_original_production_wrapper, inputs=[generation_state_holder, trim_percent_slider, handler_strength, dest_strength, guidance_scale_slider, stg_scale_slider, inference_steps_slider], outputs=[final_video_output, step4_accordion, original_latents_paths_state, current_source_video_state, generation_state_holder])
177
  run_upscaler_button.click(fn=run_upscaler_wrapper, inputs=[current_source_video_state, original_latents_paths_state, upscaler_chunk_size_slider], outputs=[final_video_output, current_source_video_state])
 
180
  generation_state_holder.change(fn=lambda state: state, inputs=generation_state_holder, outputs=generation_data_output)
181
  update_log_button.click(fn=get_log_content, inputs=[], outputs=[log_display])
182
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  # --- 5. INICIALIZAÇÃO DA APLICAÇÃO ---
184
  if __name__ == "__main__":
185
+ if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
 
186
  os.makedirs(WORKSPACE_DIR)
187
  logger.info("Aplicação Gradio iniciada. Lançando interface...")
188
  demo.queue().launch()