gdms commited on
Commit
f77d0ec
·
1 Parent(s): 75ce402

processador de imagem chamando GPT, mas falhando na contagem

Browse files
Files changed (2) hide show
  1. tool_audio_extractor.py +16 -3
  2. tool_video_analyzer.py +23 -7
tool_audio_extractor.py CHANGED
@@ -10,8 +10,10 @@ import base64
10
  import time
11
  import json
12
  import re
 
13
  from openai import OpenAI
14
 
 
15
  # --- Configurações (Substitua os placeholders) ---
16
  VIDEO_URL = "https://www.youtube.com/watch?v=1htKBjuUWec" # Substitua pela URL do vídeo do YouTube
17
  OUTPUT_DIR = "./audio_analysis_output" # Diretório para salvar o áudio
@@ -25,11 +27,23 @@ if VIDEO_URL == "URL_DO_SEU_VIDEO_AQUI":
25
 
26
  # --- Funções ---
27
 
28
- def create_output_directory():
29
  """Cria o diretório de saída se não existir."""
30
  if not os.path.exists(OUTPUT_DIR):
31
  os.makedirs(OUTPUT_DIR)
32
  print(f"Diretório criado: {OUTPUT_DIR}")
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def retirar_sufixo_codec_arquivo(directory) -> None:
35
  for filename in os.listdir(directory):
@@ -110,8 +124,7 @@ def extract_text_from_audio() -> str:
110
  # --- Atualização do Bloco Principal ---
111
  # (Adicionar inicialização do cliente OpenAI e o loop de análise)
112
  if __name__ == "__main__":
113
- create_output_directory()
114
-
115
  # Etapa 1: Baixar o vídeo
116
  video_downloaded_or_exists = False
117
  if VIDEO_URL != "URL_DO_SEU_VIDEO_AQUI":
 
10
  import time
11
  import json
12
  import re
13
+ import shutil
14
  from openai import OpenAI
15
 
16
+
17
  # --- Configurações (Substitua os placeholders) ---
18
  VIDEO_URL = "https://www.youtube.com/watch?v=1htKBjuUWec" # Substitua pela URL do vídeo do YouTube
19
  OUTPUT_DIR = "./audio_analysis_output" # Diretório para salvar o áudio
 
27
 
28
  # --- Funções ---
29
 
30
+ def create_or_clear_output_directory():
31
  """Cria o diretório de saída se não existir."""
32
  if not os.path.exists(OUTPUT_DIR):
33
  os.makedirs(OUTPUT_DIR)
34
  print(f"Diretório criado: {OUTPUT_DIR}")
35
+ else:
36
+ # Limpa todos os arquivos e subdiretórios
37
+ for filename in os.listdir(OUTPUT_DIR):
38
+ file_path = os.path.join(OUTPUT_DIR, filename)
39
+ try:
40
+ if os.path.isfile(file_path) or os.path.islink(file_path):
41
+ os.unlink(file_path)
42
+ elif os.path.isdir(file_path):
43
+ shutil.rmtree(file_path)
44
+ except Exception as e:
45
+ print(f"Erro ao excluir {file_path}: {e}")
46
+ print(f"Diretório limpo: {OUTPUT_DIR}")
47
 
48
  def retirar_sufixo_codec_arquivo(directory) -> None:
49
  for filename in os.listdir(directory):
 
124
  # --- Atualização do Bloco Principal ---
125
  # (Adicionar inicialização do cliente OpenAI e o loop de análise)
126
  if __name__ == "__main__":
127
+ create_or_clear_output_directory()
 
128
  # Etapa 1: Baixar o vídeo
129
  video_downloaded_or_exists = False
130
  if VIDEO_URL != "URL_DO_SEU_VIDEO_AQUI":
tool_video_analyzer.py CHANGED
@@ -11,6 +11,7 @@ import time
11
  from openai import OpenAI # Importa a classe OpenAI
12
  import json
13
  import re
 
14
 
15
  # --- Configurações (Substitua os placeholders) ---
16
  VIDEO_URL = "https://www.youtube.com/watch?v=L1vXCYZAYYM" # Substitua pela URL do vídeo do YouTube
@@ -18,7 +19,8 @@ OUTPUT_DIR = "./video_analysis_output" # Diretório para salvar o vídeo e os fr
18
  FRAME_INTERVAL_SECONDS = 3 # Intervalo entre frames a serem extraídos
19
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
20
  GPT_MODEL = "gpt-4o" # Modelo GPT a ser usado (certifique-se que é o correto para análise de imagem)
21
- PROMPT_TEXT = "Quantas aves existem nesta imagem? Responda apenas com o número." # Prompt para o GPT-4o
 
22
  RESULTS_FILE = os.path.join(OUTPUT_DIR, "analysis_results.json")
23
  VIDEO_FILENAME = "downloaded_video.mp4"
24
  VIDEO_PATH = os.path.join(OUTPUT_DIR, VIDEO_FILENAME)
@@ -36,11 +38,23 @@ if VIDEO_URL == "URL_DO_SEU_VIDEO_AQUI":
36
 
37
  # --- Funções ---
38
 
39
- def create_output_directory():
40
  """Cria o diretório de saída se não existir."""
41
  if not os.path.exists(OUTPUT_DIR):
42
  os.makedirs(OUTPUT_DIR)
43
  print(f"Diretório criado: {OUTPUT_DIR}")
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def retirar_sufixo_codec_arquivo(directory) -> None:
46
  for filename in os.listdir(directory):
@@ -167,8 +181,6 @@ def encode_frame_to_base64(frame_path):
167
 
168
 
169
  def analyze_frame_with_gpt4o(client, base64_image, prompt):
170
- print("NAO CHAMAR AINDA")
171
- return
172
 
173
  """Envia um frame codificado em base64 para a API GPT-4o e retorna a análise."""
174
  print(f"Enviando frame para análise no {GPT_MODEL}...")
@@ -246,7 +258,7 @@ def save_results_to_json(results_list, output_file):
246
  # --- Atualização do Bloco Principal ---
247
  # (Adicionar inicialização do cliente OpenAI e o loop de análise)
248
  if __name__ == "__main__":
249
- create_output_directory()
250
  extracted_frames = []
251
  analysis_results_list = []
252
 
@@ -297,15 +309,17 @@ if __name__ == "__main__":
297
  pass # Mantém 'unknown' se o parsing falhar
298
 
299
  # Codifica o frame
 
 
300
  base64_image = encode_frame_to_base64(frame_path)
301
 
302
  if base64_image:
303
  # Analisa o frame com GPT-4o
304
- # analysis_result = analyze_frame_with_gpt4o(openai_client, base64_image, PROMPT_TEXT)
305
  result_entry = {
306
  "frame_path": frame_path,
307
  "timestamp_approx_sec": timestamp_str,
308
- "analysis": f' pulado frame {frame_path}' #analysis_result
309
  }
310
  analysis_results_list.append(result_entry)
311
 
@@ -318,6 +332,8 @@ if __name__ == "__main__":
318
  "timestamp_approx_sec": timestamp_str,
319
  "analysis": {"error": "Failed to encode frame to base64."}
320
  })
 
 
321
  print("\nAnálise de todos os frames concluída.")
322
  elif not extracted_frames:
323
  print("Nenhum frame foi extraído. Pulando etapa de análise.")
 
11
  from openai import OpenAI # Importa a classe OpenAI
12
  import json
13
  import re
14
+ import shutil
15
 
16
  # --- Configurações (Substitua os placeholders) ---
17
  VIDEO_URL = "https://www.youtube.com/watch?v=L1vXCYZAYYM" # Substitua pela URL do vídeo do YouTube
 
19
  FRAME_INTERVAL_SECONDS = 3 # Intervalo entre frames a serem extraídos
20
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
21
  GPT_MODEL = "gpt-4o" # Modelo GPT a ser usado (certifique-se que é o correto para análise de imagem)
22
+ #PROMPT_TEXT = "You are an image analyzer, do not return any explanation. If asked to count items, return only an integer. If in doubt, return 0. How many different bird species are visible in the image?" # Prompt para o GPT-4o
23
+ PROMPT_TEXT = "You are an expert in visual species classification. Based on the image provided, determine and return the number of distinct bird species visible. Do not count individuals — only count different species based on visual traits like size, shape, color, and beak structure. Return only a single integer. If unsure, return your best estimate. Do not provide explanations or any extra text."
24
  RESULTS_FILE = os.path.join(OUTPUT_DIR, "analysis_results.json")
25
  VIDEO_FILENAME = "downloaded_video.mp4"
26
  VIDEO_PATH = os.path.join(OUTPUT_DIR, VIDEO_FILENAME)
 
38
 
39
  # --- Funções ---
40
 
41
+ def create_or_clear_output_directory():
42
  """Cria o diretório de saída se não existir."""
43
  if not os.path.exists(OUTPUT_DIR):
44
  os.makedirs(OUTPUT_DIR)
45
  print(f"Diretório criado: {OUTPUT_DIR}")
46
+ else:
47
+ # Limpa todos os arquivos e subdiretórios
48
+ for filename in os.listdir(OUTPUT_DIR):
49
+ file_path = os.path.join(OUTPUT_DIR, filename)
50
+ try:
51
+ if os.path.isfile(file_path) or os.path.islink(file_path):
52
+ os.unlink(file_path)
53
+ elif os.path.isdir(file_path):
54
+ shutil.rmtree(file_path)
55
+ except Exception as e:
56
+ print(f"Erro ao excluir {file_path}: {e}")
57
+ print(f"Diretório limpo: {OUTPUT_DIR}")
58
 
59
  def retirar_sufixo_codec_arquivo(directory) -> None:
60
  for filename in os.listdir(directory):
 
181
 
182
 
183
  def analyze_frame_with_gpt4o(client, base64_image, prompt):
 
 
184
 
185
  """Envia um frame codificado em base64 para a API GPT-4o e retorna a análise."""
186
  print(f"Enviando frame para análise no {GPT_MODEL}...")
 
258
  # --- Atualização do Bloco Principal ---
259
  # (Adicionar inicialização do cliente OpenAI e o loop de análise)
260
  if __name__ == "__main__":
261
+ create_or_clear_output_directory()
262
  extracted_frames = []
263
  analysis_results_list = []
264
 
 
309
  pass # Mantém 'unknown' se o parsing falhar
310
 
311
  # Codifica o frame
312
+ #teste com a imagem correta
313
+ frame_path = f"{OUTPUT_DIR}/frame_0031_time_93.00s.png"
314
  base64_image = encode_frame_to_base64(frame_path)
315
 
316
  if base64_image:
317
  # Analisa o frame com GPT-4o
318
+ analysis_result = analyze_frame_with_gpt4o(openai_client, base64_image, PROMPT_TEXT)
319
  result_entry = {
320
  "frame_path": frame_path,
321
  "timestamp_approx_sec": timestamp_str,
322
+ "analysis": analysis_result
323
  }
324
  analysis_results_list.append(result_entry)
325
 
 
332
  "timestamp_approx_sec": timestamp_str,
333
  "analysis": {"error": "Failed to encode frame to base64."}
334
  })
335
+
336
+ break # teste somente uma chamada
337
  print("\nAnálise de todos os frames concluída.")
338
  elif not extracted_frames:
339
  print("Nenhum frame foi extraído. Pulando etapa de análise.")