gdms commited on
Commit
1991eac
·
1 Parent(s): f77d0ec

Análise de video via GPT-40

Browse files
Files changed (3) hide show
  1. .gitignore +1 -0
  2. requirements-video.txt +2 -1
  3. tool_video_analyzer.py +23 -7
.gitignore CHANGED
@@ -4,3 +4,4 @@ video_analysis_output/
4
  get-pip.py
5
  *.m4a
6
  *.mp4
 
 
4
  get-pip.py
5
  *.m4a
6
  *.mp4
7
+ audio_analysis_output/
requirements-video.txt CHANGED
@@ -1 +1,2 @@
1
- yt-dlp opencv-python openai
 
 
1
+ yt-dlp opencv-python openai
2
+ torch torchvision transformers pillow scikit-learn
tool_video_analyzer.py CHANGED
@@ -16,11 +16,16 @@ import shutil
16
  # --- Configurações (Substitua os placeholders) ---
17
  VIDEO_URL = "https://www.youtube.com/watch?v=L1vXCYZAYYM" # Substitua pela URL do vídeo do YouTube
18
  OUTPUT_DIR = "./video_analysis_output" # Diretório para salvar o vídeo e os frames
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)
@@ -101,6 +106,11 @@ def extract_frames(video_path, output_dir, interval_sec):
101
  return []
102
 
103
  cap = cv2.VideoCapture(video_path)
 
 
 
 
 
104
  if not cap.isOpened():
105
  print(f"Erro ao abrir o arquivo de vídeo: {video_path}")
106
  return []
@@ -126,6 +136,10 @@ def extract_frames(video_path, output_dir, interval_sec):
126
  if target_frame_pos >= total_frames:
127
  break # Sai se o próximo frame alvo estiver além do final do vídeo
128
 
 
 
 
 
129
  cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_pos)
130
  ret, frame = cap.read()
131
 
@@ -134,7 +148,8 @@ def extract_frames(video_path, output_dir, interval_sec):
134
  break # Sai se não conseguir ler o frame
135
 
136
  # redimensiona o frame (custo chamada)
137
- frame = cv2.resize(frame, (1280, 720))
 
138
 
139
  # Calcula o timestamp em segundos
140
  timestamp_sec = target_frame_pos / fps
@@ -143,7 +158,9 @@ def extract_frames(video_path, output_dir, interval_sec):
143
  frame_filename = f"frame_{saved_frame_index:04d}_time_{timestamp_sec:.2f}s.png"
144
  frame_path = os.path.join(output_dir, frame_filename)
145
  try:
146
- cv2.imwrite(frame_path, frame)
 
 
147
  extracted_frames_paths.append(frame_path)
148
  print(f"Frame salvo: {frame_path} (Timestamp: {timestamp_sec:.2f}s)")
149
  saved_frame_index += 1
@@ -292,7 +309,7 @@ if __name__ == "__main__":
292
  extracted_frames = extract_frames(VIDEO_PATH, OUTPUT_DIR, FRAME_INTERVAL_SECONDS)
293
  else:
294
  print("Pulando extração de frames pois o vídeo não está disponível.")
295
-
296
  # Etapa 3 e 4: Codificar e Analisar Frames
297
  if extracted_frames and openai_client:
298
  print(f"\nIniciando análise de {len(extracted_frames)} frames com {GPT_MODEL}...")
@@ -310,7 +327,6 @@ if __name__ == "__main__":
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:
@@ -333,7 +349,7 @@ if __name__ == "__main__":
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.")
 
16
  # --- Configurações (Substitua os placeholders) ---
17
  VIDEO_URL = "https://www.youtube.com/watch?v=L1vXCYZAYYM" # Substitua pela URL do vídeo do YouTube
18
  OUTPUT_DIR = "./video_analysis_output" # Diretório para salvar o vídeo e os frames
19
+ FRAME_INTERVAL_SECONDS = 1 # Intervalo entre frames a serem extraídos
20
+ INICIO_FRAME_IMPORTANTE = 96 # inicio intervalo relevante, para não ficar caro a inferencia ao gpt
21
+ FIM_FRAME_IMPORTANTE = 96 # fim intervalo relevante, para não ficar caro a inferencia ao gpt
22
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
23
  GPT_MODEL = "gpt-4o" # Modelo GPT a ser usado (certifique-se que é o correto para análise de imagem)
24
  #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
25
+ #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."
26
+ #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 and the species name. If unsure, return your best estimate. Do not provide explanations or any extra text."
27
+ PROMPT_TEXT = "You are a world-class expert in avian species classification. Analyze the provided image and determine how many **distinct bird species** are present. Consider size, shape, plumage, coloration, and beak structure. Focus only on visible morphological differences. Return a **single integer** with no explanation. Do not count individuals of the same species. If unsure, return your most informed estimate."
28
+
29
  RESULTS_FILE = os.path.join(OUTPUT_DIR, "analysis_results.json")
30
  VIDEO_FILENAME = "downloaded_video.mp4"
31
  VIDEO_PATH = os.path.join(OUTPUT_DIR, VIDEO_FILENAME)
 
106
  return []
107
 
108
  cap = cv2.VideoCapture(video_path)
109
+ # Verificar a resolução
110
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
111
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
112
+ print(f"Resolução original do vídeo: {width}x{height}")
113
+
114
  if not cap.isOpened():
115
  print(f"Erro ao abrir o arquivo de vídeo: {video_path}")
116
  return []
 
136
  if target_frame_pos >= total_frames:
137
  break # Sai se o próximo frame alvo estiver além do final do vídeo
138
 
139
+ if (saved_frame_index < INICIO_FRAME_IMPORTANTE or saved_frame_index > FIM_FRAME_IMPORTANTE):
140
+ print(f"Pulando frame {saved_frame_index}")
141
+ saved_frame_index += 1
142
+ continue # evitar custo desnecessário para inferencia ao gpt
143
  cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_pos)
144
  ret, frame = cap.read()
145
 
 
148
  break # Sai se não conseguir ler o frame
149
 
150
  # redimensiona o frame (custo chamada)
151
+ # removido porque poderia afetar a nitidez e impactar o resultado
152
+ # frame = cv2.resize(frame, (1280, 720))
153
 
154
  # Calcula o timestamp em segundos
155
  timestamp_sec = target_frame_pos / fps
 
158
  frame_filename = f"frame_{saved_frame_index:04d}_time_{timestamp_sec:.2f}s.png"
159
  frame_path = os.path.join(output_dir, frame_filename)
160
  try:
161
+ # modificado para salvar com qualidade máxima cv2.imwrite(frame_path, frame)
162
+ cv2.imwrite(frame_path, frame, [cv2.IMWRITE_PNG_COMPRESSION, 0])
163
+
164
  extracted_frames_paths.append(frame_path)
165
  print(f"Frame salvo: {frame_path} (Timestamp: {timestamp_sec:.2f}s)")
166
  saved_frame_index += 1
 
309
  extracted_frames = extract_frames(VIDEO_PATH, OUTPUT_DIR, FRAME_INTERVAL_SECONDS)
310
  else:
311
  print("Pulando extração de frames pois o vídeo não está disponível.")
312
+
313
  # Etapa 3 e 4: Codificar e Analisar Frames
314
  if extracted_frames and openai_client:
315
  print(f"\nIniciando análise de {len(extracted_frames)} frames com {GPT_MODEL}...")
 
327
 
328
  # Codifica o frame
329
  #teste com a imagem correta
 
330
  base64_image = encode_frame_to_base64(frame_path)
331
 
332
  if base64_image:
 
349
  "analysis": {"error": "Failed to encode frame to base64."}
350
  })
351
 
352
+ # break # teste somente uma chamada
353
  print("\nAnálise de todos os frames concluída.")
354
  elif not extracted_frames:
355
  print("Nenhum frame foi extraído. Pulando etapa de análise.")