import os import json import argparse import base64 import cv2 import tempfile import subprocess import shutil import io import time import glob from openai import OpenAI from tqdm import tqdm from PIL import Image GENERIC_RESULT_PATTERN = "_result.json" def get_media_type(file_path: str) -> str: ext = os.path.splitext(file_path)[1].lower() if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']: return 'video' elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']: return 'image' else: raise ValueError(f"Unsupported file format: {ext}") def encode_media_to_base64(media_path: str) -> str: try: with open(media_path, "rb") as media_file: return base64.b64encode(media_file.read()).decode('utf-8') except FileNotFoundError: raise except Exception as e: raise IOError(f"Could not read or encode file {media_path}: {e}") def extract_keyframes(video_path: str, max_frames: int = 20) -> list: cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise ValueError(f"Cannot open video file: {video_path}") total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) video_fps = cap.get(cv2.CAP_PROP_FPS) duration = total_frames / video_fps if video_fps > 0 else 0 if duration <= 20: target_frames = min(max_frames, int(duration)) frame_interval = max(1, int(video_fps)) # 1 frame per second else: target_frames = max_frames frame_interval = max(1, int(total_frames / max_frames)) keyframes = [] frame_count = 0 sampled_count = 0 while cap.isOpened() and sampled_count < target_frames: ret, frame = cap.read() if not ret: break if frame_count % frame_interval == 0: frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(frame_rgb) keyframes.append(pil_image) sampled_count += 1 frame_count += 1 cap.release() return keyframes def extract_audio_to_text(video_path: str, client: OpenAI) -> str: try: with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_audio: temp_audio_path = temp_audio.name command = [ 'ffmpeg', '-i', video_path, '-vn', '-acodec', 'mp3', '-ar', '16000', '-ac', '1', '-y', temp_audio_path ] result = subprocess.run(command, capture_output=True, text=True) if result.returncode != 0: print(f"FFmpeg audio extraction failed: {result.stderr}") os.unlink(temp_audio_path) return "Audio extraction failed." with open(temp_audio_path, 'rb') as audio_file: transcription = client.audio.transcriptions.create( model="whisper-1", file=(os.path.basename(temp_audio_path), audio_file.read()), response_format="text" ) os.unlink(temp_audio_path) return transcription except Exception as e: print(f"Audio processing failed: {e}") if 'temp_audio_path' in locals() and os.path.exists(temp_audio_path): os.unlink(temp_audio_path) return "Audio processing failed." def process_single_sample(client: OpenAI, media_full_path: str, prompt_text: str) -> str: clean_prompt = prompt_text.replace("", "").replace("