Spaces:
Build error
Build error
Arash commited on
Commit ·
6715b3e
1
Parent(s): 81917a3
feat: agent setup with tools
Browse files- .gitignore +14 -0
- README.md +38 -1
- agent copy.py +483 -0
- agent.py +162 -0
- app.py +3 -12
- nodes/answer_composer.py +96 -0
- nodes/image_tool_wrapper.py +89 -0
- nodes/planner.py +75 -0
- nodes/tool_wrappers.py +262 -0
- pub_env.fish +13 -0
- quick_fetch.py +8 -0
- requirements.txt +50 -2
- run_local.py +68 -0
- tools/__init__.py +0 -0
- tools/classify_entities.py +121 -0
- tools/detect_objects.py +63 -0
- tools/downloader.py +59 -0
- tools/e2b_executor.py +70 -0
- tools/image_processor.py +193 -0
- tools/ocr_text.py +106 -0
- tools/scene_analyzer.py +144 -0
- tools/segmenter.py +65 -0
- tools/transcriber.py +148 -0
.gitignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Environment variables
|
| 2 |
+
.env
|
| 3 |
+
.venv/
|
| 4 |
+
__pycache__/
|
| 5 |
+
*.py[cod]
|
| 6 |
+
*$py.class
|
| 7 |
+
downloaded_files
|
| 8 |
+
downloaded_files_app
|
| 9 |
+
data
|
| 10 |
+
yolov*.pt
|
| 11 |
+
questions*.json
|
| 12 |
+
.DS_Store
|
| 13 |
+
tools_old/*
|
| 14 |
+
*.png
|
README.md
CHANGED
|
@@ -12,4 +12,41 @@ hf_oauth: true
|
|
| 12 |
hf_oauth_expiration_minutes: 480
|
| 13 |
---
|
| 14 |
|
| 15 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
hf_oauth_expiration_minutes: 480
|
| 13 |
---
|
| 14 |
|
| 15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
| 16 |
+
|
| 17 |
+
# Local Dev
|
| 18 |
+
|
| 19 |
+
Dependencies:
|
| 20 |
+
```shell
|
| 21 |
+
brew install stockfish
|
| 22 |
+
brew install ffmpeg # for youtube audio transcription
|
| 23 |
+
brew install tesseract # for image transcription
|
| 24 |
+
brew install graphviz # for graph visualization
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
To prepare the environment:
|
| 28 |
+
```shell
|
| 29 |
+
. pub_env.fish
|
| 30 |
+
python3 -m venv .venv
|
| 31 |
+
. .venv/bin/activate.fish
|
| 32 |
+
pip install --upgrade pip wheel setuptools
|
| 33 |
+
pip install "gradio[oauth]"
|
| 34 |
+
pip install -r requirements.txt
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Iterating Locally
|
| 38 |
+
|
| 39 |
+
### Pull the questions once via:
|
| 40 |
+
```shell
|
| 41 |
+
python quick_fetch.py # creates questions.json
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### Run the agent locally:
|
| 45 |
+
```shell
|
| 46 |
+
python run_local.py
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
### To run the app:
|
| 50 |
+
```shell
|
| 51 |
+
python app.py
|
| 52 |
+
```
|
agent copy.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Annotated, TypedDict, List, Union, Dict, Any, Literal
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from langchain_openai import ChatOpenAI
|
| 4 |
+
from langchain_core.messages import (
|
| 5 |
+
HumanMessage,
|
| 6 |
+
AIMessage,
|
| 7 |
+
FunctionMessage,
|
| 8 |
+
SystemMessage,
|
| 9 |
+
ToolMessage,
|
| 10 |
+
)
|
| 11 |
+
from langgraph.graph import StateGraph, END
|
| 12 |
+
from langgraph.graph.message import add_messages
|
| 13 |
+
from langgraph.prebuilt import ToolNode
|
| 14 |
+
from langfuse.callback import CallbackHandler
|
| 15 |
+
from langchain_community.tools import TavilySearchResults
|
| 16 |
+
from langchain_core.tools import tool
|
| 17 |
+
from pydantic import BaseModel, Field
|
| 18 |
+
from langchain_core.documents import Document
|
| 19 |
+
from langchain_core.documents.base import Blob
|
| 20 |
+
from langchain_community.document_loaders import (
|
| 21 |
+
UnstructuredExcelLoader, # .xlsx / .xls
|
| 22 |
+
UnstructuredImageLoader, # .png / .jpg
|
| 23 |
+
)
|
| 24 |
+
from langchain_community.document_loaders.parsers.audio import (
|
| 25 |
+
OpenAIWhisperParserLocal, # .mp3 / .wav
|
| 26 |
+
)
|
| 27 |
+
import os
|
| 28 |
+
from tools_old.youtube_tool import YoutubeTool
|
| 29 |
+
from tools_old.chess_tool import MateFinder
|
| 30 |
+
from tools_old.video_tool import VideoAnalysisTool
|
| 31 |
+
import json
|
| 32 |
+
from e2b import Sandbox as E2BSandbox
|
| 33 |
+
from pydantic import model_validator
|
| 34 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 35 |
+
import openai
|
| 36 |
+
|
| 37 |
+
# Initialize LLM
|
| 38 |
+
gpt4o = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0)
|
| 39 |
+
gemini_llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=os.getenv("GEMINI_API_KEY"), temperature=0.0)
|
| 40 |
+
|
| 41 |
+
# Initialize existing tools
|
| 42 |
+
search_tool_tavily = TavilySearchResults(
|
| 43 |
+
max_results=3,
|
| 44 |
+
include_answer=True,
|
| 45 |
+
include_raw_content=False,
|
| 46 |
+
include_images=True,
|
| 47 |
+
search_depth="advanced",
|
| 48 |
+
)
|
| 49 |
+
youtube = YoutubeTool() # Original instance
|
| 50 |
+
chess_tool = MateFinder() # Assuming this is already a LangChain compatible tool
|
| 51 |
+
video_tool = VideoAnalysisTool() # Assuming this is already a LangChain compatible tool
|
| 52 |
+
|
| 53 |
+
# Define Input Schema for YoutubeTool
|
| 54 |
+
class YoutubeToolInput(BaseModel):
|
| 55 |
+
youtube_url: str = Field(description="The full URL of the YouTube video to be processed or analyzed.")
|
| 56 |
+
question: str = Field(description="The question being asked about the YouTube video. This helps provide context for the analysis.")
|
| 57 |
+
analysis_type: Literal['transcript', 'visual', 'both'] = Field(
|
| 58 |
+
default='both',
|
| 59 |
+
description="Specifies the type of analysis to perform: 'transcript' for text content, 'visual' for object/scene detection, or 'both'."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
@tool("youtube_video_analyzer", args_schema=YoutubeToolInput)
|
| 63 |
+
def youtube_tool_with_schema(youtube_url: str, question: str, analysis_type: Literal['transcript', 'visual', 'both'] = 'both') -> str:
|
| 64 |
+
"""
|
| 65 |
+
Analyzes a YouTube video from the provided URL for its transcript and/or visual content.
|
| 66 |
+
You must provide the 'youtube_url' and the 'question' being asked about the video.
|
| 67 |
+
You can optionally specify 'analysis_type' as 'transcript', 'visual', or 'both' (defaults to 'both').
|
| 68 |
+
Use 'visual' if the question is about objects, scenes, or counts of things in the video.
|
| 69 |
+
Use 'transcript' if the question is about spoken content.
|
| 70 |
+
"""
|
| 71 |
+
print(f"[TOOL WRAPPER] Called youtube_tool_with_schema with URL: {youtube_url}, Question: {question}, Analysis Type: {analysis_type}")
|
| 72 |
+
try:
|
| 73 |
+
query_dict = {
|
| 74 |
+
"url": youtube_url,
|
| 75 |
+
"question": question,
|
| 76 |
+
"analysis_type": analysis_type
|
| 77 |
+
}
|
| 78 |
+
# Directly call the _run method of the YoutubeTool instance
|
| 79 |
+
# to bypass BaseTool.run() argument parsing issues for this specific tool.
|
| 80 |
+
result = youtube._run(query_dict) # Changed from youtube.run(query_dict)
|
| 81 |
+
return str(result) # Ensure the output is a string for the agent
|
| 82 |
+
except Exception as e:
|
| 83 |
+
import traceback
|
| 84 |
+
print(f"[TOOL WRAPPER] Error in youtube_tool_with_schema: {str(e)}\n{traceback.format_exc()}")
|
| 85 |
+
return f"Error during YouTube tool execution: {str(e)}"
|
| 86 |
+
|
| 87 |
+
# Define Tool Schemas using Pydantic for better validation and description
|
| 88 |
+
class TavilySearchInput(BaseModel):
|
| 89 |
+
query: str = Field(description="The search query to find information on the web. For Wikipedia searches, include 'wikipedia' in the query.")
|
| 90 |
+
|
| 91 |
+
@tool("tavily_search_results_json", args_schema=TavilySearchInput)
|
| 92 |
+
def tavily_search_tool(query: str) -> str:
|
| 93 |
+
"""
|
| 94 |
+
Performs a web search using Tavily to find up-to-date information, news, or details on a specific topic.
|
| 95 |
+
This tool is ideal for queries requiring current events, specific facts, or general knowledge from the internet.
|
| 96 |
+
If you need information from Wikipedia, ensure the word 'wikipedia' is part of your query.
|
| 97 |
+
Example:
|
| 98 |
+
User asks: "What's the weather in Paris?"
|
| 99 |
+
Tool call: tavily_search_results_json(query="weather in Paris")
|
| 100 |
+
|
| 101 |
+
User asks: "Tell me about LangGraph on Wikipedia."
|
| 102 |
+
Tool call: tavily_search_results_json(query="LangGraph wikipedia")
|
| 103 |
+
"""
|
| 104 |
+
print(f"[TOOL REGISTRY] Called tavily_search_tool with query: {query}")
|
| 105 |
+
# Enhance query for Wikipedia if specified
|
| 106 |
+
if "wikipedia" in query.lower() and "site:wikipedia.org" not in query.lower():
|
| 107 |
+
query_enhanced = f"{query} site:wikipedia.org"
|
| 108 |
+
print(f"[TOOL REGISTRY] Enhanced Wikipedia query: {query_enhanced}")
|
| 109 |
+
return search_tool_tavily.invoke({"query": query_enhanced})
|
| 110 |
+
return search_tool_tavily.invoke({"query": query})
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# E2B Code Execution Tool
|
| 114 |
+
class E2BCodeExecutionInput(BaseModel):
|
| 115 |
+
code: str | None = Field(default=None, description="The Python code string to execute. Use this if the code is directly available.")
|
| 116 |
+
file_path: str | None = Field(default=None, description="Path to a Python file to execute. The content of this file will be run. Use this if the code is in a file.")
|
| 117 |
+
|
| 118 |
+
@model_validator(mode='before')
|
| 119 |
+
@classmethod
|
| 120 |
+
def check_code_or_file_path_provided(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
| 121 |
+
code_provided = values.get('code') is not None and values.get('code') != ""
|
| 122 |
+
file_path_provided = values.get('file_path') is not None and values.get('file_path') != ""
|
| 123 |
+
|
| 124 |
+
if not code_provided and not file_path_provided:
|
| 125 |
+
raise ValueError('Either "code" or "file_path" must be provided.')
|
| 126 |
+
if code_provided and file_path_provided:
|
| 127 |
+
raise ValueError('Provide either "code" or "file_path", not both.')
|
| 128 |
+
return values
|
| 129 |
+
|
| 130 |
+
@tool("execute_python_code_e2b", args_schema=E2BCodeExecutionInput)
|
| 131 |
+
def execute_python_e2b_tool(code: str | None = None, file_path: str | None = None) -> str:
|
| 132 |
+
"""
|
| 133 |
+
Executes Python code in a secure E2B sandbox.
|
| 134 |
+
Provide either a 'code' string directly, or a 'file_path' to a Python script.
|
| 135 |
+
The tool will return the standard output and standard error from the execution.
|
| 136 |
+
This is useful for running arbitrary Python scripts, calculations, or simulations.
|
| 137 |
+
Example:
|
| 138 |
+
To run a simple print statement:
|
| 139 |
+
execute_python_code_e2b(code="print('Hello from E2B!')")
|
| 140 |
+
|
| 141 |
+
To run code from a file:
|
| 142 |
+
execute_python_code_e2b(file_path="path/to/your/script.py")
|
| 143 |
+
"""
|
| 144 |
+
print(f"[TOOL REGISTRY] Called execute_python_e2b_tool with code: {'yes' if code else 'no'}, file_path: {file_path}")
|
| 145 |
+
|
| 146 |
+
if os.getenv("E2B_API_KEY") is None:
|
| 147 |
+
return "Error: E2B_API_KEY is not set. Please set this environment variable to use the E2B code interpreter."
|
| 148 |
+
|
| 149 |
+
code_to_execute = code
|
| 150 |
+
if file_path:
|
| 151 |
+
try:
|
| 152 |
+
expanded_file_path = Path(file_path).expanduser().resolve()
|
| 153 |
+
if not expanded_file_path.is_file():
|
| 154 |
+
return f"Error: File not found at path: {file_path} (resolved to {expanded_file_path})"
|
| 155 |
+
with open(expanded_file_path, "r") as f:
|
| 156 |
+
code_to_execute = f.read()
|
| 157 |
+
print(f"[TOOL REGISTRY] Read code from file: {expanded_file_path}")
|
| 158 |
+
except Exception as e:
|
| 159 |
+
return f"Error reading Python file {file_path}: {str(e)}"
|
| 160 |
+
|
| 161 |
+
if not code_to_execute:
|
| 162 |
+
# This case should ideally be caught by Pydantic validator earlier
|
| 163 |
+
return "Error: No code provided for execution after attempting to load from file (if applicable)."
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
print(f"[E2B TOOL] Attempting to create sandbox and run code (first 200 chars):\n{code_to_execute[:200]}...")
|
| 167 |
+
with E2BSandbox() as sandbox:
|
| 168 |
+
stdout, stderr, exec_error = sandbox.execute_python(code=code_to_execute)
|
| 169 |
+
print(f"[E2B TOOL] Execution result - stdout: {stdout}, stderr: {stderr}, error: {exec_error}")
|
| 170 |
+
|
| 171 |
+
if exec_error:
|
| 172 |
+
error_message = f"Error during E2B execution: {exec_error.name}: {exec_error.value}\n"
|
| 173 |
+
if exec_error.traceback_raw and isinstance(exec_error.traceback_raw, list):
|
| 174 |
+
error_message += "Traceback:\n" + "\n".join(exec_error.traceback_raw)
|
| 175 |
+
return error_message.strip()
|
| 176 |
+
|
| 177 |
+
result_parts = []
|
| 178 |
+
if stdout:
|
| 179 |
+
result_parts.append(f"Stdout:\n{stdout}")
|
| 180 |
+
if stderr:
|
| 181 |
+
result_parts.append(f"Stderr:\n{stderr}")
|
| 182 |
+
|
| 183 |
+
if not result_parts:
|
| 184 |
+
return "Code executed successfully with no output to stdout or stderr."
|
| 185 |
+
return "\n".join(result_parts)
|
| 186 |
+
|
| 187 |
+
except Exception as e:
|
| 188 |
+
import traceback
|
| 189 |
+
tb_str = traceback.format_exc()
|
| 190 |
+
print(f"[E2B TOOL] Exception during E2B sandbox operation: {str(e)}\n{tb_str}")
|
| 191 |
+
return f"Error with E2B sandbox execution: {str(e)}"
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# Tool schemas for LLM - This is no longer strictly needed in this format for bind_tools
|
| 195 |
+
# but can be useful for other purposes or if we decide to generate prompts differently.
|
| 196 |
+
# For now, we will rely on the @tool decorator and bind_tools.
|
| 197 |
+
# TOOL_SCHEMAS = """...""" # Commented out as bind_tools handles this
|
| 198 |
+
|
| 199 |
+
SYSTEM_PROMPT = '''You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.'''
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@tool
|
| 203 |
+
def parse_spreadsheet(path: str) -> List[Document]:
|
| 204 |
+
"""Load all cells of an Excel workbook into Documents."""
|
| 205 |
+
loader = UnstructuredExcelLoader(Path(path).expanduser())
|
| 206 |
+
return loader.load()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@tool
|
| 210 |
+
def transcribe_audio(path: str) -> str:
|
| 211 |
+
"""Whisper-transcribe an audio file locally."""
|
| 212 |
+
parser = OpenAIWhisperParserLocal(device="cpu")
|
| 213 |
+
blob = Blob.from_path(path)
|
| 214 |
+
docs = list(parser.parse(blob))
|
| 215 |
+
return "\n".join(d.page_content for d in docs)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@tool
|
| 219 |
+
def describe_image(path: str) -> List[Document]:
|
| 220 |
+
"""Generate one caption per image."""
|
| 221 |
+
try:
|
| 222 |
+
loader = UnstructuredImageLoader(Path(path).expanduser(), mode="single")
|
| 223 |
+
docs = loader.load()
|
| 224 |
+
if not docs or not docs[0].page_content:
|
| 225 |
+
return [Document(page_content="Unable to extract text from image")]
|
| 226 |
+
return docs
|
| 227 |
+
except Exception as e:
|
| 228 |
+
return [Document(page_content=f"Error processing image: {str(e)}")]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# We will collect all tools that the LLM can use here
|
| 232 |
+
# For now, we only have tavily_search_tool correctly defined for LangGraph
|
| 233 |
+
# TODO: Wrap other tools (youtube, chess_tool, video_tool, parse_spreadsheet, etc.)
|
| 234 |
+
# with the @tool decorator and Pydantic schemas if they are to be used by the LLM.
|
| 235 |
+
|
| 236 |
+
available_tools = [
|
| 237 |
+
tavily_search_tool,
|
| 238 |
+
youtube_tool_with_schema, # Correctly wrapped version
|
| 239 |
+
chess_tool,
|
| 240 |
+
video_tool,
|
| 241 |
+
parse_spreadsheet,
|
| 242 |
+
transcribe_audio,
|
| 243 |
+
describe_image,
|
| 244 |
+
execute_python_e2b_tool,
|
| 245 |
+
]
|
| 246 |
+
|
| 247 |
+
# Bind tools to the LLM
|
| 248 |
+
gpt4o_with_tools = gpt4o.bind_tools(available_tools)
|
| 249 |
+
gemini_with_tools = gemini_llm.bind_tools(available_tools)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# State definition
|
| 253 |
+
class AgentState(TypedDict):
|
| 254 |
+
messages: Annotated[
|
| 255 |
+
List[Union[HumanMessage, AIMessage, FunctionMessage, SystemMessage, ToolMessage]],
|
| 256 |
+
add_messages,
|
| 257 |
+
]
|
| 258 |
+
next: str
|
| 259 |
+
file_path: str | None
|
| 260 |
+
message_count: int # Tracks LLM calls
|
| 261 |
+
tool_call_count: int # Tracks tool invocations
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def agent_node(state: AgentState):
|
| 265 |
+
"""Process agent messages and determine next steps."""
|
| 266 |
+
state["message_count"] = state.get("message_count", 0) + 1
|
| 267 |
+
print(f"\n[AGENT NODE] Message count (LLM calls): {state['message_count']}")
|
| 268 |
+
print(f"[AGENT NODE] Tool call count: {state.get('tool_call_count', 0)}")
|
| 269 |
+
print(f"[AGENT NODE] Current messages: {[(type(m).__name__, m.content[:100] if isinstance(m.content, str) else m.content) for m in state['messages']]}")
|
| 270 |
+
|
| 271 |
+
current_llm_with_tools = gpt4o_with_tools
|
| 272 |
+
current_llm_plain = gpt4o
|
| 273 |
+
llm_name = "GPT-4o"
|
| 274 |
+
|
| 275 |
+
def get_llm_response(messages_payload, use_tools=True):
|
| 276 |
+
nonlocal current_llm_with_tools, current_llm_plain, llm_name
|
| 277 |
+
primary_llm_name = "GPT-4o"
|
| 278 |
+
|
| 279 |
+
# First attempt with primary LLM (GPT-4o)
|
| 280 |
+
current_llm_with_tools = gpt4o_with_tools
|
| 281 |
+
current_llm_plain = gpt4o
|
| 282 |
+
llm_name = primary_llm_name
|
| 283 |
+
print(f"[AGENT NODE] Attempting LLM call with {llm_name}")
|
| 284 |
+
try:
|
| 285 |
+
if use_tools:
|
| 286 |
+
return current_llm_with_tools.invoke(messages_payload)
|
| 287 |
+
else:
|
| 288 |
+
return current_llm_plain.invoke(messages_payload)
|
| 289 |
+
except openai.RateLimitError as e:
|
| 290 |
+
print(f"[AGENT NODE] OpenAI ({llm_name}) rate limit hit: {e}. Attempting fallback to Gemini.")
|
| 291 |
+
|
| 292 |
+
# Directly attempt Gemini fallback, assuming gemini_llm and gemini_with_tools are initialized.
|
| 293 |
+
current_llm_with_tools = gemini_with_tools
|
| 294 |
+
current_llm_plain = gemini_llm
|
| 295 |
+
llm_name = "Gemini"
|
| 296 |
+
print(f"[AGENT NODE] Now using {llm_name} for this call.")
|
| 297 |
+
try:
|
| 298 |
+
if use_tools:
|
| 299 |
+
return current_llm_with_tools.invoke(messages_payload)
|
| 300 |
+
else:
|
| 301 |
+
return current_llm_plain.invoke(messages_payload)
|
| 302 |
+
except Exception as gemini_e: # Catch errors from Gemini call
|
| 303 |
+
print(f"[AGENT NODE] Gemini ({llm_name}) call also failed: {gemini_e}. Rethrowing original OpenAI error after fallback attempt.")
|
| 304 |
+
raise e # Rethrow the original openai.RateLimitError
|
| 305 |
+
# No explicit rethrow here for the primary error if Gemini is not attempted or fails,
|
| 306 |
+
# as the original error `e` would propagate if not caught by a Gemini success.
|
| 307 |
+
# However, the above structure ensures `e` is re-thrown if Gemini fails.
|
| 308 |
+
|
| 309 |
+
if state["message_count"] > 2 or state.get("tool_call_count", 0) >= 2:
|
| 310 |
+
if state.get("tool_call_count", 0) >= 2 and state["message_count"] <=2 : # if tool limit reached early
|
| 311 |
+
print("[AGENT NODE] Reached tool limit, attempting to generate final answer.")
|
| 312 |
+
elif state["message_count"] > 2:
|
| 313 |
+
print("[AGENT NODE] Reached LLM call limit, attempting to generate final answer.")
|
| 314 |
+
|
| 315 |
+
forced_final_answer_prompt = state["messages"] + [SystemMessage(content="You have reached your operational limits. Please provide a FINAL ANSWER based on the information you have gathered so far. If you cannot answer, state that clearly.")]
|
| 316 |
+
try:
|
| 317 |
+
response = get_llm_response(forced_final_answer_prompt, use_tools=True)
|
| 318 |
+
except Exception as e:
|
| 319 |
+
print(f"[AGENT NODE] Both primary and fallback LLMs failed for forced final answer: {e}")
|
| 320 |
+
return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors after hitting operational limits.")], "message_count": state["message_count"], "next": END}
|
| 321 |
+
print(f"[AGENT NODE] LLM Response ({llm_name}, forcing final): {response.content[:100]}...")
|
| 322 |
+
final_content = response.content
|
| 323 |
+
if not final_content.startswith("FINAL ANSWER:"):
|
| 324 |
+
final_content = f"FINAL ANSWER: {final_content}"
|
| 325 |
+
return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END}
|
| 326 |
+
|
| 327 |
+
print(f"[AGENT NODE] Running LLM with tools (will attempt {gpt4o.model_name} first)")
|
| 328 |
+
try:
|
| 329 |
+
response = get_llm_response(state["messages"], use_tools=True)
|
| 330 |
+
except Exception as e:
|
| 331 |
+
print(f"[AGENT NODE] Both primary and fallback LLMs failed for main tool call: {e}")
|
| 332 |
+
try:
|
| 333 |
+
synthesize_prompt = state["messages"] + [SystemMessage("Primary and fallback LLMs failed to use tools. Please synthesize a final answer based on the conversation so far without using any tools.")]
|
| 334 |
+
final_response_obj = get_llm_response(synthesize_prompt, use_tools=False)
|
| 335 |
+
final_content = final_response_obj.content
|
| 336 |
+
if not final_content.startswith("FINAL ANSWER:"):
|
| 337 |
+
final_content = f"FINAL ANSWER: {final_content}"
|
| 338 |
+
return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END}
|
| 339 |
+
except Exception as final_e:
|
| 340 |
+
print(f"[AGENT NODE] Final synthesis attempt also failed: {final_e}")
|
| 341 |
+
return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors.")], "message_count": state["message_count"], "next": END}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
print(f"[AGENT NODE] LLM Response ({llm_name}): {response.content[:100]}...")
|
| 345 |
+
print(f"[AGENT NODE] LLM Response object type: {type(response)}")
|
| 346 |
+
if hasattr(response, 'tool_calls') and response.tool_calls:
|
| 347 |
+
print(f"[AGENT NODE] LLM ({llm_name}) tool_calls: {response.tool_calls}")
|
| 348 |
+
|
| 349 |
+
has_tool_calls = hasattr(response, "tool_calls") and response.tool_calls and len(response.tool_calls) > 0
|
| 350 |
+
print(f"[AGENT NODE] Has tool calls ({llm_name}): {has_tool_calls}")
|
| 351 |
+
|
| 352 |
+
if has_tool_calls and state.get("tool_call_count", 0) < 2:
|
| 353 |
+
print(f"[AGENT NODE] Moving to tools node (called by {llm_name})")
|
| 354 |
+
return {"messages": [response], "message_count": state["message_count"]}
|
| 355 |
+
else:
|
| 356 |
+
if has_tool_calls and state.get("tool_call_count", 0) >= 2:
|
| 357 |
+
print(f"[AGENT NODE] Tool call limit reached, not executing further tools (LLM: {llm_name}). Generating final answer.")
|
| 358 |
+
else:
|
| 359 |
+
print(f"[AGENT NODE] No tool calls from LLM ({llm_name}) or tool limit reached. Generating final answer.")
|
| 360 |
+
|
| 361 |
+
final_content = response.content
|
| 362 |
+
if not final_content.startswith("FINAL ANSWER:"):
|
| 363 |
+
final_content = f"FINAL ANSWER: {final_content}"
|
| 364 |
+
|
| 365 |
+
if hasattr(response, "tool_calls") and response.tool_calls and len(response.tool_calls) > 0 :
|
| 366 |
+
print(f"[AGENT NODE] Warning: LLM ({llm_name}) tried to call tool {response.tool_calls} but was overridden due to limits.")
|
| 367 |
+
# Attempt a final synthesis without tools
|
| 368 |
+
synthesize_prompt = state["messages"] + [response, SystemMessage("You have reached your operational limits or attempted to use a tool when not allowed. Please synthesize a final answer without using any tools based on the conversation so far.")]
|
| 369 |
+
try:
|
| 370 |
+
final_response_obj = get_llm_response(synthesize_prompt, use_tools=False)
|
| 371 |
+
except Exception as e:
|
| 372 |
+
print(f"[AGENT NODE] Both primary and fallback LLMs failed for override synthesis: {e}")
|
| 373 |
+
return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors during override synthesis.")], "message_count": state["message_count"], "next": END}
|
| 374 |
+
|
| 375 |
+
final_content = final_response_obj.content
|
| 376 |
+
if not final_content.startswith("FINAL ANSWER:"):
|
| 377 |
+
final_content = f"FINAL ANSWER: {final_content}"
|
| 378 |
+
|
| 379 |
+
return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END}
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
# We will use the prebuilt ToolNode from LangGraph
|
| 383 |
+
# It expects a list of LangChain tools
|
| 384 |
+
tool_executor_node = ToolNode(available_tools)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def after_tool_node(state: AgentState):
|
| 388 |
+
"""Increment tool call count and decide next step."""
|
| 389 |
+
state["tool_call_count"] = state.get("tool_call_count", 0) + 1
|
| 390 |
+
print(f"\n[AFTER TOOL NODE] Tool call count updated to: {state['tool_call_count']}")
|
| 391 |
+
last_message = state["messages"][-1]
|
| 392 |
+
print(f"[AFTER TOOL NODE] Last message type: {type(last_message)}")
|
| 393 |
+
# If last message is a ToolMessage, it means a tool was just executed.
|
| 394 |
+
# We should go back to the agent to process the tool's output.
|
| 395 |
+
if isinstance(last_message, ToolMessage):
|
| 396 |
+
print("[AFTER TOOL NODE] Tool executed. Returning to agent_node.")
|
| 397 |
+
return {"next": "agent", "tool_call_count": state["tool_call_count"]}
|
| 398 |
+
else:
|
| 399 |
+
# This case should ideally not be hit if ToolNode works as expected
|
| 400 |
+
# and agent_node correctly routes to tools.
|
| 401 |
+
print("[AFTER TOOL NODE] No ToolMessage found after tool execution, unexpected state. Ending.")
|
| 402 |
+
return {"next": END, "tool_call_count": state["tool_call_count"]}
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class OptimaAgent:
|
| 406 |
+
def __init__(self):
|
| 407 |
+
workflow = StateGraph(AgentState)
|
| 408 |
+
|
| 409 |
+
workflow.add_node("agent", agent_node)
|
| 410 |
+
# workflow.add_node("tools", tool_node) # Replacing with prebuilt ToolNode
|
| 411 |
+
workflow.add_node("tool_executor", tool_executor_node)
|
| 412 |
+
workflow.add_node("after_tools", after_tool_node)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
workflow.set_entry_point("agent")
|
| 416 |
+
|
| 417 |
+
# If agent decides to use a tool, it goes to tool_executor
|
| 418 |
+
# The output of agent_node (AIMessage with tool_calls) is the input to tool_executor_node
|
| 419 |
+
workflow.add_conditional_edges(
|
| 420 |
+
"agent",
|
| 421 |
+
lambda x: "tool_executor" if hasattr(x["messages"][-1], "tool_calls") and x["messages"][-1].tool_calls else END,
|
| 422 |
+
{
|
| 423 |
+
"tool_executor": "tool_executor",
|
| 424 |
+
END: END
|
| 425 |
+
}
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# After tools are executed, go to 'after_tools' to update count and then back to agent
|
| 429 |
+
workflow.add_edge("tool_executor", "after_tools")
|
| 430 |
+
workflow.add_edge("after_tools", "agent")
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
self.graph = workflow.compile()
|
| 434 |
+
|
| 435 |
+
def __call__(self, user_text: str, file_path: str | None = None) -> str:
|
| 436 |
+
print(f"\n[AGENT] Starting new conversation with query: {user_text}")
|
| 437 |
+
langfuse_handler = CallbackHandler()
|
| 438 |
+
initial_state = AgentState(
|
| 439 |
+
messages=[
|
| 440 |
+
SystemMessage(content=SYSTEM_PROMPT),
|
| 441 |
+
HumanMessage(content=user_text),
|
| 442 |
+
],
|
| 443 |
+
next="",
|
| 444 |
+
file_path=file_path,
|
| 445 |
+
message_count=0,
|
| 446 |
+
tool_call_count=0,
|
| 447 |
+
)
|
| 448 |
+
print("[AGENT] Initial state:", initial_state)
|
| 449 |
+
|
| 450 |
+
try:
|
| 451 |
+
print("[AGENT] Running graph")
|
| 452 |
+
# The config for recursion_limit should be on the .invoke call
|
| 453 |
+
result = self.graph.invoke(initial_state, config={"callbacks": [langfuse_handler], "recursion_limit": 15})
|
| 454 |
+
print("[AGENT] Graph execution completed")
|
| 455 |
+
# print("[AGENT] Final result state:", result)
|
| 456 |
+
|
| 457 |
+
final_message = result["messages"][-1]
|
| 458 |
+
if isinstance(final_message, (AIMessage, SystemMessage)) and "FINAL ANSWER:" in final_message.content:
|
| 459 |
+
answer = final_message.content.split("FINAL ANSWER:", 1)[-1].strip()
|
| 460 |
+
elif isinstance(final_message, FunctionMessage): # Should be ToolMessage with new structure
|
| 461 |
+
answer = f"Observed tool output: {final_message.content}" # Fallback if graph ends unexpectedly
|
| 462 |
+
elif isinstance(final_message, ToolMessage):
|
| 463 |
+
answer = f"Observed tool output: {final_message.content}" # Fallback
|
| 464 |
+
else:
|
| 465 |
+
answer = str(final_message.content) # General fallback
|
| 466 |
+
|
| 467 |
+
# Ensure "FINAL ANSWER:" prefix if somehow missing and it's the end.
|
| 468 |
+
if not answer.startswith("FINAL ANSWER:") and result.get("next") == END and isinstance(final_message, AIMessage):
|
| 469 |
+
if "FINAL ANSWER:" not in final_message.content:
|
| 470 |
+
answer = f"FINAL ANSWER: {answer}"
|
| 471 |
+
else: # It was already there but split failed or was complex
|
| 472 |
+
answer = final_message.content.split("FINAL ANSWER:", 1)[-1].strip()
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
print(f"[AGENT] Full answer: {answer}")
|
| 476 |
+
print(f"[AGENT] FINAL ANSWER: {answer.split('FINAL ANSWER:', 1)[-1].strip()}")
|
| 477 |
+
return answer
|
| 478 |
+
|
| 479 |
+
except Exception as e:
|
| 480 |
+
print(f"[AGENT] Error during execution: {str(e)}")
|
| 481 |
+
import traceback
|
| 482 |
+
traceback.print_exc()
|
| 483 |
+
return f"I encountered an error: {str(e)}"
|
agent.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Annotated, TypedDict, List, Optional
|
| 3 |
+
|
| 4 |
+
from langchain_openai import ChatOpenAI
|
| 5 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 6 |
+
from langchain_core.messages import BaseMessage, HumanMessage
|
| 7 |
+
from langgraph.graph import StateGraph, END
|
| 8 |
+
from langgraph.graph.message import add_messages
|
| 9 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 10 |
+
|
| 11 |
+
from nodes.planner import planner_node
|
| 12 |
+
from nodes.answer_composer import answer_composer_node
|
| 13 |
+
from nodes.tool_wrappers import process_video_chain, run_audio_transcription
|
| 14 |
+
|
| 15 |
+
from tools.e2b_executor import execute_python_e2b_tool
|
| 16 |
+
from nodes.image_tool_wrapper import image_analyzer_tool
|
| 17 |
+
|
| 18 |
+
ORIGINAL_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AgentState(TypedDict):
|
| 22 |
+
messages: Annotated[List[BaseMessage], add_messages]
|
| 23 |
+
task_id: Optional[str]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# --- Tool Setup ---
|
| 27 |
+
|
| 28 |
+
# Tools that the planner LLM will be explicitly aware of and can choose from.
|
| 29 |
+
# This list is curated to reduce token count in the planner's prompt.
|
| 30 |
+
planner_facing_tools = [
|
| 31 |
+
TavilySearchResults(max_results=5),
|
| 32 |
+
execute_python_e2b_tool,
|
| 33 |
+
process_video_chain,
|
| 34 |
+
image_analyzer_tool,
|
| 35 |
+
run_audio_transcription,
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
# ---- DEBUG: Print tool names ----
|
| 39 |
+
print("--- Planner Facing Tools (before binding) ---")
|
| 40 |
+
for t in planner_facing_tools:
|
| 41 |
+
tool_name = getattr(t, 'name', 'Unknown name')
|
| 42 |
+
print(f"- Tool: {tool_name}, Type: {type(t)}")
|
| 43 |
+
if hasattr(t, 'description') : print(f" Desc: {t.description[:70]}...")
|
| 44 |
+
print("------------------------------------------")
|
| 45 |
+
# ---- END DEBUG ----
|
| 46 |
+
|
| 47 |
+
# The ToolNode that will execute tools called by the planner.
|
| 48 |
+
# It MUST be initialized with the same set of tools the planner is aware of.
|
| 49 |
+
tool_executor_node = ToolNode(planner_facing_tools)
|
| 50 |
+
|
| 51 |
+
# --- LLM Setup ---
|
| 52 |
+
planner_llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0)
|
| 53 |
+
# Bind planner LLM only to the curated list of tools
|
| 54 |
+
planner_llm_with_tools = planner_llm.bind_tools(planner_facing_tools)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# --- Graph Definition ---
|
| 58 |
+
|
| 59 |
+
def planner_entry_node(state: AgentState):
|
| 60 |
+
"""Wrapper for the planner_node to be used in the graph.
|
| 61 |
+
This node calls the imported planner_node from nodes/planner.py,
|
| 62 |
+
passing the required planner_llm_with_tools and descriptions for planner_facing_tools.
|
| 63 |
+
"""
|
| 64 |
+
print("---CALLING PLANNER WRAPPER NODE (agent.py)---")
|
| 65 |
+
|
| 66 |
+
# Generate descriptions only for the tools the planner is aware of
|
| 67 |
+
tool_descriptions = "\n".join([
|
| 68 |
+
f"- {tool.name}: {tool.description}" for tool in planner_facing_tools
|
| 69 |
+
])
|
| 70 |
+
|
| 71 |
+
return planner_node(state, llm_instance=planner_llm_with_tools, available_tools_descriptions=tool_descriptions)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
graph_builder = StateGraph(AgentState)
|
| 75 |
+
|
| 76 |
+
graph_builder.add_node("planner", planner_entry_node)
|
| 77 |
+
graph_builder.add_node("tool_executor", tool_executor_node)
|
| 78 |
+
graph_builder.add_node("answer_composer", answer_composer_node)
|
| 79 |
+
|
| 80 |
+
graph_builder.set_entry_point("planner")
|
| 81 |
+
|
| 82 |
+
graph_builder.add_conditional_edges(
|
| 83 |
+
"planner",
|
| 84 |
+
tools_condition,
|
| 85 |
+
{
|
| 86 |
+
"tools": "tool_executor",
|
| 87 |
+
END: "answer_composer",
|
| 88 |
+
},
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
graph_builder.add_edge("tool_executor", "planner")
|
| 92 |
+
graph_builder.add_edge("answer_composer", END)
|
| 93 |
+
|
| 94 |
+
assistant_graph = graph_builder.compile()
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
assistant_graph.get_graph().draw_png(output_file_path="workflow_graph.png")
|
| 98 |
+
print("New workflow graph saved to workflow_graph.png")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Could not draw graph: {e}. Pygraphviz might be missing or not set up correctly.")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class OptimaAgent:
|
| 104 |
+
def __init__(self):
|
| 105 |
+
self.graph = assistant_graph
|
| 106 |
+
self.initial_system_prompt_content = ORIGINAL_SYSTEM_PROMPT
|
| 107 |
+
|
| 108 |
+
def __call__(self, query: str, task_id: str, file_path: str = None):
|
| 109 |
+
print(f"User: {query}\nTask ID: {task_id}")
|
| 110 |
+
|
| 111 |
+
current_query = query
|
| 112 |
+
if file_path:
|
| 113 |
+
current_query = f"File path: {file_path}\n\n{query}"
|
| 114 |
+
|
| 115 |
+
initial_messages: List[BaseMessage] = [
|
| 116 |
+
HumanMessage(content=current_query),
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
initial_state = AgentState(messages=initial_messages, task_id=task_id)
|
| 120 |
+
|
| 121 |
+
final_state = self.graph.invoke(initial_state)
|
| 122 |
+
|
| 123 |
+
if final_state and "messages" in final_state:
|
| 124 |
+
all_messages = final_state["messages"]
|
| 125 |
+
if all_messages:
|
| 126 |
+
print("\n=== Final Assistant Response (from new graph) ===")
|
| 127 |
+
final_message = all_messages[-1]
|
| 128 |
+
final_message.pretty_print()
|
| 129 |
+
print("---END---")
|
| 130 |
+
|
| 131 |
+
content = final_message.content
|
| 132 |
+
if "FINAL ANSWER:" in content:
|
| 133 |
+
answer = content.split("FINAL ANSWER:")[-1].strip()
|
| 134 |
+
return answer
|
| 135 |
+
print("Warning: 'FINAL ANSWER:' not found in the final message from the graph.")
|
| 136 |
+
return content
|
| 137 |
+
else:
|
| 138 |
+
print("\n--- Assistant (new graph) finished with no messages. ---")
|
| 139 |
+
return "No response generated"
|
| 140 |
+
else:
|
| 141 |
+
print("\n--- Assistant (new graph) finished with unexpected state: ---")
|
| 142 |
+
print(final_state)
|
| 143 |
+
return "Error: Unexpected state from new graph"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
agent = OptimaAgent()
|
| 148 |
+
example_task_id = "cli_test_task_001"
|
| 149 |
+
|
| 150 |
+
print(f"\nRunning new agent with a query about LangGraph (Task ID: {example_task_id})...\n")
|
| 151 |
+
result = agent("What is LangGraph? Explain briefly.", task_id=example_task_id)
|
| 152 |
+
print(f"Final Answer: {result}")
|
| 153 |
+
|
| 154 |
+
video_url_for_test = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
| 155 |
+
print(f"\nRunning new agent with a video query for URL: {video_url_for_test} (Task ID: {example_task_id})...\n")
|
| 156 |
+
result_video = agent(f"What is this video about? Summarize its content. Video URL: {video_url_for_test}", task_id=example_task_id)
|
| 157 |
+
print(f"Final Answer from video query: {result_video}")
|
| 158 |
+
|
| 159 |
+
python_code_query = "Calculate 25 * 4 and tell me the result using Python."
|
| 160 |
+
print(f"\nRunning new agent with Python code execution query (Task ID: {example_task_id})...\n")
|
| 161 |
+
result_python = agent(python_code_query, task_id=example_task_id)
|
| 162 |
+
print(f"Final Answer from Python query: {result_python}")
|
app.py
CHANGED
|
@@ -3,21 +3,12 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -40,7 +31,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
|
@@ -193,4 +184,4 @@ if __name__ == "__main__":
|
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from agent import OptimaAgent
|
| 7 |
|
| 8 |
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 14 |
"""
|
|
|
|
| 31 |
|
| 32 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 33 |
try:
|
| 34 |
+
agent = OptimaAgent()
|
| 35 |
except Exception as e:
|
| 36 |
print(f"Error instantiating agent: {e}")
|
| 37 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 184 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 185 |
|
| 186 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 187 |
+
demo.launch(debug=True, share=False)
|
nodes/answer_composer.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Annotated, List, TypedDict
|
| 2 |
+
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage, AIMessage
|
| 3 |
+
from langchain_openai import ChatOpenAI
|
| 4 |
+
from langgraph.graph.message import add_messages
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Define the state for the answer composer node
|
| 8 |
+
class ComposerState(TypedDict):
|
| 9 |
+
messages: Annotated[List[BaseMessage], add_messages]
|
| 10 |
+
# May include other fields like 'accumulated_tool_outputs' if processed separately
|
| 11 |
+
|
| 12 |
+
llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0)
|
| 13 |
+
|
| 14 |
+
# The SYSTEM_PROMPT from agent.py should be used here for consistency in final answer formatting.
|
| 15 |
+
# It would be better to import it from a shared constants file if it becomes complex.
|
| 16 |
+
# For now, I'll redefine a simplified version. Ensure it matches your agent.py's prompt for FINAL ANSWER format.
|
| 17 |
+
COMPOSER_SYSTEM_PROMPT = """You are a helpful AI assistant. Your primary task is to synthesize a concise and accurate final answer to the user's most recent query, based on the entire preceding conversation history (which includes user questions, your own previous messages, tool calls, and their outputs like text from web pages or analysis summaries).
|
| 18 |
+
|
| 19 |
+
Specific instructions for content synthesis:
|
| 20 |
+
- If the user's question involves counting items from a list (e.g., albums from a discography within a specific date range) found in provided text:
|
| 21 |
+
1. Carefully identify the correct section (e.g., 'Studio Albums').
|
| 22 |
+
2. For each item, accurately extract its title and its primary listed year of release/publication.
|
| 23 |
+
3. Strictly filter these items based on the date range given in the user's question (inclusive).
|
| 24 |
+
4. Only count items that match the specified type (e.g., 'studio album').
|
| 25 |
+
5. For album projects released in multiple parts very closely together (e.g., Cantora 1 & Cantora 2 in the same year), count them as ONE album project for 'how many albums' questions.
|
| 26 |
+
6. State the final count clearly.
|
| 27 |
+
|
| 28 |
+
- If a tool output (often in a ToolMessage) contains a 'source_frame_for_summary' key with a relevant frame name (not 'N/A' or 'Error'), and this frame is pertinent to the answer, include a brief sentence mentioning it, for example: 'This information pertains to frame [frame_name].' or 'The key observation was in frame [frame_name].' Place this sentence naturally within your response before the final conclusion.
|
| 29 |
+
|
| 30 |
+
After synthesizing the answer based on these guidelines and the conversation history, you MUST conclude your entire response with the exact phrase 'FINAL ANSWER: [Your synthesized answer here]'.
|
| 31 |
+
The format of '[Your synthesized answer here]' should follow general rules for conciseness: a number, as few words as possible, or a comma-separated list, as appropriate for the question.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def answer_composer_node(state: ComposerState) -> ComposerState:
|
| 35 |
+
"""
|
| 36 |
+
LLM-based node to synthesize the final answer or pass through if already provided.
|
| 37 |
+
|
| 38 |
+
If the last message from the planner already contains 'FINAL ANSWER:',
|
| 39 |
+
this node will pass that message through. Otherwise, it uses an LLM
|
| 40 |
+
to generate a final, consolidated answer to the user.
|
| 41 |
+
It should adhere to the specified FINAL ANSWER format when generating.
|
| 42 |
+
"""
|
| 43 |
+
print("---CALLING ANSWER COMPOSER LLM NODE---")
|
| 44 |
+
current_messages = state["messages"]
|
| 45 |
+
|
| 46 |
+
# Check if the last message (likely from planner) already contains a FINAL ANSWER
|
| 47 |
+
if current_messages and isinstance(current_messages[-1], AIMessage) and "FINAL ANSWER:" in current_messages[-1].content:
|
| 48 |
+
print("Answer Composer detected FINAL ANSWER from planner. Passing through.")
|
| 49 |
+
# Ensure the message is in the correct format for the graph state update
|
| 50 |
+
final_ai_message = current_messages[-1]
|
| 51 |
+
# No need to append dummy FINAL ANSWER here, as it's already present.
|
| 52 |
+
return {"messages": [final_ai_message]} # Return the planner's message to be added to state
|
| 53 |
+
|
| 54 |
+
# If no FINAL ANSWER from planner, proceed to compose one
|
| 55 |
+
print("No FINAL ANSWER from planner detected. Composer will generate one.")
|
| 56 |
+
messages_for_composer = [SystemMessage(content=COMPOSER_SYSTEM_PROMPT)]
|
| 57 |
+
|
| 58 |
+
# Filter out any previous system messages to avoid confusion, if necessary,
|
| 59 |
+
# or make sure the history is clean. For now, just append history.
|
| 60 |
+
# Exclude the initial system prompt if it was generic and not for the composer.
|
| 61 |
+
for msg in current_messages:
|
| 62 |
+
if not isinstance(msg, SystemMessage): # Avoid duplicating system prompts if agent adds its own
|
| 63 |
+
messages_for_composer.append(msg)
|
| 64 |
+
elif isinstance(msg, SystemMessage) and msg.content != COMPOSER_SYSTEM_PROMPT:
|
| 65 |
+
# If there are other system messages you want to retain, add them.
|
| 66 |
+
# For now, only the composer system prompt is used.
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
# Ensure the last message isn't an AI planning message if the planner adds one
|
| 70 |
+
# The composer needs the *result* of the plan (tool outputs) not the plan itself as the last thing.
|
| 71 |
+
|
| 72 |
+
print(f"Answer Composer received {len(messages_for_composer)} messages. Last: {messages_for_composer[-1].content[:100] if messages_for_composer else 'No messages'}")
|
| 73 |
+
|
| 74 |
+
response_message = llm.invoke(messages_for_composer)
|
| 75 |
+
|
| 76 |
+
# The response should be an AIMessage. If it's not, wrap it.
|
| 77 |
+
if not isinstance(response_message, AIMessage):
|
| 78 |
+
final_ai_message = AIMessage(content=str(response_message.content if hasattr(response_message, 'content') else response_message))
|
| 79 |
+
else:
|
| 80 |
+
final_ai_message = response_message
|
| 81 |
+
|
| 82 |
+
# Ensure the final answer format is present
|
| 83 |
+
if "FINAL ANSWER:" not in final_ai_message.content:
|
| 84 |
+
print("Warning: 'FINAL ANSWER:' not found in composer output. Appending dummy for safety.")
|
| 85 |
+
# This indicates a problem with the prompt or model behavior.
|
| 86 |
+
# For robustness, you might try to extract the likely answer or add a fallback.
|
| 87 |
+
# For now, just append to the existing content if it's missing.
|
| 88 |
+
final_ai_message.content += "\nFINAL ANSWER: [Could not reliably extract final answer]"
|
| 89 |
+
|
| 90 |
+
print(f"Answer Composer generated: {final_ai_message.content[:300]}") # Increased preview length
|
| 91 |
+
|
| 92 |
+
# The graph expects a dictionary with 'messages' to be added.
|
| 93 |
+
# We add only the final composed AIMessage to avoid re-adding the whole history.
|
| 94 |
+
# However, standard LangGraph practice is to return the message to be *added* to the state.
|
| 95 |
+
# The StateGraph using `add_messages` will handle appending it to the existing `messages` list.
|
| 96 |
+
return {"messages": [final_ai_message]}
|
nodes/image_tool_wrapper.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Wrapper to make the image processing functionality available as a structured tool for the agent.
|
| 3 |
+
'''
|
| 4 |
+
from langchain_core.tools import StructuredTool
|
| 5 |
+
from pydantic.v1 import BaseModel, Field # Assuming Pydantic v1 based on typical Langchain usage
|
| 6 |
+
from typing import Optional, Type
|
| 7 |
+
|
| 8 |
+
from tools.image_processor import process_image_and_answer
|
| 9 |
+
|
| 10 |
+
class ImageAnalyzerInput(BaseModel):
|
| 11 |
+
"""Input schema for the Image Analyzer Tool."""
|
| 12 |
+
image_path: str = Field(description="The file path of the image to be analyzed.")
|
| 13 |
+
question: str = Field(description="The question to answer about the image.")
|
| 14 |
+
task_id: Optional[str] = Field(None, description="Optional task ID for tracking.")
|
| 15 |
+
|
| 16 |
+
def run_image_analysis(image_path: str, question: str, task_id: Optional[str] = None) -> dict:
|
| 17 |
+
"""Runs the image processing and question answering logic."""
|
| 18 |
+
print(f"--- Calling Image Analyzer Tool --- (Task ID: {task_id})")
|
| 19 |
+
print(f"Image path: {image_path}, Question: {question}")
|
| 20 |
+
try:
|
| 21 |
+
result = process_image_and_answer(image_path=image_path, question=question, task_id=task_id)
|
| 22 |
+
print(f"Image analysis result: {result}")
|
| 23 |
+
return result
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Error in Image Analyzer Tool: {e}")
|
| 26 |
+
return {
|
| 27 |
+
"image_path": image_path,
|
| 28 |
+
"question": question,
|
| 29 |
+
"task_id": task_id,
|
| 30 |
+
"answer": f"Error during image analysis: {str(e)}",
|
| 31 |
+
"status": "Error in tool execution"
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
image_analyzer_tool = StructuredTool.from_function(
|
| 35 |
+
func=run_image_analysis,
|
| 36 |
+
name="ImageAnalyzerTool",
|
| 37 |
+
description="Analyzes an image to answer a question about it. Provide the image file path and the specific question.",
|
| 38 |
+
args_schema=ImageAnalyzerInput,
|
| 39 |
+
# return_direct=False, # Set to True if the tool output should be returned directly to the user
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
# Example usage (for testing this module directly)
|
| 44 |
+
# Ensure a dummy image exists for testing, or provide a valid path
|
| 45 |
+
dummy_image_path_for_wrapper = "../dummy_image.png" # Relative to nodes directory
|
| 46 |
+
|
| 47 |
+
# Create a dummy image in the root if it doesn't exist (from where run_local.py might be run)
|
| 48 |
+
# This is a bit of a workaround for direct testing of the wrapper
|
| 49 |
+
import os
|
| 50 |
+
if not os.path.exists(dummy_image_path_for_wrapper):
|
| 51 |
+
try:
|
| 52 |
+
with open(dummy_image_path_for_wrapper, "w") as f:
|
| 53 |
+
f.write("This is a dummy image file content for wrapper test.")
|
| 54 |
+
print(f"Created dummy file for wrapper testing: {dummy_image_path_for_wrapper}")
|
| 55 |
+
except IOError as e:
|
| 56 |
+
print(f"Could not create dummy file for wrapper testing: {e}. Please create it manually or update path.")
|
| 57 |
+
# dummy_image_path_for_wrapper = "path/to/your/actual/image.png" # Or provide a real image path
|
| 58 |
+
|
| 59 |
+
if os.path.exists(dummy_image_path_for_wrapper):
|
| 60 |
+
test_question = "What is the primary subject of the image?"
|
| 61 |
+
test_task_id = "test-wrapper-001"
|
| 62 |
+
|
| 63 |
+
print("\n--- Testing ImageAnalyzerTool directly ---")
|
| 64 |
+
# Test by directly invoking the wrapped function (as the tool would)
|
| 65 |
+
output = run_image_analysis(
|
| 66 |
+
image_path=dummy_image_path_for_wrapper,
|
| 67 |
+
question=test_question,
|
| 68 |
+
task_id=test_task_id
|
| 69 |
+
)
|
| 70 |
+
print("\n--- Tool Output ---")
|
| 71 |
+
print(output)
|
| 72 |
+
print("-------------------")
|
| 73 |
+
|
| 74 |
+
print("\n--- Testing ImageAnalyzerTool via .invoke() (simulating LangChain agent call) ---")
|
| 75 |
+
# Test by invoking the tool instance
|
| 76 |
+
try:
|
| 77 |
+
tool_input = {
|
| 78 |
+
"image_path": dummy_image_path_for_wrapper,
|
| 79 |
+
"question": test_question,
|
| 80 |
+
"task_id": test_task_id
|
| 81 |
+
}
|
| 82 |
+
tool_output = image_analyzer_tool.invoke(input=tool_input)
|
| 83 |
+
print("\n--- Tool .invoke() Output ---")
|
| 84 |
+
print(tool_output)
|
| 85 |
+
print("---------------------------")
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"Error invoking tool: {e}")
|
| 88 |
+
else:
|
| 89 |
+
print(f"Skipping wrapper example run as dummy image '{dummy_image_path_for_wrapper}' could not be prepared.")
|
nodes/planner.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM planner (interprets questions)
|
| 2 |
+
|
| 3 |
+
from typing import Annotated, List, TypedDict
|
| 4 |
+
from langchain_core.messages import BaseMessage, AIMessage, SystemMessage
|
| 5 |
+
from langchain_openai import ChatOpenAI
|
| 6 |
+
from langgraph.graph.message import add_messages
|
| 7 |
+
|
| 8 |
+
# Define the state for the planner node (can be part of a larger graph state)
|
| 9 |
+
# For now, let's assume it receives the current messages and can add to them.
|
| 10 |
+
class PlannerState(TypedDict):
|
| 11 |
+
messages: Annotated[List[BaseMessage], add_messages]
|
| 12 |
+
# You might add other specific fields the planner needs or updates
|
| 13 |
+
# For example: plan_history: List[str]
|
| 14 |
+
|
| 15 |
+
# This local LLM definition is overridden if an llm_instance is passed to planner_node
|
| 16 |
+
# default_llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0)
|
| 17 |
+
|
| 18 |
+
def planner_node(state: PlannerState, llm_instance: ChatOpenAI, available_tools_descriptions: str) -> PlannerState:
|
| 19 |
+
"""LLM-based planner node.
|
| 20 |
+
Receives current state (which includes task_id), an LLM instance (bound with tools),
|
| 21 |
+
and tool descriptions. Decides the next step.
|
| 22 |
+
"""
|
| 23 |
+
print("---CALLING PLANNER LLM NODE (nodes/planner.py version)---")
|
| 24 |
+
current_messages = state["messages"]
|
| 25 |
+
task_id_from_state = state.get("task_id", "UNKNOWN_TASK_ID") # Get task_id from state
|
| 26 |
+
|
| 27 |
+
planner_system_prompt = f"""You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 28 |
+
|
| 29 |
+
You are also a planner for this AI assistant.
|
| 30 |
+
Your goal is to analyze the user's query and the conversation history to decide the best next step towards fulfilling the above response format and constraints.
|
| 31 |
+
|
| 32 |
+
When answering questions about specific items (e.g., publications, albums, movies), pay close attention to:
|
| 33 |
+
1. **Release Dates vs. Other Dates**: Use the official release date. Do not confuse it with award dates, recording dates, or other mentions of dates.
|
| 34 |
+
2. **Item Type**: If a specific type is requested (e.g., "studio album", "debut novel"), ensure items match this type. Verify from reliable sections like discographies or official lists, not just general mentions or awards. For example, a "Best Folk Album" award does not automatically mean it's a "studio album".
|
| 35 |
+
3. **Multi-Part Questions & Comprehensive Extraction**: If the user's query requires multiple pieces of related information (e.g., identifying an entity based on one criterion and then finding a different attribute of that same entity, like 'the person with the most X and their Y'), strive to find a single, comprehensive data source (like a detailed statistics page or biography). Once such a source is found through a tool call (e.g., web search), examine the retrieved information thoroughly. Extract all the necessary pieces of information from this source in one go if possible, rather than making follow-up tool calls for each individual piece of information if the initial data is likely complete.
|
| 36 |
+
|
| 37 |
+
Available context:
|
| 38 |
+
- Current Task ID: {task_id_from_state}
|
| 39 |
+
|
| 40 |
+
Available tools and their descriptions:
|
| 41 |
+
{available_tools_descriptions}
|
| 42 |
+
|
| 43 |
+
Based on the latest user message and conversation history, decide if a tool needs to be called.
|
| 44 |
+
If a tool is needed, specify which tool and what parameters to use in the AIMessage's tool_calls attribute.
|
| 45 |
+
IMPORTANT: If a tool requires a 'task_id' (like video processing tools for path organization),
|
| 46 |
+
ensure you use the Current Task ID: {task_id_from_state} for that argument.
|
| 47 |
+
|
| 48 |
+
If no tool is needed, or if you have enough information to answer, set your content to indicate readiness for answer composition (e.g., "Proceeding to compose answer.").
|
| 49 |
+
If the query is ambiguous, you can ask a clarifying question.
|
| 50 |
+
Focus on creating a plan or selecting the correct tool to gather necessary information.
|
| 51 |
+
Do not try to generate the final answer to the user here, unless it's a simple greeting or clarification.
|
| 52 |
+
Your response should be an AIMessage, possibly with tool_calls.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
messages_for_planner = [SystemMessage(content=planner_system_prompt)] + current_messages
|
| 56 |
+
|
| 57 |
+
print(f"Planner (nodes/planner.py) received: {current_messages[-1].content if current_messages else 'No messages'}. Task ID from state: {task_id_from_state}")
|
| 58 |
+
|
| 59 |
+
response = llm_instance.invoke(messages_for_planner)
|
| 60 |
+
print(f"Planner (nodes/planner.py) LLM response: {response.content[:100]}, Tool calls: {response.tool_calls}")
|
| 61 |
+
|
| 62 |
+
# Ensure task_id is preserved in the state update if it was there
|
| 63 |
+
# The add_messages in the StateGraph handles messages. We need to ensure other state parts are not lost.
|
| 64 |
+
# This node only returns messages to be added. The graph should merge the rest of the state.
|
| 65 |
+
# However, if this node were to *change* task_id, it would need to return it.
|
| 66 |
+
# For now, it just uses it.
|
| 67 |
+
returned_state_update = {"messages": [response]}
|
| 68 |
+
# if task_id_from_state != "UNKNOWN_TASK_ID":
|
| 69 |
+
# returned_state_update["task_id"] = task_id_from_state # Not strictly needed if graph merges state
|
| 70 |
+
|
| 71 |
+
return returned_state_update
|
| 72 |
+
|
| 73 |
+
# Remove the old placeholder TypedDict definition if PlannerState is now correctly defined at the top.
|
| 74 |
+
# if "TypedDict" not in globals():
|
| 75 |
+
# from typing import TypedDict # This was a placeholder, remove if PlannerState is fine
|
nodes/tool_wrappers.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Any, Optional
|
| 2 |
+
from langchain_core.tools import tool, Tool
|
| 3 |
+
from langgraph.prebuilt import ToolNode
|
| 4 |
+
from PIL import Image # Added for image cropping
|
| 5 |
+
|
| 6 |
+
# Import the individual tool functions
|
| 7 |
+
from tools.downloader import download_video
|
| 8 |
+
from tools.segmenter import segment_video
|
| 9 |
+
from tools.detect_objects import detect_objects
|
| 10 |
+
from tools.classify_entities import classify_entities
|
| 11 |
+
from tools.transcriber import transcribe_audio
|
| 12 |
+
from tools.ocr_text import extract_text_from_frame
|
| 13 |
+
from tools.scene_analyzer import analyze_scene # LLM-based analysis
|
| 14 |
+
from tools.e2b_executor import execute_python_e2b_tool
|
| 15 |
+
|
| 16 |
+
# --- Define individual tools for LangGraph/LangChain ---
|
| 17 |
+
# These wrap the core functions to be LangChain compatible tools if needed individually
|
| 18 |
+
# However, the main goal is the composite tool `process_video_chain`
|
| 19 |
+
|
| 20 |
+
@tool
|
| 21 |
+
def run_video_download(url: str, task_id: str) -> str:
|
| 22 |
+
"""Tool to download a video from a given URL. Uses task_id for pathing. Returns the local file path."""
|
| 23 |
+
if not task_id:
|
| 24 |
+
raise ValueError("task_id must be provided for run_video_download")
|
| 25 |
+
return download_video(url, task_id)
|
| 26 |
+
|
| 27 |
+
@tool
|
| 28 |
+
def run_video_segmentation(video_path: str, task_id: str, frames_per_second: int = 1) -> List[str]:
|
| 29 |
+
"""Tool to segment a video into frames. Uses task_id for pathing. Returns list of frame paths."""
|
| 30 |
+
if not task_id:
|
| 31 |
+
raise ValueError("task_id must be provided for run_video_segmentation")
|
| 32 |
+
return segment_video(video_path, task_id, frames_per_second)
|
| 33 |
+
|
| 34 |
+
@tool
|
| 35 |
+
def run_object_detection(frame_path: str, labels: Optional[List[str]] = None) -> List[Dict]:
|
| 36 |
+
"""Tool to detect objects in a single frame. Can filter by labels."""
|
| 37 |
+
return detect_objects(frame_path, labels)
|
| 38 |
+
|
| 39 |
+
@tool
|
| 40 |
+
def run_entity_classification(image_paths_or_crops: List[Any], candidate_labels: List[str]) -> List[List[Dict[str, Any]]]:
|
| 41 |
+
"""Tool to classify entities in image crops or image paths using CLIP against candidate labels."""
|
| 42 |
+
# Assuming image_paths_or_crops can be paths or PIL Images - classify_entities should handle this
|
| 43 |
+
return classify_entities(image_paths_or_crops, candidate_labels)
|
| 44 |
+
|
| 45 |
+
@tool
|
| 46 |
+
def run_audio_transcription(video_or_audio_path: str, language: str = None, word_timestamps: bool = False) -> Dict:
|
| 47 |
+
"""Tool to transcribe audio from a video or audio file."""
|
| 48 |
+
return transcribe_audio(video_or_audio_path, language=language, word_timestamps=word_timestamps)
|
| 49 |
+
|
| 50 |
+
@tool
|
| 51 |
+
def run_frame_ocr(frame_path: str, lang: Optional[str] = None) -> List[Dict[str, Any]]:
|
| 52 |
+
"""Tool to extract text from a single frame using OCR."""
|
| 53 |
+
return extract_text_from_frame(frame_path, lang=lang)
|
| 54 |
+
|
| 55 |
+
@tool
|
| 56 |
+
def run_scene_analysis_llm(all_tool_outputs: Dict[str, Any], question: str) -> Dict[str, Any]:
|
| 57 |
+
"""Tool to analyze aggregated multimedia tool outputs using an LLM to answer a question."""
|
| 58 |
+
return analyze_scene(all_tool_outputs, question)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# --- Composite Video Processing Tool ---
|
| 62 |
+
@tool
|
| 63 |
+
def process_video_chain(url: str, question: str, task_id: str,
|
| 64 |
+
frames_per_second_for_segmentation: int = 1,
|
| 65 |
+
object_detection_labels: Optional[List[str]] = None,
|
| 66 |
+
classification_candidate_labels: Optional[List[str]] = None,
|
| 67 |
+
ocr_language: Optional[str] = None,
|
| 68 |
+
transcription_language: Optional[str] = None,
|
| 69 |
+
enable_word_timestamps_transcription: bool = False
|
| 70 |
+
) -> Dict[str, Any]:
|
| 71 |
+
"""Comprehensive tool to download, process, and analyze a YouTube video to answer a question.
|
| 72 |
+
Uses task_id for organizing downloaded/generated video files and frames.
|
| 73 |
+
Returns a concise summary of the analysis. Detailed intermediate results are processed internally.
|
| 74 |
+
|
| 75 |
+
IMPORTANT FOR IDENTIFYING AND COUNTING DISTINCT SPECIES/TYPES:
|
| 76 |
+
- To identify and count specific *distinct* types or species of objects (e.g., "how many different bird species"),
|
| 77 |
+
you MUST provide BOTH:
|
| 78 |
+
1. `object_detection_labels`: Set to the general category (e.g., ['bird']).
|
| 79 |
+
2. `classification_candidate_labels`: Provide a list of SPECIFIC, DISTINCT type/species names the objects could be,
|
| 80 |
+
or distinct descriptive phrases for CLIP to differentiate against.
|
| 81 |
+
Examples for birds: ["adelie penguin", "emperor penguin", "petrel", "skua", "albatross"].
|
| 82 |
+
DO NOT use generic phrases like ["identify bird species"] alone if you need to count distinct species,
|
| 83 |
+
as this will not provide different species names for the classifier to output.
|
| 84 |
+
- If `classification_candidate_labels` is not provided or is too generic (like only ["identify bird species"]),
|
| 85 |
+
the system cannot distinguish between different species, and counts of distinct species will be inaccurate.
|
| 86 |
+
|
| 87 |
+
Example for counting distinct bird species:
|
| 88 |
+
User asks: "What is the highest number of distinct bird species on camera simultaneously in video X?"
|
| 89 |
+
Planner should aim to call with:
|
| 90 |
+
object_detection_labels=['bird'],
|
| 91 |
+
classification_candidate_labels=["adelie penguin", "emperor penguin", "petrel", "skua", "albatross"] # (or other relevant species)
|
| 92 |
+
"""
|
| 93 |
+
print(f"--- Starting Video Processing Chain for URL: {url} (Task ID: {task_id}) ---")
|
| 94 |
+
print(f"User Question: {question}")
|
| 95 |
+
print(f"Parameters: obj_labels={object_detection_labels}, class_labels={classification_candidate_labels}")
|
| 96 |
+
|
| 97 |
+
if not task_id:
|
| 98 |
+
raise ValueError("task_id is required for process_video_chain to organize data.")
|
| 99 |
+
|
| 100 |
+
video_path: Optional[str] = None
|
| 101 |
+
frame_paths: List[str] = []
|
| 102 |
+
transcript_text: str = "Transcription not performed or failed."
|
| 103 |
+
final_analysis_answer = "Analysis could not be completed."
|
| 104 |
+
processing_status = "Error"
|
| 105 |
+
num_frames_processed = 0
|
| 106 |
+
per_frame_species_details = [] # To store detailed species info for the analyzer
|
| 107 |
+
final_analysis: Any = {} # Ensure final_analysis is defined for return statement
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
print("Step 1: Downloading video...")
|
| 111 |
+
video_path = run_video_download.func(url=url, task_id=task_id)
|
| 112 |
+
print(f"Video downloaded to: {video_path}")
|
| 113 |
+
|
| 114 |
+
print("Step 2: Segmenting video...")
|
| 115 |
+
if video_path:
|
| 116 |
+
frame_paths = run_video_segmentation.func(video_path=video_path, task_id=task_id, frames_per_second=frames_per_second_for_segmentation)
|
| 117 |
+
num_frames_processed = len(frame_paths)
|
| 118 |
+
print(f"Video segmented into {num_frames_processed} frames.")
|
| 119 |
+
else:
|
| 120 |
+
raise ValueError("Video download failed, cannot proceed.")
|
| 121 |
+
|
| 122 |
+
if not frame_paths and video_path:
|
| 123 |
+
print("Warning: No frames were extracted. Frame-based analysis will be skipped.")
|
| 124 |
+
|
| 125 |
+
print("Step 3: Transcribing audio...")
|
| 126 |
+
if video_path:
|
| 127 |
+
try:
|
| 128 |
+
transcript_data = transcribe_audio(video_path, language=transcription_language, word_timestamps=enable_word_timestamps_transcription)
|
| 129 |
+
transcript_text = transcript_data.get('text', "Transcription produced no text.")
|
| 130 |
+
print(f"Audio transcribed. Preview: {transcript_text[:100]}...")
|
| 131 |
+
except Exception as e:
|
| 132 |
+
print(f"Error during audio transcription: {e}")
|
| 133 |
+
transcript_text = f"Error during audio transcription: {str(e)}"
|
| 134 |
+
|
| 135 |
+
collated_ocr_extractions = [] # OCR can still run even if species focus is primary
|
| 136 |
+
|
| 137 |
+
if frame_paths:
|
| 138 |
+
print(f"Step 4: Processing {num_frames_processed} frames for object detection, species classification, and OCR...")
|
| 139 |
+
for i, frame_p in enumerate(frame_paths):
|
| 140 |
+
frame_specific_species = []
|
| 141 |
+
try:
|
| 142 |
+
# Always run OCR
|
| 143 |
+
ocr_results_for_frame = extract_text_from_frame(frame_p, lang=ocr_language)
|
| 144 |
+
for ocr_item in ocr_results_for_frame: ocr_item['frame_path_ref'] = frame_p
|
| 145 |
+
collated_ocr_extractions.extend(ocr_results_for_frame)
|
| 146 |
+
|
| 147 |
+
# Object detection - potentially filtered (e.g., for 'bird')
|
| 148 |
+
detections = detect_objects(frame_p, labels=object_detection_labels)
|
| 149 |
+
|
| 150 |
+
if detections and classification_candidate_labels:
|
| 151 |
+
# If we have detections AND we want to classify them (e.g., bird species)
|
| 152 |
+
pil_frame_image = Image.open(frame_p).convert("RGB")
|
| 153 |
+
bird_crops_for_frame = []
|
| 154 |
+
detected_objects_for_species_analysis = []
|
| 155 |
+
|
| 156 |
+
for det_idx, detection_result in enumerate(detections):
|
| 157 |
+
# If object_detection_labels forced a specific type (e.g. 'bird'),
|
| 158 |
+
# then all `detection_result` here match that type.
|
| 159 |
+
# Otherwise, one might check `detection_result['label']` if needed.
|
| 160 |
+
bbox = detection_result['bbox']
|
| 161 |
+
try:
|
| 162 |
+
cropped_img = pil_frame_image.crop(bbox)
|
| 163 |
+
bird_crops_for_frame.append(cropped_img)
|
| 164 |
+
# Keep track of original detection for context if needed
|
| 165 |
+
detected_objects_for_species_analysis.append(detection_result)
|
| 166 |
+
except Exception as crop_err:
|
| 167 |
+
print(f"Error cropping object {det_idx} from {frame_p} with bbox {bbox}: {crop_err}")
|
| 168 |
+
|
| 169 |
+
if bird_crops_for_frame:
|
| 170 |
+
# Classify all crops from this frame in one batch
|
| 171 |
+
classification_results_for_frame = classify_entities(bird_crops_for_frame, classification_candidate_labels)
|
| 172 |
+
|
| 173 |
+
# Process classification results for this frame
|
| 174 |
+
for crop_idx, class_list_for_crop in enumerate(classification_results_for_frame):
|
| 175 |
+
if class_list_for_crop: # class_list_for_crop is List[Dict[str, Union[str, float]]]
|
| 176 |
+
top_classification = class_list_for_crop[0] # Highest score
|
| 177 |
+
# Add more context if needed, e.g., original bbox
|
| 178 |
+
original_detection_context = detected_objects_for_species_analysis[crop_idx]
|
| 179 |
+
frame_specific_species.append({
|
| 180 |
+
"identified_label": top_classification['label'],
|
| 181 |
+
"confidence": top_classification['score'],
|
| 182 |
+
"original_detection_label": original_detection_context.get('label'),
|
| 183 |
+
"bbox": original_detection_context.get('bbox')
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
if frame_specific_species:
|
| 187 |
+
per_frame_species_details.append({
|
| 188 |
+
"frame_path": frame_p,
|
| 189 |
+
"identified_entities": frame_specific_species
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
except Exception as e:
|
| 193 |
+
print(f"Error processing frame {frame_p} details: {e}")
|
| 194 |
+
print("Frame processing for analysis input complete.")
|
| 195 |
+
else:
|
| 196 |
+
print("Skipping detailed frame processing as no frames were extracted.")
|
| 197 |
+
|
| 198 |
+
print("Step 5: Analyzing scene with LLM...")
|
| 199 |
+
|
| 200 |
+
detailed_scene_analyzer_input = {
|
| 201 |
+
"question": question,
|
| 202 |
+
"audio_transcript": {"text": transcript_text},
|
| 203 |
+
"video_frames_info": f"{num_frames_processed} frames extracted from {video_path if video_path else 'N/A'}. Path structure includes task_id.",
|
| 204 |
+
"per_frame_species_details": per_frame_species_details, # NEW: Pass detailed species info
|
| 205 |
+
"ocr_extractions_summary": f"{len(collated_ocr_extractions)} OCR elements found.",
|
| 206 |
+
# To keep the prompt to scene_analyzer leaner if per_frame_species_details is rich:
|
| 207 |
+
# We might not need object_detections or entity_classifications summaries if species details are comprehensive
|
| 208 |
+
# "object_detections": collated_object_detections, # Potentially too verbose now
|
| 209 |
+
# "text_extractions": collated_ocr_extractions, # Also potentially verbose
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
final_analysis = analyze_scene(detailed_scene_analyzer_input, question)
|
| 213 |
+
final_analysis_answer = final_analysis.get("answer", "Scene analysis did not return a direct answer.")
|
| 214 |
+
print(f"Scene analysis complete. LLM Answer: {final_analysis_answer[:200]}...")
|
| 215 |
+
processing_status = "Success"
|
| 216 |
+
|
| 217 |
+
except ValueError as ve:
|
| 218 |
+
print(f"ValueError in process_video_chain: {ve}")
|
| 219 |
+
final_analysis_answer = f"Failed to process video: {str(ve)}"
|
| 220 |
+
processing_status = f"Error: {str(ve)}"
|
| 221 |
+
except Exception as e:
|
| 222 |
+
print(f"General error in process_video_chain: {e}")
|
| 223 |
+
final_analysis_answer = f"Failed to process video due to an unexpected error: {str(e)}"
|
| 224 |
+
processing_status = f"Error: {str(e)}"
|
| 225 |
+
import traceback
|
| 226 |
+
traceback.print_exc()
|
| 227 |
+
|
| 228 |
+
print(f"--- Video Processing Chain Finished for URL: {url} (Task ID: {task_id}) ---")
|
| 229 |
+
|
| 230 |
+
concise_summary_output = {
|
| 231 |
+
"input_url": url,
|
| 232 |
+
"question": question,
|
| 233 |
+
"task_id": task_id,
|
| 234 |
+
"analysis_summary": final_analysis_answer,
|
| 235 |
+
"source_frame_for_summary": final_analysis.get("source_frame", "N/A") if isinstance(final_analysis, dict) else "N/A",
|
| 236 |
+
"frames_processed_count": num_frames_processed,
|
| 237 |
+
"identified_species_frames_count": len(per_frame_species_details),
|
| 238 |
+
"status": processing_status,
|
| 239 |
+
}
|
| 240 |
+
return concise_summary_output
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# List of all tools available for the executor
|
| 244 |
+
# (This list was previously named new_structured_tools, then structured_tools. Let's use all_defined_tools for clarity)
|
| 245 |
+
all_defined_tools = [
|
| 246 |
+
run_video_download,
|
| 247 |
+
run_video_segmentation,
|
| 248 |
+
run_object_detection,
|
| 249 |
+
run_entity_classification,
|
| 250 |
+
run_audio_transcription,
|
| 251 |
+
run_frame_ocr,
|
| 252 |
+
run_scene_analysis_llm,
|
| 253 |
+
process_video_chain,
|
| 254 |
+
execute_python_e2b_tool,
|
| 255 |
+
]
|
| 256 |
+
|
| 257 |
+
# This executor is now the single source of truth for tool execution logic
|
| 258 |
+
# if agent.py imports and uses it.
|
| 259 |
+
# For now, agent.py defines its own ToolNode based on planner_facing_tools.
|
| 260 |
+
# To make this cleaner, agent.py should import this tool_executor.
|
| 261 |
+
# Let's rename this to main_tool_executor for clarity if it's to be imported.
|
| 262 |
+
main_tool_executor = ToolNode(all_defined_tools)
|
pub_env.fish
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
set -x SPACE_HOST "local/dev"
|
| 2 |
+
set -x SPACE_ID "arashx07"
|
| 3 |
+
set -x OCR_AGENT "tesseract"
|
| 4 |
+
set -x BREW_GRAPHVIZ_PREFIX (brew --prefix graphviz)
|
| 5 |
+
set -x CFLAGS "-I$BREW_GRAPHVIZ_PREFIX/include"
|
| 6 |
+
set -x LDFLAGS "-L$BREW_GRAPHVIZ_PREFIX/lib"
|
| 7 |
+
# huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
|
| 8 |
+
# To disable this warning, you can either:
|
| 9 |
+
# - Avoid using `tokenizers` before the fork if possible
|
| 10 |
+
# - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
|
| 11 |
+
set -x TOKENIZERS_PARALLELISM "false"
|
| 12 |
+
|
| 13 |
+
echo "ENV VARS SET"
|
quick_fetch.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests, json
|
| 2 |
+
from app import DEFAULT_API_URL
|
| 3 |
+
|
| 4 |
+
QUESTIONS = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
|
| 5 |
+
|
| 6 |
+
with open("questions.json", "w") as f:
|
| 7 |
+
json.dump(QUESTIONS, f, indent=2)
|
| 8 |
+
print(f"Saved {len(QUESTIONS)} questions")
|
requirements.txt
CHANGED
|
@@ -1,2 +1,50 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ─── core stack ─────────────────────────────────────────────────────────────────
|
| 2 |
+
gradio==5.29.1
|
| 3 |
+
requests==2.32.3
|
| 4 |
+
langchain==0.3.25
|
| 5 |
+
langchain-openai==0.3.16
|
| 6 |
+
langchain-google-genai==2.1.4
|
| 7 |
+
langchain-community==0.3.24
|
| 8 |
+
langgraph==0.4.3
|
| 9 |
+
langfuse==2.60.4
|
| 10 |
+
pygraphviz==1.14 # for graph visualization
|
| 11 |
+
|
| 12 |
+
# ─── tools & helpers ───────────────────────────────────────────────────────────
|
| 13 |
+
tavily-python==0.7.2
|
| 14 |
+
yt-dlp>=2024.4 # leave un-pinned to stay current
|
| 15 |
+
youtube-search==2.1.2
|
| 16 |
+
youtube-transcript-api==1.0.3
|
| 17 |
+
faster-whisper>=0.10.0 # optimized whisper implementation
|
| 18 |
+
pydub==0.25.1 # for audio processing
|
| 19 |
+
e2b-code-interpreter==1.5.0 # needs the next line…
|
| 20 |
+
e2b==1.5.0 # …explicitly pin to stop pip back-tracking
|
| 21 |
+
python-chess==1.999
|
| 22 |
+
wikipedia==1.4.0
|
| 23 |
+
|
| 24 |
+
# ─── ML / audio / vision ───────────────────────────────────────────────────────
|
| 25 |
+
transformers==4.51.3
|
| 26 |
+
torch==2.7.0
|
| 27 |
+
torchvision==0.22.0
|
| 28 |
+
librosa==0.11.0
|
| 29 |
+
opencv-python==4.11.0.86
|
| 30 |
+
numpy==2.2.5
|
| 31 |
+
pillow==11.2.1
|
| 32 |
+
accelerate==1.6.0
|
| 33 |
+
ultralytics>=8.1.0
|
| 34 |
+
|
| 35 |
+
# ─── unstructured docs & OCR ───────────────────────────────────────────────────
|
| 36 |
+
unstructured==0.17.2
|
| 37 |
+
unstructured_inference==0.8.10
|
| 38 |
+
unstructured-pytesseract==0.3.15
|
| 39 |
+
pdfminer.six==20250506
|
| 40 |
+
pi_heif==0.22.0
|
| 41 |
+
pdf2image==1.17.0
|
| 42 |
+
pytesseract==0.3.13
|
| 43 |
+
openpyxl==3.1.5
|
| 44 |
+
ffmpeg-python==0.2.0
|
| 45 |
+
soundfile==0.12.1
|
| 46 |
+
beautifulsoup4==4.12.3 # Added for web page parsing
|
| 47 |
+
|
| 48 |
+
# ─── resolver hot-spots pinned to cut install time ─────────────────────────────
|
| 49 |
+
httpx==0.27.2 # gradio needs ≥0.24,<1 — this satisfies everything
|
| 50 |
+
attrs==23.2.0 # aiohttp dependency, explicit to avoid back-tracking
|
run_local.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, argparse, pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
from agent import OptimaAgent
|
| 8 |
+
|
| 9 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
+
DOWNLOAD_DIR = "downloaded_files" # Files downloaded by run_local.py go here directly
|
| 11 |
+
DATA_DIR = "data" # Root for persistent data like videos and frames (task_id structured)
|
| 12 |
+
|
| 13 |
+
def main(file: str):
|
| 14 |
+
# Ensure root download and data directories exist
|
| 15 |
+
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 16 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 17 |
+
# Further subdirectories like data/videos or data/frames will be created by tools
|
| 18 |
+
|
| 19 |
+
agent = OptimaAgent()
|
| 20 |
+
|
| 21 |
+
print(f"Processing questions from file: {file}...")
|
| 22 |
+
qs = json.load(open(file))
|
| 23 |
+
rows = []
|
| 24 |
+
for item in qs:
|
| 25 |
+
print("processing item:", item)
|
| 26 |
+
file_path = None
|
| 27 |
+
task_id = item["task_id"]
|
| 28 |
+
|
| 29 |
+
if "file_name" in item and item["file_name"]:
|
| 30 |
+
file_name = item["file_name"] # This is usually <task_id>.<ext>
|
| 31 |
+
file_url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 32 |
+
# Save directly into DOWNLOAD_DIR
|
| 33 |
+
local_file_path = os.path.join(DOWNLOAD_DIR, file_name)
|
| 34 |
+
|
| 35 |
+
print(f"Downloading file for task {task_id}: {file_name} to {local_file_path}...")
|
| 36 |
+
try:
|
| 37 |
+
response = requests.get(file_url, stream=True)
|
| 38 |
+
response.raise_for_status()
|
| 39 |
+
with open(local_file_path, "wb") as f:
|
| 40 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 41 |
+
f.write(chunk)
|
| 42 |
+
print(f"Successfully downloaded to {local_file_path}")
|
| 43 |
+
file_path = local_file_path
|
| 44 |
+
except requests.exceptions.RequestException as e:
|
| 45 |
+
print(f"Error downloading file for task {task_id}: {e}")
|
| 46 |
+
|
| 47 |
+
# Call agent with question, task_id, and potential file path
|
| 48 |
+
answer = agent(item["question"], task_id=task_id, file_path=file_path)
|
| 49 |
+
rows.append(
|
| 50 |
+
{
|
| 51 |
+
"task_id": task_id,
|
| 52 |
+
"question": item["question"][:60] + "…",
|
| 53 |
+
"answer": answer,
|
| 54 |
+
}
|
| 55 |
+
)
|
| 56 |
+
print(pd.DataFrame(rows))
|
| 57 |
+
print("DONE")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
parser = argparse.ArgumentParser()
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"-f",
|
| 64 |
+
"--file",
|
| 65 |
+
default="questions.json",
|
| 66 |
+
help="Path to the questions JSON file.",
|
| 67 |
+
)
|
| 68 |
+
main(**vars(parser.parse_args()))
|
tools/__init__.py
ADDED
|
File without changes
|
tools/classify_entities.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Union, Dict
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
# Load the CLIP model and processor once when the module is imported
|
| 8 |
+
# Using a common pre-trained model
|
| 9 |
+
MODEL_NAME = "openai/clip-vit-base-patch32"
|
| 10 |
+
# Revert to use_fast=False to avoid '_valid_processor_keys' error with padding/truncation
|
| 11 |
+
processor = CLIPProcessor.from_pretrained(MODEL_NAME, use_fast=False)
|
| 12 |
+
model = CLIPModel.from_pretrained(MODEL_NAME)
|
| 13 |
+
|
| 14 |
+
# Determine device
|
| 15 |
+
device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
|
| 16 |
+
model.to(device)
|
| 17 |
+
|
| 18 |
+
def classify_entities(image_paths_or_crops: List[Union[str, Image.Image]],
|
| 19 |
+
candidate_labels: List[str],
|
| 20 |
+
batch_size: int = 8) -> List[List[Dict[str, Union[str, float]]]] :
|
| 21 |
+
"""Classifies objects in cropped regions or image paths against candidate labels using CLIP.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
image_paths_or_crops: A list of either file paths to images or PIL Image objects.
|
| 25 |
+
candidate_labels: A list of strings representing the categories to classify against
|
| 26 |
+
(e.g., ['a photo of a cat', 'a photo of a dog']).
|
| 27 |
+
batch_size: Number of images to process in a single batch.
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
A list of lists of dictionaries. Each inner list corresponds to an input image/crop,
|
| 31 |
+
and contains dictionaries with 'label' and 'score' for each candidate label.
|
| 32 |
+
Example: [[{'label': 'cat', 'score': 0.9}, {'label': 'dog', 'score': 0.1}], ...]
|
| 33 |
+
"""
|
| 34 |
+
if not image_paths_or_crops:
|
| 35 |
+
return []
|
| 36 |
+
if not candidate_labels:
|
| 37 |
+
raise ValueError("Candidate labels must be provided for classification.")
|
| 38 |
+
|
| 39 |
+
all_classifications = []
|
| 40 |
+
|
| 41 |
+
for i in range(0, len(image_paths_or_crops), batch_size):
|
| 42 |
+
batch_items = image_paths_or_crops[i:i+batch_size]
|
| 43 |
+
images_to_process = []
|
| 44 |
+
for item in batch_items:
|
| 45 |
+
if isinstance(item, str):
|
| 46 |
+
if not os.path.exists(item):
|
| 47 |
+
print(f"Warning: Image path {item} not found. Skipping.")
|
| 48 |
+
# Add a placeholder for skipped items to maintain result structure if needed
|
| 49 |
+
# For now, just skipping it means the output list will be shorter
|
| 50 |
+
continue
|
| 51 |
+
try:
|
| 52 |
+
img = Image.open(item).convert("RGB")
|
| 53 |
+
images_to_process.append(img)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Error opening or processing image {item}: {e}. Skipping.")
|
| 56 |
+
continue
|
| 57 |
+
elif isinstance(item, Image.Image):
|
| 58 |
+
images_to_process.append(item.convert("RGB"))
|
| 59 |
+
else:
|
| 60 |
+
print(f"Warning: Invalid item type {type(item)}. Skipping.")
|
| 61 |
+
continue
|
| 62 |
+
|
| 63 |
+
if not images_to_process:
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
# Re-add padding and truncation as they are generally needed for text batching
|
| 68 |
+
inputs = processor(text=candidate_labels, images=images_to_process,
|
| 69 |
+
return_tensors="pt", padding=True, truncation=True).to(device)
|
| 70 |
+
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
outputs = model(**inputs)
|
| 73 |
+
|
| 74 |
+
logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 75 |
+
probs = logits_per_image.softmax(dim=1) # we can take the softmax to get probabilities
|
| 76 |
+
|
| 77 |
+
batch_results = []
|
| 78 |
+
for j in range(len(images_to_process)):
|
| 79 |
+
image_scores = []
|
| 80 |
+
for k, label in enumerate(candidate_labels):
|
| 81 |
+
image_scores.append({"label": label, "score": float(probs[j, k].item())})
|
| 82 |
+
# Sort by score descending
|
| 83 |
+
image_scores.sort(key=lambda x: x['score'], reverse=True)
|
| 84 |
+
batch_results.append(image_scores)
|
| 85 |
+
all_classifications.extend(batch_results)
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"Error during CLIP processing batch starting at index {i}: {e}")
|
| 89 |
+
# Add empty results for this batch to maintain structure, or handle error as needed
|
| 90 |
+
for _ in images_to_process: # Ensure one result per attempted image in batch
|
| 91 |
+
all_classifications.append([{"label": "error", "score": 0.0}])
|
| 92 |
+
|
| 93 |
+
item_count = len(image_paths_or_crops)
|
| 94 |
+
print(f"Classified {len(all_classifications)} items (expected {item_count}) against {len(candidate_labels)} labels.")
|
| 95 |
+
return all_classifications
|
| 96 |
+
|
| 97 |
+
# Example usage (for testing):
|
| 98 |
+
# if __name__ == '__main__':
|
| 99 |
+
# # Create dummy image files for testing
|
| 100 |
+
# import numpy as np
|
| 101 |
+
# os.makedirs("temp_test_images", exist_ok=True)
|
| 102 |
+
# dummy_image_path1 = "temp_test_images/dummy_clip_1.png"
|
| 103 |
+
# dummy_image_path2 = "temp_test_images/dummy_clip_2.png"
|
| 104 |
+
# cv2.imwrite(dummy_image_path1, np.random.randint(0, 255, size=(100, 100, 3), dtype=np.uint8))
|
| 105 |
+
# pil_img = Image.fromarray(np.random.randint(0, 255, size=(120, 120, 3), dtype=np.uint8))
|
| 106 |
+
|
| 107 |
+
# labels_to_test = ["a photo of a dog", "a drawing of a cat", "a landscape scene", "a red car"]
|
| 108 |
+
|
| 109 |
+
# classifications = classify_entities(
|
| 110 |
+
# [dummy_image_path1, pil_img, "non_existent_image.jpg"],
|
| 111 |
+
# candidate_labels=labels_to_test
|
| 112 |
+
# )
|
| 113 |
+
|
| 114 |
+
# for i, result_set in enumerate(classifications):
|
| 115 |
+
# print(f"Results for image {i+1}:")
|
| 116 |
+
# for res in result_set:
|
| 117 |
+
# print(f" Label: {res['label']}, Score: {res['score']:.4f}")
|
| 118 |
+
|
| 119 |
+
# if os.path.exists(dummy_image_path1): os.remove(dummy_image_path1)
|
| 120 |
+
# if os.path.exists(dummy_image_path2): os.remove(dummy_image_path2) # was never created, but good practice
|
| 121 |
+
# if os.path.exists("temp_test_images"): os.rmdir("temp_test_images")
|
tools/detect_objects.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Optional
|
| 2 |
+
import os
|
| 3 |
+
from ultralytics import YOLO
|
| 4 |
+
import cv2 # For loading image to get dimensions if needed
|
| 5 |
+
|
| 6 |
+
# Load the YOLOv8 model once when the module is imported
|
| 7 |
+
# We'll use a small, general-purpose model. You can choose others like yolov8n.pt, yolov8s.pt, etc.
|
| 8 |
+
# Or even a custom-trained model path.
|
| 9 |
+
model = YOLO("yolov8x.pt")
|
| 10 |
+
|
| 11 |
+
def detect_objects(frame_path: str, labels: Optional[List[str]] = None) -> List[Dict]:
|
| 12 |
+
"""Runs object detection on a frame using YOLOv8; optionally filters by labels.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
frame_path: Path to the image frame.
|
| 16 |
+
labels: A list of class names to filter by (e.g., ['person', 'car']).
|
| 17 |
+
If None, all detected objects are returned.
|
| 18 |
+
YOLO class names can be found at: https://docs.ultralytics.com/datasets/coco/#classes
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
A list of dictionaries, where each dictionary represents a detected object
|
| 22 |
+
and contains 'label' (class name), 'confidence' (0-1), and 'bbox' ([x_min, y_min, x_max, y_max]).
|
| 23 |
+
"""
|
| 24 |
+
if not os.path.exists(frame_path):
|
| 25 |
+
raise FileNotFoundError(f"Frame file not found: {frame_path}")
|
| 26 |
+
|
| 27 |
+
results = model(frame_path, verbose=False) # verbose=False to reduce console output
|
| 28 |
+
detected_objects = []
|
| 29 |
+
|
| 30 |
+
# Process results list
|
| 31 |
+
for result in results:
|
| 32 |
+
boxes = result.boxes # Boxes object for bounding box outputs
|
| 33 |
+
names = result.names # Class names
|
| 34 |
+
|
| 35 |
+
for i in range(len(boxes)):
|
| 36 |
+
class_id = int(boxes.cls[i])
|
| 37 |
+
class_name = names[class_id]
|
| 38 |
+
confidence = float(boxes.conf[i])
|
| 39 |
+
bbox_tensor = boxes.xyxy[i] # [x_min, y_min, x_max, y_max]
|
| 40 |
+
bbox = [int(coord) for coord in bbox_tensor.tolist()] # Convert to list of ints
|
| 41 |
+
|
| 42 |
+
if labels is None or class_name in labels:
|
| 43 |
+
detected_objects.append({
|
| 44 |
+
"label": class_name,
|
| 45 |
+
"confidence": confidence,
|
| 46 |
+
"bbox": bbox,
|
| 47 |
+
"frame_path": frame_path # Optional: add frame path for context
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
print(f"Detected {len(detected_objects)} objects in {frame_path} (filtered by: {labels if labels else 'All'}).")
|
| 51 |
+
return detected_objects
|
| 52 |
+
|
| 53 |
+
# Example usage (for testing):
|
| 54 |
+
# if __name__ == '__main__':
|
| 55 |
+
# # Create a dummy image file for testing
|
| 56 |
+
# import numpy as np
|
| 57 |
+
# dummy_image_path = "dummy_frame.png"
|
| 58 |
+
# cv2.imwrite(dummy_image_path, np.zeros((640, 480, 3), dtype=np.uint8))
|
| 59 |
+
#
|
| 60 |
+
# detections = detect_objects(dummy_image_path, labels=['person', 'bicycle'])
|
| 61 |
+
# print(detections)
|
| 62 |
+
# if os.path.exists(dummy_image_path):
|
| 63 |
+
# os.remove(dummy_image_path)
|
tools/downloader.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yt_dlp
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# Base directory for all video data
|
| 5 |
+
BASE_VIDEOS_DATA_DIR = os.path.join("data", "videos")
|
| 6 |
+
|
| 7 |
+
def download_video(url: str, task_id: str) -> str:
|
| 8 |
+
"""Downloads YouTube video and returns local path, organized by task_id.
|
| 9 |
+
Creates a subdirectory under data/videos/<task_id>/ to store the video.
|
| 10 |
+
"""
|
| 11 |
+
if not task_id:
|
| 12 |
+
raise ValueError("task_id must be provided to download_video for path organization.")
|
| 13 |
+
|
| 14 |
+
# Task-specific output folder: data/videos/<task_id>/
|
| 15 |
+
video_output_folder = os.path.join(BASE_VIDEOS_DATA_DIR, task_id)
|
| 16 |
+
os.makedirs(video_output_folder, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
ydl_opts = {
|
| 19 |
+
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
|
| 20 |
+
# Output template will save files directly into video_output_folder
|
| 21 |
+
'outtmpl': os.path.join(video_output_folder, '%(id)s.%(ext)s'),
|
| 22 |
+
'quiet': True,
|
| 23 |
+
}
|
| 24 |
+
try:
|
| 25 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 26 |
+
info_dict = ydl.extract_info(url, download=True)
|
| 27 |
+
# The 'outtmpl' option handles the full path including task_id and video_id.%(ext)s
|
| 28 |
+
# ydl.prepare_filename(info_dict) or info_dict.get('filepath') might give the exact path
|
| 29 |
+
# For robustness, construct from known parts or find the downloaded file.
|
| 30 |
+
video_id = info_dict.get("id", None)
|
| 31 |
+
ext = info_dict.get("ext", "mp4")
|
| 32 |
+
|
| 33 |
+
if video_id:
|
| 34 |
+
expected_filename = f"{video_id}.{ext}"
|
| 35 |
+
final_video_path = os.path.join(video_output_folder, expected_filename)
|
| 36 |
+
if os.path.exists(final_video_path):
|
| 37 |
+
return final_video_path
|
| 38 |
+
else:
|
| 39 |
+
# Fallback: yt-dlp might use a slightly different name if title is in outtmpl or if ID is not clean
|
| 40 |
+
# Search for the file if exact match is not found (less robust)
|
| 41 |
+
print(f"Warning: Expected file {final_video_path} not found directly. Searching in {video_output_folder}")
|
| 42 |
+
downloaded_files = os.listdir(video_output_folder)
|
| 43 |
+
if downloaded_files:
|
| 44 |
+
# Try to find a file that contains the video_id if possible
|
| 45 |
+
for f_name in downloaded_files:
|
| 46 |
+
if video_id in f_name and f_name.endswith(f".{ext}"):
|
| 47 |
+
return os.path.join(video_output_folder, f_name)
|
| 48 |
+
# If no specific match, return the first one (assuming only one download per call)
|
| 49 |
+
return os.path.join(video_output_folder, downloaded_files[0])
|
| 50 |
+
raise yt_dlp.utils.DownloadError(f"Downloaded video file for id {video_id} not found in {video_output_folder}.")
|
| 51 |
+
else:
|
| 52 |
+
raise yt_dlp.utils.DownloadError("Could not determine video_id from download info.")
|
| 53 |
+
|
| 54 |
+
except yt_dlp.utils.DownloadError as e:
|
| 55 |
+
print(f"Error downloading video {url} for task {task_id}: {e}")
|
| 56 |
+
raise
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"An unexpected error occurred downloading {url} for task {task_id}: {e}")
|
| 59 |
+
raise
|
tools/e2b_executor.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from pydantic import BaseModel, Field
|
| 3 |
+
from langchain_core.tools import tool
|
| 4 |
+
from e2b_code_interpreter import Sandbox
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# Might want to add validation to the execution result. It might be too large for the LLM to handle.
|
| 9 |
+
|
| 10 |
+
class E2BCodeExecutionInput(BaseModel):
|
| 11 |
+
code: str | None = Field(
|
| 12 |
+
default=None, description="The Python code string to execute."
|
| 13 |
+
)
|
| 14 |
+
file_path: str | None = Field(
|
| 15 |
+
default=None, description="Path to a Python file to execute."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@tool("execute_python_code_e2b", args_schema=E2BCodeExecutionInput)
|
| 20 |
+
def execute_python_e2b_tool(
|
| 21 |
+
code: str | None = None, file_path: str | None = None
|
| 22 |
+
) -> str:
|
| 23 |
+
"""
|
| 24 |
+
Execute Python code in a secure E2B sandbox. Only one argument is allowed. Either a code snippet (string) or a python file path (string).
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
code: The Python code string to execute.
|
| 28 |
+
file_path: Path to a Python file to execute.
|
| 29 |
+
"""
|
| 30 |
+
print("execute_python_code_e2b called with code:", code, "and file_path:", file_path)
|
| 31 |
+
if not os.getenv("E2B_API_KEY"):
|
| 32 |
+
raise ValueError("E2B_API_KEY is not set. Please set this environment variable.")
|
| 33 |
+
|
| 34 |
+
if file_path and code:
|
| 35 |
+
raise ValueError("Provide either code or a file_path, not both.")
|
| 36 |
+
|
| 37 |
+
if file_path:
|
| 38 |
+
try:
|
| 39 |
+
expanded_file_path = Path(file_path).expanduser()
|
| 40 |
+
if not expanded_file_path.is_file():
|
| 41 |
+
raise FileNotFoundError(f"The file {expanded_file_path} was not found.")
|
| 42 |
+
with open(expanded_file_path, "r") as f:
|
| 43 |
+
code = f.read()
|
| 44 |
+
except FileNotFoundError as e:
|
| 45 |
+
raise
|
| 46 |
+
except Exception as e:
|
| 47 |
+
raise RuntimeError(f"Error reading file {file_path}: {str(e)}")
|
| 48 |
+
|
| 49 |
+
if not code:
|
| 50 |
+
raise ValueError("No code provided to execute. Either pass a code string or a valid file_path.")
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
with Sandbox() as sandbox:
|
| 54 |
+
execution = sandbox.run_code(code)
|
| 55 |
+
if execution.logs.stdout:
|
| 56 |
+
print(f"E2B Sandbox stdout:\n{execution.logs.stdout}")
|
| 57 |
+
if execution.logs.stderr:
|
| 58 |
+
print(f"E2B Sandbox stderr:\n{execution.logs.stderr}")
|
| 59 |
+
if execution.error:
|
| 60 |
+
error_info = {
|
| 61 |
+
"error_type": "E2BSandboxError",
|
| 62 |
+
"message": execution.error.message,
|
| 63 |
+
"traceback": execution.error.traceback,
|
| 64 |
+
"name": execution.error.name
|
| 65 |
+
}
|
| 66 |
+
return json.dumps({"e2b_execution_error": error_info})
|
| 67 |
+
|
| 68 |
+
return execution.to_json()
|
| 69 |
+
except Exception as e:
|
| 70 |
+
raise RuntimeError(f"An unexpected error occurred during E2B sandbox execution: {str(e)}")
|
tools/image_processor.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
This module provides functions to process an image and answer questions about it
|
| 3 |
+
using OpenAI's vision-capable models (e.g., GPT-4o).
|
| 4 |
+
'''
|
| 5 |
+
import os
|
| 6 |
+
import base64
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from langchain_openai import ChatOpenAI
|
| 9 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 10 |
+
|
| 11 |
+
# --- Global variables for models (loaded once) ---
|
| 12 |
+
LLM_MODEL = None
|
| 13 |
+
|
| 14 |
+
def _get_mime_type(image_path: str) -> str:
|
| 15 |
+
try:
|
| 16 |
+
extension = os.path.splitext(image_path)[1].lower()
|
| 17 |
+
if extension == ".png":
|
| 18 |
+
return "image/png"
|
| 19 |
+
elif extension in [".jpg", ".jpeg"]:
|
| 20 |
+
return "image/jpeg"
|
| 21 |
+
elif extension == ".gif":
|
| 22 |
+
return "image/gif"
|
| 23 |
+
elif extension == ".webp":
|
| 24 |
+
return "image/webp"
|
| 25 |
+
else:
|
| 26 |
+
# Fallback for unknown types, try to let PIL infer and default to jpeg
|
| 27 |
+
try:
|
| 28 |
+
img = Image.open(image_path)
|
| 29 |
+
format = img.format
|
| 30 |
+
if format == "PNG": return "image/png"
|
| 31 |
+
if format == "JPEG": return "image/jpeg"
|
| 32 |
+
if format == "GIF": return "image/gif"
|
| 33 |
+
if format == "WEBP": return "image/webp"
|
| 34 |
+
except Exception:
|
| 35 |
+
pass # Ignore PIL error if it occurs, use default
|
| 36 |
+
print(f"Warning: Unknown image type for {image_path}, defaulting to image/jpeg. May affect processing.")
|
| 37 |
+
return "image/jpeg" # Default if extension is not recognized
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"Error getting mime type for {image_path}: {e}. Defaulting to image/jpeg.")
|
| 40 |
+
return "image/jpeg"
|
| 41 |
+
|
| 42 |
+
def _encode_image_to_base64(image_path: str) -> str | None:
|
| 43 |
+
'''Encodes an image file to a base64 string.'''
|
| 44 |
+
try:
|
| 45 |
+
with open(image_path, "rb") as image_file:
|
| 46 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 47 |
+
except FileNotFoundError:
|
| 48 |
+
print(f"Error: Image file not found at {image_path}")
|
| 49 |
+
return None
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Error encoding image {image_path}: {e}")
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
def _initialize_models():
|
| 55 |
+
global LLM_MODEL
|
| 56 |
+
|
| 57 |
+
if LLM_MODEL is None:
|
| 58 |
+
try:
|
| 59 |
+
print("Initializing LLM (ChatOpenAI gpt-4o for Vision)...")
|
| 60 |
+
LLM_MODEL = ChatOpenAI(model="gpt-4o", temperature=0.0, api_key=os.getenv("OPENAI_API_KEY"), max_tokens=1024) # GPT-4o is vision-capable
|
| 61 |
+
print("Vision LLM initialized successfully.")
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"Error initializing Vision LLM: {e}. Image Q&A will not work.")
|
| 64 |
+
LLM_MODEL = None # Ensure it's None if failed
|
| 65 |
+
|
| 66 |
+
_initialize_models() # Initialize models when the module is loaded
|
| 67 |
+
|
| 68 |
+
def process_image_and_answer(image_path: str, question: str, task_id: str | None = None) -> dict:
|
| 69 |
+
'''
|
| 70 |
+
Processes an image to answer a question about it using OpenAI's GPT-4o (Vision).
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
image_path: Path to the image file.
|
| 74 |
+
question: The question to answer about the image.
|
| 75 |
+
task_id: An optional task ID for tracking.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
A dictionary containing the input parameters, a status message, and the answer.
|
| 79 |
+
'''
|
| 80 |
+
print(f"Processing image '{image_path}' for question '{question}' (Task ID: {task_id}) using GPT-4o Vision.")
|
| 81 |
+
|
| 82 |
+
if LLM_MODEL is None:
|
| 83 |
+
return {
|
| 84 |
+
"image_path": image_path,
|
| 85 |
+
"question": question,
|
| 86 |
+
"task_id": task_id,
|
| 87 |
+
"description": "N/A - Vision LLM not initialized",
|
| 88 |
+
"answer": "Error: Vision LLM is not initialized.",
|
| 89 |
+
"status": "Error: LLM not initialized"
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
base64_image = _encode_image_to_base64(image_path)
|
| 93 |
+
if base64_image is None:
|
| 94 |
+
return {
|
| 95 |
+
"image_path": image_path,
|
| 96 |
+
"question": question,
|
| 97 |
+
"task_id": task_id,
|
| 98 |
+
"description": "N/A - Image encoding failed",
|
| 99 |
+
"answer": f"Error: Could not encode image at {image_path}. Check logs.",
|
| 100 |
+
"status": "Error: Image encoding failed"
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
mime_type = _get_mime_type(image_path)
|
| 104 |
+
|
| 105 |
+
# System prompt can guide the LLM on how to behave, even for vision tasks.
|
| 106 |
+
# For chess, asking for algebraic notation is a good idea.
|
| 107 |
+
system_prompt_content = (
|
| 108 |
+
"You are an expert AI assistant analyzing an image. Answer the user's question based on the visual content of the image. "
|
| 109 |
+
"If the question is about a chess position, and you can identify it, provide the answer in algebraic notation (e.g., Qb7, Nxf3). "
|
| 110 |
+
"Be precise and focus only on what is visible in the image and relevant to the question."
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
messages = [
|
| 114 |
+
SystemMessage(content=system_prompt_content),
|
| 115 |
+
HumanMessage(
|
| 116 |
+
content=[
|
| 117 |
+
{"type": "text", "text": question},
|
| 118 |
+
{
|
| 119 |
+
"type": "image_url",
|
| 120 |
+
"image_url": {
|
| 121 |
+
"url": f"data:{mime_type};base64,{base64_image}"
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
]
|
| 125 |
+
)
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
print(f"Sending image and question to GPT-4o Vision...")
|
| 130 |
+
response = LLM_MODEL.invoke(messages)
|
| 131 |
+
answer = response.content
|
| 132 |
+
print(f"Successfully received answer from GPT-4o Vision: {answer[:200]}...")
|
| 133 |
+
status = "Success"
|
| 134 |
+
description = "Image processed directly by Vision LLM."
|
| 135 |
+
except Exception as e:
|
| 136 |
+
print(f"Error calling OpenAI Vision API: {e}")
|
| 137 |
+
answer = f"Error: Could not get answer from Vision LLM. Details: {str(e)}"
|
| 138 |
+
status = "Error: Vision API call failed"
|
| 139 |
+
description = "N/A - Vision API call error"
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"image_path": image_path,
|
| 143 |
+
"question": question,
|
| 144 |
+
"task_id": task_id,
|
| 145 |
+
"description": description,
|
| 146 |
+
"answer": answer,
|
| 147 |
+
"status": status
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
if __name__ == '__main__':
|
| 151 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 152 |
+
print("WARNING: OPENAI_API_KEY not set. GPT-4o Vision calls will fail.")
|
| 153 |
+
|
| 154 |
+
dummy_image_path = "dummy_test_image.png"
|
| 155 |
+
is_dummy_created = False
|
| 156 |
+
try:
|
| 157 |
+
img = Image.new('RGB', (60, 30), color = 'red') # Create a simple red image
|
| 158 |
+
img.save(dummy_image_path, "PNG")
|
| 159 |
+
print(f"Created dummy PNG file for testing: {dummy_image_path}")
|
| 160 |
+
is_dummy_created = True
|
| 161 |
+
except Exception as e:
|
| 162 |
+
print(f"Could not create dummy PNG for testing: {e}. Ensure current directory is writable or provide a valid image path for testing.")
|
| 163 |
+
|
| 164 |
+
if is_dummy_created or os.path.exists(dummy_image_path):
|
| 165 |
+
print(f"\n--- Testing with image: {dummy_image_path} ---")
|
| 166 |
+
|
| 167 |
+
test_question_color = "What is the dominant color of this image?"
|
| 168 |
+
test_task_id_color = "test-vision-color-001"
|
| 169 |
+
print(f"\nRunning color question: '{test_question_color}'")
|
| 170 |
+
result_color = process_image_and_answer(dummy_image_path, test_question_color, test_task_id_color)
|
| 171 |
+
print("\n--- Color Question Test Run Output ---")
|
| 172 |
+
for key, value in result_color.items():
|
| 173 |
+
print(f"{key.capitalize()}: {value}")
|
| 174 |
+
print("------------------------------------")
|
| 175 |
+
|
| 176 |
+
# This will still be a tough test for the dummy image, but tests the flow
|
| 177 |
+
test_question_chess = "If this were a chess board with a queen on a1, what color is the queen?"
|
| 178 |
+
test_task_id_chess = "test-vision-chess-001"
|
| 179 |
+
print(f"\nRunning hypothetical chess question: '{test_question_chess}'")
|
| 180 |
+
result_chess = process_image_and_answer(dummy_image_path, test_question_chess, test_task_id_chess)
|
| 181 |
+
print("\n--- Hypothetical Chess Question Test Run Output ---")
|
| 182 |
+
for key, value in result_chess.items():
|
| 183 |
+
print(f"{key.capitalize()}: {value}")
|
| 184 |
+
print("-----------------------------------------------")
|
| 185 |
+
|
| 186 |
+
if is_dummy_created:
|
| 187 |
+
try:
|
| 188 |
+
os.remove(dummy_image_path)
|
| 189 |
+
print(f"Removed dummy file: {dummy_image_path}")
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print(f"Could not remove dummy file {dummy_image_path}: {e}")
|
| 192 |
+
else:
|
| 193 |
+
print("Skipping example run as dummy image could not be prepared.")
|
tools/ocr_text.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Optional
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import pytesseract
|
| 5 |
+
|
| 6 |
+
def extract_text_from_frame(frame_path: str, lang: Optional[str] = None, config: str = '') -> List[Dict[str, any]]:
|
| 7 |
+
"""Returns text found in frame using OCR (pytesseract).
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
frame_path: Path to the image file.
|
| 11 |
+
lang: Language for Tesseract to use (e.g., 'eng', 'fra'). If None, Tesseract default (usually English) is used.
|
| 12 |
+
config: Additional Tesseract configuration options (e.g., '--psm 6').
|
| 13 |
+
|
| 14 |
+
Returns:
|
| 15 |
+
A list of dictionaries, where each dictionary contains detailed data for a recognized text block.
|
| 16 |
+
Keys include 'level', 'page_num', 'block_num', 'par_num', 'line_num', 'word_num',
|
| 17 |
+
'left', 'top', 'width', 'height', 'conf' (confidence), and 'text'.
|
| 18 |
+
Returns an empty list if no text is found or in case of an error.
|
| 19 |
+
"""
|
| 20 |
+
if not os.path.exists(frame_path):
|
| 21 |
+
raise FileNotFoundError(f"Frame file not found: {frame_path}")
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
img = Image.open(frame_path)
|
| 25 |
+
# Perform OCR using image_to_data to get structured information including bounding boxes and confidence
|
| 26 |
+
# Output type is pandas DataFrame by default, convert to dict for easier use
|
| 27 |
+
ocr_data = pytesseract.image_to_data(img, lang=lang, config=config, output_type=pytesseract.Output.DICT)
|
| 28 |
+
|
| 29 |
+
extracted_elements = []
|
| 30 |
+
num_items = len(ocr_data['text'])
|
| 31 |
+
|
| 32 |
+
for i in range(num_items):
|
| 33 |
+
# Filter out empty text results and results with very low confidence (e.g., placeholder blocks)
|
| 34 |
+
# Tesseract returns -1 for confidence of blocks that are not actual words (e.g. page/block separators)
|
| 35 |
+
# We will only consider items that have actual text and a non-negative confidence.
|
| 36 |
+
text = ocr_data['text'][i].strip()
|
| 37 |
+
confidence = int(ocr_data['conf'][i]) # Convert to int, as Tesseract provides it like this
|
| 38 |
+
|
| 39 |
+
if text and confidence > 0: # Consider only words with positive confidence
|
| 40 |
+
element = {
|
| 41 |
+
"level": ocr_data['level'][i],
|
| 42 |
+
"page_num": ocr_data['page_num'][i],
|
| 43 |
+
"block_num": ocr_data['block_num'][i],
|
| 44 |
+
"par_num": ocr_data['par_num'][i],
|
| 45 |
+
"line_num": ocr_data['line_num'][i],
|
| 46 |
+
"word_num": ocr_data['word_num'][i],
|
| 47 |
+
"left": ocr_data['left'][i],
|
| 48 |
+
"top": ocr_data['top'][i],
|
| 49 |
+
"width": ocr_data['width'][i],
|
| 50 |
+
"height": ocr_data['height'][i],
|
| 51 |
+
"conf": confidence,
|
| 52 |
+
"text": text,
|
| 53 |
+
}
|
| 54 |
+
extracted_elements.append(element)
|
| 55 |
+
|
| 56 |
+
print(f"Extracted {len(extracted_elements)} text elements from {frame_path}.")
|
| 57 |
+
return extracted_elements
|
| 58 |
+
|
| 59 |
+
except pytesseract.TesseractNotFoundError:
|
| 60 |
+
print("Tesseract is not installed or not in your PATH. Please install Tesseract.")
|
| 61 |
+
raise
|
| 62 |
+
except RuntimeError as e:
|
| 63 |
+
# Handles cases like Tesseract not finding language data files
|
| 64 |
+
print(f"Runtime error during OCR for {frame_path}: {e}")
|
| 65 |
+
raise
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"An unexpected error occurred during OCR for {frame_path}: {e}")
|
| 68 |
+
# Return empty list for other errors, or re-raise if critical
|
| 69 |
+
return []
|
| 70 |
+
|
| 71 |
+
# Example usage (for testing):
|
| 72 |
+
# if __name__ == '__main__':
|
| 73 |
+
# # Create a dummy image file with some text for testing
|
| 74 |
+
# from PIL import Image, ImageDraw, ImageFont
|
| 75 |
+
# import numpy as np
|
| 76 |
+
# import cv2 # for the dummy image creation
|
| 77 |
+
|
| 78 |
+
# dummy_ocr_image_path = "dummy_ocr_frame.png"
|
| 79 |
+
# try:
|
| 80 |
+
# img = Image.new('RGB', (400, 100), color = (255, 255, 255))
|
| 81 |
+
# d = ImageDraw.Draw(img)
|
| 82 |
+
# try:
|
| 83 |
+
# # Try to load a common font, fall back if not found
|
| 84 |
+
# font = ImageFont.truetype("arial.ttf", 20)
|
| 85 |
+
# except IOError:
|
| 86 |
+
# font = ImageFont.load_default()
|
| 87 |
+
# d.text((10,10), "Hello World\nTest OCR 123", fill=(0,0,0), font=font)
|
| 88 |
+
# img.save(dummy_ocr_image_path)
|
| 89 |
+
# print(f"Created dummy OCR image: {dummy_ocr_image_path}")
|
| 90 |
+
|
| 91 |
+
# text_data = extract_text_from_frame(dummy_ocr_image_path, lang='eng')
|
| 92 |
+
# if text_data:
|
| 93 |
+
# print("\nExtracted text data:")
|
| 94 |
+
# for item in text_data:
|
| 95 |
+
# print(f" Text: '{item['text']}', Conf: {item['conf']}, BBox: [{item['left']}, {item['top']}, {item['width']}, {item['height']}]")
|
| 96 |
+
# else:
|
| 97 |
+
# print("No text data extracted or an error occurred.")
|
| 98 |
+
|
| 99 |
+
# except pytesseract.TesseractNotFoundError:
|
| 100 |
+
# print("TEST SKIPPED: Tesseract is not installed or not in your PATH.")
|
| 101 |
+
# except Exception as e:
|
| 102 |
+
# print(f"Error in test setup or execution: {e}")
|
| 103 |
+
# finally:
|
| 104 |
+
# if os.path.exists(dummy_ocr_image_path):
|
| 105 |
+
# os.remove(dummy_ocr_image_path)
|
| 106 |
+
# print(f"Cleaned up {dummy_ocr_image_path}")
|
tools/scene_analyzer.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
# Initialize OpenAI client
|
| 6 |
+
# Ensure your OPENAI_API_KEY environment variable is set
|
| 7 |
+
client = OpenAI()
|
| 8 |
+
|
| 9 |
+
MODEL_ID = "gpt-4o" # Or another model like gpt-3.5-turbo
|
| 10 |
+
|
| 11 |
+
def analyze_scene(all_tool_outputs: Dict[str, Any], question: str) -> Dict[str, Any]:
|
| 12 |
+
"""Interprets aggregated outputs from other vision/audio tools to answer a specific question.
|
| 13 |
+
Focuses on analyzing detailed per-frame species information if provided.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
all_tool_outputs: A dictionary containing results from other tools.
|
| 17 |
+
Expected keys might include 'object_detections', 'text_extractions',
|
| 18 |
+
'audio_transcript', 'frame_classifications', etc.
|
| 19 |
+
question: The user's question that this analysis should answer.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
A dictionary containing the answer and any supporting information.
|
| 23 |
+
E.g., {"answer": "The scene likely contains a cat playing with a red ball.",
|
| 24 |
+
"reasoning": "Object detection found a cat and a ball. Color classification confirmed red for the ball..."}
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
prompt_parts = [
|
| 28 |
+
"You are an AI assistant analyzing outputs from multimedia processing tools.",
|
| 29 |
+
"Your goal is to answer the user's question based on the provided information.",
|
| 30 |
+
"Be concise. If your answer is derived from data linked to a specific frame (e.g., object counts, species identification in a frame), "
|
| 31 |
+
"you MUST state the source frame path (use the base name like 'frame_xxxx.png').",
|
| 32 |
+
"\nUser Question:",
|
| 33 |
+
question,
|
| 34 |
+
"\nTool Outputs Digest:"
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
# Prioritize and structure critical information for the LLM
|
| 38 |
+
if "video_frames_info" in all_tool_outputs:
|
| 39 |
+
prompt_parts.append(f"- Video Context: {all_tool_outputs['video_frames_info']}")
|
| 40 |
+
|
| 41 |
+
if "audio_transcript" in all_tool_outputs and all_tool_outputs["audio_transcript"].get("text"):
|
| 42 |
+
transcript_preview = all_tool_outputs["audio_transcript"]["text"][:300] # Preview of transcript
|
| 43 |
+
prompt_parts.append(f"- Audio Transcript Snippet: {transcript_preview}...")
|
| 44 |
+
|
| 45 |
+
if "ocr_extractions_summary" in all_tool_outputs:
|
| 46 |
+
prompt_parts.append(f"- OCR Summary: {all_tool_outputs['ocr_extractions_summary']}")
|
| 47 |
+
|
| 48 |
+
# Detailed per-frame species information - This is key for species-related questions
|
| 49 |
+
if "per_frame_species_details" in all_tool_outputs and all_tool_outputs["per_frame_species_details"]:
|
| 50 |
+
prompt_parts.append("\n--- Per-Frame Identified Entity Details (e.g., Species) ---")
|
| 51 |
+
# Summarize if too long, but provide enough detail for species counting questions
|
| 52 |
+
details = all_tool_outputs["per_frame_species_details"]
|
| 53 |
+
if len(details) > 5: # If more than 5 frames have species details, summarize
|
| 54 |
+
prompt_parts.append(f"(Showing details for first 3 and last 2 frames with identified entities, out of {len(details)} such frames total)")
|
| 55 |
+
frames_to_show_details = details[:3] + details[-2:]
|
| 56 |
+
else:
|
| 57 |
+
frames_to_show_details = details
|
| 58 |
+
|
| 59 |
+
for item in frames_to_show_details:
|
| 60 |
+
frame_path = item.get("frame_path", "Unknown frame")
|
| 61 |
+
entities = item.get("identified_entities", [])
|
| 62 |
+
entity_descs = [f"{entity.get('identified_label', 'unknown_entity')} (conf: {entity.get('confidence', 0):.2f}) at bbox {entity.get('bbox')}" for entity in entities]
|
| 63 |
+
prompt_parts.append(f"- Frame {os.path.basename(frame_path)}: Detected entities: [{', '.join(entity_descs)}]")
|
| 64 |
+
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.")
|
| 65 |
+
elif "object_detections_summary" in all_tool_outputs: # Fallback if no species details
|
| 66 |
+
prompt_parts.append(f"- Object Detection Summary: {all_tool_outputs['object_detections_summary']}")
|
| 67 |
+
|
| 68 |
+
# Add other summaries if they exist and seem relevant
|
| 69 |
+
# (e.g., text_extractions_summary if not already covered by OCR summary)
|
| 70 |
+
|
| 71 |
+
prompt = "\n".join(prompt_parts)
|
| 72 |
+
|
| 73 |
+
# print(f"\n--- Sending request to LLM for scene analysis ({MODEL_ID}) ---")
|
| 74 |
+
# print(f"Prompt (approx {len(prompt.split())} tokens): \n{prompt[:1500]}...")
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
completion = client.chat.completions.create(
|
| 78 |
+
model=MODEL_ID,
|
| 79 |
+
messages=[
|
| 80 |
+
{"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."},
|
| 81 |
+
{"role": "user", "content": prompt}
|
| 82 |
+
],
|
| 83 |
+
temperature=0.2, # Lower temperature for more factual interpretation
|
| 84 |
+
max_tokens=600
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
answer_content = completion.choices[0].message.content.strip()
|
| 88 |
+
|
| 89 |
+
# Attempt to parse the source frame from the answer if mentioned
|
| 90 |
+
# This is a simple heuristic; more robust parsing might be needed if format varies wildly
|
| 91 |
+
source_frame_mention = ""
|
| 92 |
+
words = answer_content.split()
|
| 93 |
+
for i, word in enumerate(words):
|
| 94 |
+
if "frame_" in word and ".png" in word:
|
| 95 |
+
# Extract the frame name like frame_xxxx.png
|
| 96 |
+
source_frame_mention = os.path.basename(word.strip('.,;:!?()[]{}'))
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
# print(f"LLM ({MODEL_ID}) analysis complete. Tokens used: Prompt={completion.usage.prompt_tokens}, Completion={completion.usage.completion_tokens}")
|
| 100 |
+
return {
|
| 101 |
+
"answer": answer_content,
|
| 102 |
+
"source_frame": source_frame_mention if source_frame_mention else "Not specified or N/A",
|
| 103 |
+
"model_used": MODEL_ID,
|
| 104 |
+
"prompt_tokens": completion.usage.prompt_tokens if completion.usage else None,
|
| 105 |
+
"completion_tokens": completion.usage.completion_tokens if completion.usage else None,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"Error calling OpenAI API for scene analysis: {e}")
|
| 110 |
+
return {
|
| 111 |
+
"answer": "Error: Could not complete scene analysis due to an API error.",
|
| 112 |
+
"source_frame": "Error",
|
| 113 |
+
"error_details": str(e)
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# Example usage (for testing - requires other tools to have produced sample outputs):
|
| 117 |
+
# if __name__ == '__main__':
|
| 118 |
+
# sample_tool_outputs = {
|
| 119 |
+
# "object_detections": [
|
| 120 |
+
# {"label": "cat", "confidence": 0.9, "bbox": [10, 10, 50, 50]},
|
| 121 |
+
# {"label": "ball", "confidence": 0.8, "bbox": [60, 60, 80, 80]},
|
| 122 |
+
# {"label": "dog", "confidence": 0.7, "bbox": [100,100,150,150], "frame_path": "data/frames/video1/frame_0001.png"}
|
| 123 |
+
# ],
|
| 124 |
+
# "text_extractions": [
|
| 125 |
+
# {"text": "EXIT", "conf": 95, "bbox": [200, 50, 250, 70], "frame_path": "data/frames/video1/frame_0002.png"}
|
| 126 |
+
# ],
|
| 127 |
+
# "audio_transcript": {
|
| 128 |
+
# "text": "The cat is meowing loudly near the red ball.",
|
| 129 |
+
# "language": "en"
|
| 130 |
+
# },
|
| 131 |
+
# "frame_classifications": [
|
| 132 |
+
# [
|
| 133 |
+
# {"label": "a photo of indoor scene", "score": 0.85},
|
| 134 |
+
# {"label": "a photo of outdoor scene", "score": 0.15}
|
| 135 |
+
# ]
|
| 136 |
+
# ]
|
| 137 |
+
# }
|
| 138 |
+
# user_question = "What is happening with the cat and the ball? Is there any text visible?"
|
| 139 |
+
|
| 140 |
+
# analysis_result = analyze_scene(sample_tool_outputs, user_question)
|
| 141 |
+
# print("\n--- Analysis Result ---")
|
| 142 |
+
# print(f"Answer: {analysis_result.get('answer')}")
|
| 143 |
+
# if analysis_result.get('error_details'):
|
| 144 |
+
# print(f"Error: {analysis_result.get('error_details')}")
|
tools/segmenter.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import os
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
# Base directory for all frame data
|
| 6 |
+
BASE_FRAMES_DATA_DIR = os.path.join("data", "frames")
|
| 7 |
+
|
| 8 |
+
def segment_video(video_path: str, task_id: str, frames_per_second: int = 1) -> List[str]:
|
| 9 |
+
"""Extracts key frames from a video, organized by task_id and video_id, and returns a list of frame paths."""
|
| 10 |
+
if not task_id:
|
| 11 |
+
raise ValueError("task_id must be provided to segment_video for path organization.")
|
| 12 |
+
if not os.path.exists(video_path):
|
| 13 |
+
# This video_path should already be task_id specific if download_video was used correctly
|
| 14 |
+
raise FileNotFoundError(f"Video file not found: {video_path}")
|
| 15 |
+
|
| 16 |
+
video_id = os.path.splitext(os.path.basename(video_path))[0]
|
| 17 |
+
# frames_output_folder: data/frames/<task_id>/<video_id>/
|
| 18 |
+
task_video_frames_dir = os.path.join(BASE_FRAMES_DATA_DIR, task_id, video_id)
|
| 19 |
+
os.makedirs(task_video_frames_dir, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
frame_paths = []
|
| 22 |
+
try:
|
| 23 |
+
cap = cv2.VideoCapture(video_path)
|
| 24 |
+
if not cap.isOpened():
|
| 25 |
+
raise IOError(f"Could not open video file: {video_path}")
|
| 26 |
+
|
| 27 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 28 |
+
if fps == 0:
|
| 29 |
+
print(f"Warning: Could not get FPS for {video_path}. Assuming 30 FPS.")
|
| 30 |
+
fps = 30 # Default if FPS is not available
|
| 31 |
+
|
| 32 |
+
frame_interval = int(fps / frames_per_second)
|
| 33 |
+
if frame_interval == 0:
|
| 34 |
+
frame_interval = 1 # Ensure at least one frame is processed if frames_per_second > fps
|
| 35 |
+
|
| 36 |
+
frame_count = 0
|
| 37 |
+
saved_frame_count = 0
|
| 38 |
+
while True:
|
| 39 |
+
ret, frame = cap.read()
|
| 40 |
+
if not ret:
|
| 41 |
+
break
|
| 42 |
+
|
| 43 |
+
if frame_count % frame_interval == 0:
|
| 44 |
+
frame_filename = os.path.join(task_video_frames_dir, f"frame_{saved_frame_count:04d}.png")
|
| 45 |
+
cv2.imwrite(frame_filename, frame)
|
| 46 |
+
frame_paths.append(frame_filename)
|
| 47 |
+
saved_frame_count += 1
|
| 48 |
+
|
| 49 |
+
frame_count += 1
|
| 50 |
+
|
| 51 |
+
except cv2.error as e:
|
| 52 |
+
print(f"OpenCV error processing video {video_path} for task {task_id}: {e}")
|
| 53 |
+
raise
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Error segmenting video {video_path} for task {task_id}: {e}")
|
| 56 |
+
raise
|
| 57 |
+
finally:
|
| 58 |
+
if 'cap' in locals() and cap.isOpened():
|
| 59 |
+
cap.release()
|
| 60 |
+
|
| 61 |
+
if not frame_paths:
|
| 62 |
+
print(f"Warning: No frames were extracted from {video_path} (Task ID: {task_id}).")
|
| 63 |
+
|
| 64 |
+
print(f"Segmented video {video_path} (Task ID: {task_id}). Extracted {len(frame_paths)} frames to {task_video_frames_dir}")
|
| 65 |
+
return frame_paths
|
tools/transcriber.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from faster_whisper import WhisperModel
|
| 3 |
+
import tempfile
|
| 4 |
+
import ffmpeg # For audio extraction if yt-dlp doesn't provide a clean audio file or for format conversion
|
| 5 |
+
|
| 6 |
+
# Load the Whisper model once when the module is imported
|
| 7 |
+
# Model sizes: "tiny", "tiny.en", "base", "base.en", "small", "small.en",
|
| 8 |
+
# "medium", "medium.en", "large-v1", "large-v2", "large-v3"
|
| 9 |
+
# Using "base.en" for a balance of speed and accuracy for English.
|
| 10 |
+
# You can change this to a larger model for better accuracy or a multilingual model.
|
| 11 |
+
MODEL_SIZE = "base.en"
|
| 12 |
+
# Run on GPU with FP16
|
| 13 |
+
# model = WhisperModel(MODEL_SIZE, device="cuda", compute_type="float16")
|
| 14 |
+
# or run on GPU with INT8
|
| 15 |
+
# model = WhisperModel(MODEL_SIZE, device="cuda", compute_type="int8_float16")
|
| 16 |
+
# or run on CPU with INT8
|
| 17 |
+
model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8") # Good for CPU
|
| 18 |
+
|
| 19 |
+
def transcribe_audio(video_or_audio_path: str,
|
| 20 |
+
language: str = None,
|
| 21 |
+
task: str = "transcribe",
|
| 22 |
+
beam_size: int = 5,
|
| 23 |
+
word_timestamps: bool = False) -> dict:
|
| 24 |
+
"""Returns full transcript from video or audio file using faster-whisper.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
video_or_audio_path: Path to the video or audio file.
|
| 28 |
+
language: Language code (e.g., 'en', 'es'). If None, auto-detects.
|
| 29 |
+
task: 'transcribe' or 'translate' (to English).
|
| 30 |
+
beam_size: Beam size for decoding.
|
| 31 |
+
word_timestamps: Whether to include word-level timestamps.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
A dictionary containing the full text and optionally segments with timestamps.
|
| 35 |
+
E.g., {"text": "Hello world.", "segments": [...], "language": "en"}
|
| 36 |
+
"""
|
| 37 |
+
if not os.path.exists(video_or_audio_path):
|
| 38 |
+
raise FileNotFoundError(f"Media file not found: {video_or_audio_path}")
|
| 39 |
+
|
| 40 |
+
print(f"Transcribing audio for {video_or_audio_path} using model {MODEL_SIZE}...")
|
| 41 |
+
|
| 42 |
+
# Whisper works best with audio files. If it's a video, extract audio first.
|
| 43 |
+
# Common audio formats like wav, mp3 are fine. We can use ffmpeg to ensure compatibility.
|
| 44 |
+
# Create a temporary file for the audio if extraction or conversion is needed.
|
| 45 |
+
|
| 46 |
+
# Check if it's a common audio format, otherwise assume it might be video or needs conversion
|
| 47 |
+
is_common_audio = video_or_audio_path.lower().endswith(('.wav', '.mp3', '.m4a', '.aac', '.ogg', '.flac'))
|
| 48 |
+
|
| 49 |
+
temp_audio_file = None
|
| 50 |
+
audio_to_transcribe = video_or_audio_path
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
if not is_common_audio:
|
| 54 |
+
print(f"Input {video_or_audio_path} is not a standard audio file, attempting to extract/convert audio.")
|
| 55 |
+
# Create a temporary WAV file for the extracted audio
|
| 56 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
|
| 57 |
+
temp_audio_file_name = tmpfile.name
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
ffmpeg.input(video_or_audio_path).output(temp_audio_file_name, acodec='pcm_s16le', ar='16000', ac=1).run(quiet=True, overwrite_output=True)
|
| 61 |
+
audio_to_transcribe = temp_audio_file_name
|
| 62 |
+
print(f"Audio extracted/converted to {audio_to_transcribe}")
|
| 63 |
+
except ffmpeg.Error as e:
|
| 64 |
+
print(f"FFmpeg error during audio extraction/conversion for {video_or_audio_path}: {e.stderr.decode() if e.stderr else str(e)}")
|
| 65 |
+
# Fallback to trying the original file directly if ffmpeg fails
|
| 66 |
+
print("Falling back to transcribing the original file directly.")
|
| 67 |
+
|
| 68 |
+
segments, info = model.transcribe(
|
| 69 |
+
audio_to_transcribe,
|
| 70 |
+
language=language,
|
| 71 |
+
task=task,
|
| 72 |
+
beam_size=beam_size,
|
| 73 |
+
word_timestamps=word_timestamps
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
full_text = ""
|
| 77 |
+
segment_data = []
|
| 78 |
+
for segment in segments:
|
| 79 |
+
full_text += segment.text + " "
|
| 80 |
+
seg_dict = {"start": segment.start, "end": segment.end, "text": segment.text}
|
| 81 |
+
if word_timestamps:
|
| 82 |
+
seg_dict["words"] = [
|
| 83 |
+
{"word": word.word, "start": word.start, "end": word.end, "probability": word.probability}
|
| 84 |
+
for word in segment.words
|
| 85 |
+
]
|
| 86 |
+
segment_data.append(seg_dict)
|
| 87 |
+
|
| 88 |
+
print(f"Transcription complete for {video_or_audio_path}. Detected language: {info.language} with probability {info.language_probability:.2f}")
|
| 89 |
+
|
| 90 |
+
return {
|
| 91 |
+
"text": full_text.strip(),
|
| 92 |
+
"segments": segment_data,
|
| 93 |
+
"language": info.language,
|
| 94 |
+
"language_probability": info.language_probability
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Error during transcription of {video_or_audio_path}: {e}")
|
| 99 |
+
raise
|
| 100 |
+
finally:
|
| 101 |
+
if temp_audio_file and os.path.exists(temp_audio_file):
|
| 102 |
+
print(f"Deleting temporary audio file {temp_audio_file}")
|
| 103 |
+
os.remove(temp_audio_file)
|
| 104 |
+
elif temp_audio_file: # If temp_audio_file was assigned but creation failed
|
| 105 |
+
print(f"Note: Temporary audio file {temp_audio_file} was planned but may not have been created or already cleaned up.")
|
| 106 |
+
|
| 107 |
+
# Example usage (for testing):
|
| 108 |
+
# if __name__ == '__main__':
|
| 109 |
+
# # This requires a test audio/video file.
|
| 110 |
+
# # For example, download a short one with yt-dlp first.
|
| 111 |
+
# # dummy_video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Short, famous video
|
| 112 |
+
# # from tools.downloader import download_video # Assuming downloader.py is in tools/
|
| 113 |
+
# # print(f"Downloading test video...")
|
| 114 |
+
# # test_file_path = download_video(dummy_video_url)
|
| 115 |
+
# # print(f"Test video downloaded to {test_file_path}")
|
| 116 |
+
|
| 117 |
+
# # Create a dummy wav file for testing if no video download is preferred
|
| 118 |
+
# import soundfile as sf
|
| 119 |
+
# import numpy as np
|
| 120 |
+
# dummy_audio_path = "dummy_audio_test.wav"
|
| 121 |
+
# data = np.random.uniform(-0.5, 0.5, 44100 * 2) # 2 seconds of dummy audio
|
| 122 |
+
# sf.write(dummy_audio_path, data, 44100)
|
| 123 |
+
# print(f"Created dummy audio: {dummy_audio_path}")
|
| 124 |
+
# test_file_path = dummy_audio_path
|
| 125 |
+
|
| 126 |
+
# if os.path.exists(test_file_path):
|
| 127 |
+
# print(f"\nTranscribing {test_file_path} (with word timestamps):")
|
| 128 |
+
# transcript_data = transcribe_audio(test_file_path, language="en", word_timestamps=True)
|
| 129 |
+
# print(f"Full text: {transcript_data['text']}")
|
| 130 |
+
# # for i, seg in enumerate(transcript_data['segments']):
|
| 131 |
+
# # print(f" Segment {i+1} ({seg['start']:.2f}s - {seg['end']:.2f}s): {seg['text']}")
|
| 132 |
+
# # if "words" in seg:
|
| 133 |
+
# # for word_info in seg["words"]:
|
| 134 |
+
# # print(f" {word_info['word']} ({word_info['start']:.2f}-{word_info['end']:.2f}) - conf: {word_info['probability']:.2f}")
|
| 135 |
+
|
| 136 |
+
# # print(f"\nTranscribing {test_file_path} (summary, auto language detection):")
|
| 137 |
+
# # transcript_data_simple = transcribe_audio(test_file_path)
|
| 138 |
+
# # print(f"Full text: {transcript_data_simple['text']}")
|
| 139 |
+
# # print(f"Detected language: {transcript_data_simple['language']}")
|
| 140 |
+
|
| 141 |
+
# if test_file_path == dummy_audio_path: # Clean up dummy audio
|
| 142 |
+
# os.remove(test_file_path)
|
| 143 |
+
# print(f"Cleaned up {dummy_audio_path}")
|
| 144 |
+
# # elif test_file_path.startswith("data/videos/"): # Clean up downloaded video
|
| 145 |
+
# # os.remove(test_file_path)
|
| 146 |
+
# # print(f"Cleaned up downloaded video: {test_file_path}")
|
| 147 |
+
# else:
|
| 148 |
+
# print(f"Test file {test_file_path} not found, skipping transcription test.")
|