from typing import Dict, List, Any import os from openai import OpenAI # Initialize OpenAI client # Ensure your OPENAI_API_KEY environment variable is set client = OpenAI() MODEL_ID = "gpt-4o" # Or another model like gpt-3.5-turbo def analyze_scene(all_tool_outputs: Dict[str, Any], question: str) -> Dict[str, Any]: """Interprets aggregated outputs from other vision/audio tools to answer a specific question. Focuses on analyzing detailed per-frame species information if provided. Args: all_tool_outputs: A dictionary containing results from other tools. Expected keys might include 'object_detections', 'text_extractions', 'audio_transcript', 'frame_classifications', etc. question: The user's question that this analysis should answer. Returns: A dictionary containing the answer and any supporting information. E.g., {"answer": "The scene likely contains a cat playing with a red ball.", "reasoning": "Object detection found a cat and a ball. Color classification confirmed red for the ball..."} """ prompt_parts = [ "You are an AI assistant analyzing outputs from multimedia processing tools.", "Your goal is to answer the user's question based on the provided information.", "Be concise. If your answer is derived from data linked to a specific frame (e.g., object counts, species identification in a frame), " "you MUST state the source frame path (use the base name like 'frame_xxxx.png').", "\nUser Question:", question, "\nTool Outputs Digest:" ] # Prioritize and structure critical information for the LLM if "video_frames_info" in all_tool_outputs: prompt_parts.append(f"- Video Context: {all_tool_outputs['video_frames_info']}") if "audio_transcript" in all_tool_outputs and all_tool_outputs["audio_transcript"].get("text"): transcript_preview = all_tool_outputs["audio_transcript"]["text"][:300] # Preview of transcript prompt_parts.append(f"- Audio Transcript Snippet: {transcript_preview}...") if "ocr_extractions_summary" in all_tool_outputs: prompt_parts.append(f"- OCR Summary: {all_tool_outputs['ocr_extractions_summary']}") # Detailed per-frame species information - This is key for species-related questions if "per_frame_species_details" in all_tool_outputs and all_tool_outputs["per_frame_species_details"]: prompt_parts.append("\n--- Per-Frame Identified Entity Details (e.g., Species) ---") # Summarize if too long, but provide enough detail for species counting questions details = all_tool_outputs["per_frame_species_details"] if len(details) > 5: # If more than 5 frames have species details, summarize prompt_parts.append(f"(Showing details for first 3 and last 2 frames with identified entities, out of {len(details)} such frames total)") frames_to_show_details = details[:3] + details[-2:] else: frames_to_show_details = details for item in frames_to_show_details: frame_path = item.get("frame_path", "Unknown frame") entities = item.get("identified_entities", []) entity_descs = [f"{entity.get('identified_label', 'unknown_entity')} (conf: {entity.get('confidence', 0):.2f}) at bbox {entity.get('bbox')}" for entity in entities] prompt_parts.append(f"- Frame {os.path.basename(frame_path)}: Detected entities: [{', '.join(entity_descs)}]") prompt_parts.append("If the user's question is about counting distinct species or entities simultaneously, focus on the 'identified_label' within each frame's 'Detected entities' list. Count unique labels per frame. Explicitly state the frame with the highest count if relevant.") elif "object_detections_summary" in all_tool_outputs: # Fallback if no species details prompt_parts.append(f"- Object Detection Summary: {all_tool_outputs['object_detections_summary']}") # Add other summaries if they exist and seem relevant # (e.g., text_extractions_summary if not already covered by OCR summary) prompt = "\n".join(prompt_parts) # print(f"\n--- Sending request to LLM for scene analysis ({MODEL_ID}) ---") # print(f"Prompt (approx {len(prompt.split())} tokens): \n{prompt[:1500]}...") try: completion = client.chat.completions.create( model=MODEL_ID, messages=[ {"role": "system", "content": "You are an intelligent multimedia analysis assistant. Interpret tool outputs to answer the user. If the answer pertains to a specific frame, explicitly mention the frame's base name (e.g., 'frame_0001.png') in your response. For counting tasks (e.g. distinct species), identify the frame providing the peak count."}, {"role": "user", "content": prompt} ], temperature=0.2, # Lower temperature for more factual interpretation max_tokens=600 ) answer_content = completion.choices[0].message.content.strip() # Attempt to parse the source frame from the answer if mentioned # This is a simple heuristic; more robust parsing might be needed if format varies wildly source_frame_mention = "" words = answer_content.split() for i, word in enumerate(words): if "frame_" in word and ".png" in word: # Extract the frame name like frame_xxxx.png source_frame_mention = os.path.basename(word.strip('.,;:!?()[]{}')) break # print(f"LLM ({MODEL_ID}) analysis complete. Tokens used: Prompt={completion.usage.prompt_tokens}, Completion={completion.usage.completion_tokens}") return { "answer": answer_content, "source_frame": source_frame_mention if source_frame_mention else "Not specified or N/A", "model_used": MODEL_ID, "prompt_tokens": completion.usage.prompt_tokens if completion.usage else None, "completion_tokens": completion.usage.completion_tokens if completion.usage else None, } except Exception as e: print(f"Error calling OpenAI API for scene analysis: {e}") return { "answer": "Error: Could not complete scene analysis due to an API error.", "source_frame": "Error", "error_details": str(e) } # Example usage (for testing - requires other tools to have produced sample outputs): # if __name__ == '__main__': # sample_tool_outputs = { # "object_detections": [ # {"label": "cat", "confidence": 0.9, "bbox": [10, 10, 50, 50]}, # {"label": "ball", "confidence": 0.8, "bbox": [60, 60, 80, 80]}, # {"label": "dog", "confidence": 0.7, "bbox": [100,100,150,150], "frame_path": "data/frames/video1/frame_0001.png"} # ], # "text_extractions": [ # {"text": "EXIT", "conf": 95, "bbox": [200, 50, 250, 70], "frame_path": "data/frames/video1/frame_0002.png"} # ], # "audio_transcript": { # "text": "The cat is meowing loudly near the red ball.", # "language": "en" # }, # "frame_classifications": [ # [ # {"label": "a photo of indoor scene", "score": 0.85}, # {"label": "a photo of outdoor scene", "score": 0.15} # ] # ] # } # user_question = "What is happening with the cat and the ball? Is there any text visible?" # analysis_result = analyze_scene(sample_tool_outputs, user_question) # print("\n--- Analysis Result ---") # print(f"Answer: {analysis_result.get('answer')}") # if analysis_result.get('error_details'): # print(f"Error: {analysis_result.get('error_details')}")