from typing import List, Dict, Any, Optional from langchain_core.tools import tool, Tool from langgraph.prebuilt import ToolNode from PIL import Image # Added for image cropping # Import the individual tool functions from tools.downloader import download_video from tools.segmenter import segment_video from tools.detect_objects import detect_objects from tools.classify_entities import classify_entities from tools.transcriber import transcribe_audio from tools.ocr_text import extract_text_from_frame from tools.scene_analyzer import analyze_scene # LLM-based analysis from tools.e2b_executor import execute_python_e2b_tool # --- Define individual tools for LangGraph/LangChain --- # These wrap the core functions to be LangChain compatible tools if needed individually # However, the main goal is the composite tool `process_video_chain` @tool def run_video_download(url: str, task_id: str) -> str: """Tool to download a video from a given URL. Uses task_id for pathing. Returns the local file path.""" if not task_id: raise ValueError("task_id must be provided for run_video_download") return download_video(url, task_id) @tool def run_video_segmentation(video_path: str, task_id: str, frames_per_second: int = 1) -> List[str]: """Tool to segment a video into frames. Uses task_id for pathing. Returns list of frame paths.""" if not task_id: raise ValueError("task_id must be provided for run_video_segmentation") return segment_video(video_path, task_id, frames_per_second) @tool def run_object_detection(frame_path: str, labels: Optional[List[str]] = None) -> List[Dict]: """Tool to detect objects in a single frame. Can filter by labels.""" return detect_objects(frame_path, labels) @tool def run_entity_classification(image_paths_or_crops: List[Any], candidate_labels: List[str]) -> List[List[Dict[str, Any]]]: """Tool to classify entities in image crops or image paths using CLIP against candidate labels.""" # Assuming image_paths_or_crops can be paths or PIL Images - classify_entities should handle this return classify_entities(image_paths_or_crops, candidate_labels) @tool def run_audio_transcription(video_or_audio_path: str, language: str = None, word_timestamps: bool = False) -> Dict: """Tool to transcribe audio from a video or audio file.""" return transcribe_audio(video_or_audio_path, language=language, word_timestamps=word_timestamps) @tool def run_frame_ocr(frame_path: str, lang: Optional[str] = None) -> List[Dict[str, Any]]: """Tool to extract text from a single frame using OCR.""" return extract_text_from_frame(frame_path, lang=lang) @tool def run_scene_analysis_llm(all_tool_outputs: Dict[str, Any], question: str) -> Dict[str, Any]: """Tool to analyze aggregated multimedia tool outputs using an LLM to answer a question.""" return analyze_scene(all_tool_outputs, question) # --- Composite Video Processing Tool --- @tool def process_video_chain(url: str, question: str, task_id: str, frames_per_second_for_segmentation: int = 1, object_detection_labels: Optional[List[str]] = None, classification_candidate_labels: Optional[List[str]] = None, ocr_language: Optional[str] = None, transcription_language: Optional[str] = None, enable_word_timestamps_transcription: bool = False ) -> Dict[str, Any]: """Comprehensive tool to download, process, and analyze a YouTube video to answer a question. Uses task_id for organizing downloaded/generated video files and frames. Returns a concise summary of the analysis. Detailed intermediate results are processed internally. IMPORTANT FOR IDENTIFYING AND COUNTING DISTINCT SPECIES/TYPES: - To identify and count specific *distinct* types or species of objects (e.g., "how many different bird species"), you MUST provide BOTH: 1. `object_detection_labels`: Set to the general category (e.g., ['bird']). 2. `classification_candidate_labels`: Provide a list of SPECIFIC, DISTINCT type/species names the objects could be, or distinct descriptive phrases for CLIP to differentiate against. Examples for birds: ["adelie penguin", "emperor penguin", "petrel", "skua", "albatross"]. DO NOT use generic phrases like ["identify bird species"] alone if you need to count distinct species, as this will not provide different species names for the classifier to output. - If `classification_candidate_labels` is not provided or is too generic (like only ["identify bird species"]), the system cannot distinguish between different species, and counts of distinct species will be inaccurate. Example for counting distinct bird species: User asks: "What is the highest number of distinct bird species on camera simultaneously in video X?" Planner should aim to call with: object_detection_labels=['bird'], classification_candidate_labels=["adelie penguin", "emperor penguin", "petrel", "skua", "albatross"] # (or other relevant species) """ print(f"--- Starting Video Processing Chain for URL: {url} (Task ID: {task_id}) ---") print(f"User Question: {question}") print(f"Parameters: obj_labels={object_detection_labels}, class_labels={classification_candidate_labels}") if not task_id: raise ValueError("task_id is required for process_video_chain to organize data.") video_path: Optional[str] = None frame_paths: List[str] = [] transcript_text: str = "Transcription not performed or failed." final_analysis_answer = "Analysis could not be completed." processing_status = "Error" num_frames_processed = 0 per_frame_species_details = [] # To store detailed species info for the analyzer final_analysis: Any = {} # Ensure final_analysis is defined for return statement try: print("Step 1: Downloading video...") video_path = run_video_download.func(url=url, task_id=task_id) print(f"Video downloaded to: {video_path}") print("Step 2: Segmenting video...") if video_path: frame_paths = run_video_segmentation.func(video_path=video_path, task_id=task_id, frames_per_second=frames_per_second_for_segmentation) num_frames_processed = len(frame_paths) print(f"Video segmented into {num_frames_processed} frames.") else: raise ValueError("Video download failed, cannot proceed.") if not frame_paths and video_path: print("Warning: No frames were extracted. Frame-based analysis will be skipped.") print("Step 3: Transcribing audio...") if video_path: try: transcript_data = transcribe_audio(video_path, language=transcription_language, word_timestamps=enable_word_timestamps_transcription) transcript_text = transcript_data.get('text', "Transcription produced no text.") print(f"Audio transcribed. Preview: {transcript_text[:100]}...") except Exception as e: print(f"Error during audio transcription: {e}") transcript_text = f"Error during audio transcription: {str(e)}" collated_ocr_extractions = [] # OCR can still run even if species focus is primary if frame_paths: print(f"Step 4: Processing {num_frames_processed} frames for object detection, species classification, and OCR...") for i, frame_p in enumerate(frame_paths): frame_specific_species = [] try: # Always run OCR ocr_results_for_frame = extract_text_from_frame(frame_p, lang=ocr_language) for ocr_item in ocr_results_for_frame: ocr_item['frame_path_ref'] = frame_p collated_ocr_extractions.extend(ocr_results_for_frame) # Object detection - potentially filtered (e.g., for 'bird') detections = detect_objects(frame_p, labels=object_detection_labels) if detections and classification_candidate_labels: # If we have detections AND we want to classify them (e.g., bird species) pil_frame_image = Image.open(frame_p).convert("RGB") bird_crops_for_frame = [] detected_objects_for_species_analysis = [] for det_idx, detection_result in enumerate(detections): # If object_detection_labels forced a specific type (e.g. 'bird'), # then all `detection_result` here match that type. # Otherwise, one might check `detection_result['label']` if needed. bbox = detection_result['bbox'] try: cropped_img = pil_frame_image.crop(bbox) bird_crops_for_frame.append(cropped_img) # Keep track of original detection for context if needed detected_objects_for_species_analysis.append(detection_result) except Exception as crop_err: print(f"Error cropping object {det_idx} from {frame_p} with bbox {bbox}: {crop_err}") if bird_crops_for_frame: # Classify all crops from this frame in one batch classification_results_for_frame = classify_entities(bird_crops_for_frame, classification_candidate_labels) # Process classification results for this frame for crop_idx, class_list_for_crop in enumerate(classification_results_for_frame): if class_list_for_crop: # class_list_for_crop is List[Dict[str, Union[str, float]]] top_classification = class_list_for_crop[0] # Highest score # Add more context if needed, e.g., original bbox original_detection_context = detected_objects_for_species_analysis[crop_idx] frame_specific_species.append({ "identified_label": top_classification['label'], "confidence": top_classification['score'], "original_detection_label": original_detection_context.get('label'), "bbox": original_detection_context.get('bbox') }) if frame_specific_species: per_frame_species_details.append({ "frame_path": frame_p, "identified_entities": frame_specific_species }) except Exception as e: print(f"Error processing frame {frame_p} details: {e}") print("Frame processing for analysis input complete.") else: print("Skipping detailed frame processing as no frames were extracted.") print("Step 5: Analyzing scene with LLM...") detailed_scene_analyzer_input = { "question": question, "audio_transcript": {"text": transcript_text}, "video_frames_info": f"{num_frames_processed} frames extracted from {video_path if video_path else 'N/A'}. Path structure includes task_id.", "per_frame_species_details": per_frame_species_details, # NEW: Pass detailed species info "ocr_extractions_summary": f"{len(collated_ocr_extractions)} OCR elements found.", # To keep the prompt to scene_analyzer leaner if per_frame_species_details is rich: # We might not need object_detections or entity_classifications summaries if species details are comprehensive # "object_detections": collated_object_detections, # Potentially too verbose now # "text_extractions": collated_ocr_extractions, # Also potentially verbose } final_analysis = analyze_scene(detailed_scene_analyzer_input, question) final_analysis_answer = final_analysis.get("answer", "Scene analysis did not return a direct answer.") print(f"Scene analysis complete. LLM Answer: {final_analysis_answer[:200]}...") processing_status = "Success" except ValueError as ve: print(f"ValueError in process_video_chain: {ve}") final_analysis_answer = f"Failed to process video: {str(ve)}" processing_status = f"Error: {str(ve)}" except Exception as e: print(f"General error in process_video_chain: {e}") final_analysis_answer = f"Failed to process video due to an unexpected error: {str(e)}" processing_status = f"Error: {str(e)}" import traceback traceback.print_exc() print(f"--- Video Processing Chain Finished for URL: {url} (Task ID: {task_id}) ---") concise_summary_output = { "input_url": url, "question": question, "task_id": task_id, "analysis_summary": final_analysis_answer, "source_frame_for_summary": final_analysis.get("source_frame", "N/A") if isinstance(final_analysis, dict) else "N/A", "frames_processed_count": num_frames_processed, "identified_species_frames_count": len(per_frame_species_details), "status": processing_status, } return concise_summary_output # List of all tools available for the executor # (This list was previously named new_structured_tools, then structured_tools. Let's use all_defined_tools for clarity) all_defined_tools = [ run_video_download, run_video_segmentation, run_object_detection, run_entity_classification, run_audio_transcription, run_frame_ocr, run_scene_analysis_llm, process_video_chain, execute_python_e2b_tool, ] # This executor is now the single source of truth for tool execution logic # if agent.py imports and uses it. # For now, agent.py defines its own ToolNode based on planner_facing_tools. # To make this cleaner, agent.py should import this tool_executor. # Let's rename this to main_tool_executor for clarity if it's to be imported. main_tool_executor = ToolNode(all_defined_tools)