Spaces:
Configuration error
Configuration error
edwin_ang_ph commited on
Commit ·
f454e61
1
Parent(s): 24138cb
test upload
Browse files- .gitignore +6 -0
- app.py +378 -0
- requirements.txt +11 -0
- tavily_searcher.py +14 -0
- video_question_answer.py +64 -0
- youtube_video_downloader.py +32 -0
- youtube_video_question_answer_tool.py +33 -0
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
env
|
| 2 |
+
.env
|
| 3 |
+
*.mp4
|
| 4 |
+
*.mp3
|
| 5 |
+
*.png
|
| 6 |
+
__pycache__
|
app.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import inspect
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
from langchain.tools import Tool
|
| 10 |
+
from langchain_openai import ChatOpenAI
|
| 11 |
+
from typing import Annotated, Optional, TypedDict
|
| 12 |
+
from langchain_core.messages import AnyMessage, HumanMessage, SystemMessage
|
| 13 |
+
from langgraph.graph.message import add_messages
|
| 14 |
+
from langgraph.graph import StateGraph, START
|
| 15 |
+
from langgraph.prebuilt import tools_condition, ToolNode
|
| 16 |
+
|
| 17 |
+
from tavily_searcher import TavilySearcher
|
| 18 |
+
from youtube_video_question_answer_tool import YoutubeVideoQuestionAnswerTool
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Load environment variables from .env file
|
| 27 |
+
load_dotenv()
|
| 28 |
+
|
| 29 |
+
print(f'os.getenv("HUGGINGFACE_TOKEN"): {os.getenv("HUGGINGFACE_TOKEN")}')
|
| 30 |
+
|
| 31 |
+
# (Keep Constants as is)
|
| 32 |
+
# --- Constants ---
|
| 33 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 34 |
+
ASSOCIATED_FILE_ENDPOINT = f"{DEFAULT_API_URL}/files/"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def retrieve_task_file(task_id: str) -> Optional[bytes]:
|
| 38 |
+
"""
|
| 39 |
+
Retrieve the task file for a given task ID.
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
response = requests.get(ASSOCIATED_FILE_ENDPOINT + task_id, timeout=15)
|
| 43 |
+
response.raise_for_status()
|
| 44 |
+
if response.status_code != 200:
|
| 45 |
+
print(f"Error fetching file: {response.status_code}")
|
| 46 |
+
return None
|
| 47 |
+
#print(f"Fetched file: {response.content}")
|
| 48 |
+
return response.content
|
| 49 |
+
except requests.exceptions.RequestException as e:
|
| 50 |
+
print(f"Error fetching file: {e}")
|
| 51 |
+
return None
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"An unexpected error occurred fetching file: {e}")
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
tavily_search_tool = Tool(
|
| 58 |
+
name="tavily_search",
|
| 59 |
+
func=TavilySearcher().search,
|
| 60 |
+
description="Search the web for a given query."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Initialize the tool
|
| 64 |
+
answer_youtube_video_question_tool = YoutubeVideoQuestionAnswerTool()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def format_gaia_answer(answer: str) -> str:
|
| 70 |
+
llm = ChatOpenAI(model="o3-mini", openai_api_key=os.getenv("OPENAI_API_KEY"))
|
| 71 |
+
prompt = f"""
|
| 72 |
+
You are formatting answers for the GAIA benchmark, which requires responses to be concise and unambiguous.
|
| 73 |
+
Given the answer: {answer}
|
| 74 |
+
Return the answer in the correct GAIA format:
|
| 75 |
+
- If the answer is a single word or number, return it without any additional text or formatting.
|
| 76 |
+
- If the answer is a list, return a comma-separated list without any additional text or formatting.
|
| 77 |
+
- If the answer is a string, return it without any additional text or formatting.
|
| 78 |
+
Do not include any prefixes, dots, enumerations, explanations, or quotation marks.
|
| 79 |
+
Do not include any additional text or formatting.
|
| 80 |
+
"""
|
| 81 |
+
response = llm.invoke(prompt)
|
| 82 |
+
# Delete double quotes
|
| 83 |
+
return response.content.strip().replace('"', '')
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# --- Basic Agent Definition ---
|
| 90 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 91 |
+
|
| 92 |
+
class AgentState(TypedDict):
|
| 93 |
+
messages: Annotated[list[AnyMessage], add_messages]
|
| 94 |
+
file_path: Optional[str]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class BasicAgent:
|
| 98 |
+
def __init__(self):
|
| 99 |
+
tools = [
|
| 100 |
+
tavily_search_tool,
|
| 101 |
+
# arxiv_search_tool,
|
| 102 |
+
# wikipedia_search_tool,
|
| 103 |
+
# transcribe_audio_tool,
|
| 104 |
+
# answer_python_code_tool,
|
| 105 |
+
# answer_image_question_tool,
|
| 106 |
+
answer_youtube_video_question_tool,
|
| 107 |
+
# read_excel_file_tool
|
| 108 |
+
]
|
| 109 |
+
llm = ChatOpenAI(model="o3-mini", openai_api_key=os.getenv("OPENAI_API_KEY"))
|
| 110 |
+
self.llm_with_tools = llm.bind_tools(tools)
|
| 111 |
+
builder = StateGraph(AgentState)
|
| 112 |
+
|
| 113 |
+
# Define nodes: these do the work
|
| 114 |
+
builder.add_node("assistant", self.assistant)
|
| 115 |
+
builder.add_node("tools", ToolNode(tools))
|
| 116 |
+
|
| 117 |
+
# Define edges: these determine how the control flow moves
|
| 118 |
+
builder.add_edge(START, "assistant")
|
| 119 |
+
builder.add_conditional_edges(
|
| 120 |
+
"assistant",
|
| 121 |
+
# If the latest message requires a tool, route to tools
|
| 122 |
+
# Otherwise, provide a direct response
|
| 123 |
+
tools_condition,
|
| 124 |
+
)
|
| 125 |
+
builder.add_edge("tools", "assistant")
|
| 126 |
+
self.agent = builder.compile()
|
| 127 |
+
|
| 128 |
+
print("BasicAgent initialized.")
|
| 129 |
+
|
| 130 |
+
def assistant(self, state: AgentState):
|
| 131 |
+
# System message
|
| 132 |
+
textual_description_of_tools="""
|
| 133 |
+
tavily_search(query: str) -> str:
|
| 134 |
+
Search the web for a given query.
|
| 135 |
+
Args:
|
| 136 |
+
query: Query to search the web for (string).
|
| 137 |
+
Returns:
|
| 138 |
+
A single string containing the information found on the web.
|
| 139 |
+
|
| 140 |
+
answer_youtube_video_question(file_path: str, question: str) -> str:
|
| 141 |
+
Answer the question based on file path of the downloaded youtube video
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
file_path: File path of the downloaded youtube video (string).
|
| 145 |
+
question: Question to answer (string).
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
A single string containing the answer to the question.
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
file_path=state["file_path"]
|
| 153 |
+
prompt = f"""
|
| 154 |
+
You are a helpful assistant that can analyse images, videos, excel files and Python scripts and run computations with provided tools:
|
| 155 |
+
{textual_description_of_tools}
|
| 156 |
+
You have access to the file path of the attached file in case it's informed. Currently the file path is: {file_path}
|
| 157 |
+
Be direct and specific. GAIA benchmark requires exact matching answers.
|
| 158 |
+
For example, if asked "What is the capital of France?", respond simply with "Paris".
|
| 159 |
+
Do not include any prefixes, dots, enumerations, explanations, or quotation marks.
|
| 160 |
+
Do not include any additional text or formatting.
|
| 161 |
+
If you are required a number, return a number, not the items.
|
| 162 |
+
"""
|
| 163 |
+
sys_msg = SystemMessage(content=prompt)
|
| 164 |
+
|
| 165 |
+
return {
|
| 166 |
+
"messages": [self.llm_with_tools.invoke([sys_msg] + state["messages"], config={"configurable": {"file_path": state["file_path"]}})],
|
| 167 |
+
"file_path": state["file_path"]
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def __call__(self, question: str, task_id: str, file_name: str) -> str:
|
| 172 |
+
print(f"######################### Agent received question (first 50 chars): {question[:50]}... with file_name: {file_name}")
|
| 173 |
+
|
| 174 |
+
# Get the file path
|
| 175 |
+
tmp_file_path = None
|
| 176 |
+
if file_name is not None and file_name != "":
|
| 177 |
+
file_content = retrieve_task_file(task_id)
|
| 178 |
+
if file_content is not None:
|
| 179 |
+
print(f"Saving file {file_name} to tmp folder")
|
| 180 |
+
tmp_file_path = f"tmp/{file_name}"
|
| 181 |
+
with open(tmp_file_path, "wb") as f:
|
| 182 |
+
f.write(file_content)
|
| 183 |
+
# Show the file path
|
| 184 |
+
print(f"File path: {tmp_file_path}")
|
| 185 |
+
|
| 186 |
+
messages = self.agent.invoke({"messages": [HumanMessage(question)], "file_path": tmp_file_path})
|
| 187 |
+
print(f"messages: {messages}")
|
| 188 |
+
# Show the messages
|
| 189 |
+
for m in messages['messages']:
|
| 190 |
+
m.pretty_print()
|
| 191 |
+
answer = messages["messages"][-1].content
|
| 192 |
+
answer = format_gaia_answer(answer)
|
| 193 |
+
print(f"######################### Agent returning answer: {answer}\n")
|
| 194 |
+
# Delete the file
|
| 195 |
+
if tmp_file_path is not None:
|
| 196 |
+
os.remove(tmp_file_path)
|
| 197 |
+
return answer
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 203 |
+
"""
|
| 204 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 205 |
+
and displays the results.
|
| 206 |
+
"""
|
| 207 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 208 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 209 |
+
|
| 210 |
+
if profile:
|
| 211 |
+
username= f"{profile.username}"
|
| 212 |
+
print(f"User logged in: {username}")
|
| 213 |
+
else:
|
| 214 |
+
print("User not logged in.")
|
| 215 |
+
return "Please Login to Hugging Face with the button.", None
|
| 216 |
+
|
| 217 |
+
api_url = DEFAULT_API_URL
|
| 218 |
+
questions_url = f"{api_url}/questions"
|
| 219 |
+
submit_url = f"{api_url}/submit"
|
| 220 |
+
|
| 221 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 222 |
+
try:
|
| 223 |
+
agent = BasicAgent()
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f"Error instantiating agent: {e}")
|
| 226 |
+
return f"Error initializing agent: {e}", None
|
| 227 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 228 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 229 |
+
print(agent_code)
|
| 230 |
+
|
| 231 |
+
# 2. Fetch Questions
|
| 232 |
+
print(f"Fetching questions from: {questions_url}")
|
| 233 |
+
try:
|
| 234 |
+
response = requests.get(questions_url, timeout=15)
|
| 235 |
+
response.raise_for_status()
|
| 236 |
+
questions_data = response.json()
|
| 237 |
+
if not questions_data:
|
| 238 |
+
print("Fetched questions list is empty.")
|
| 239 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 240 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 241 |
+
except requests.exceptions.RequestException as e:
|
| 242 |
+
print(f"Error fetching questions: {e}")
|
| 243 |
+
return f"Error fetching questions: {e}", None
|
| 244 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 245 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 246 |
+
print(f"Response text: {response.text[:500]}")
|
| 247 |
+
return f"Error decoding server response for questions: {e}", None
|
| 248 |
+
except Exception as e:
|
| 249 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 250 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 251 |
+
|
| 252 |
+
# 3. Run your Agent
|
| 253 |
+
results_log = []
|
| 254 |
+
answers_payload = []
|
| 255 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 256 |
+
for item in questions_data:
|
| 257 |
+
task_id = item.get("task_id")
|
| 258 |
+
question_text = item.get("question")
|
| 259 |
+
file_name = item.get("file_name") #!
|
| 260 |
+
if not task_id or question_text is None:
|
| 261 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 262 |
+
continue
|
| 263 |
+
try:
|
| 264 |
+
# submitted_answer = agent(question_text)
|
| 265 |
+
submitted_answer = agent(question_text, task_id, file_name)
|
| 266 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 267 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 268 |
+
except Exception as e:
|
| 269 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 270 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 271 |
+
|
| 272 |
+
if not answers_payload:
|
| 273 |
+
print("Agent did not produce any answers to submit.")
|
| 274 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 275 |
+
|
| 276 |
+
# 4. Prepare Submission
|
| 277 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 278 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 279 |
+
print(status_update)
|
| 280 |
+
|
| 281 |
+
# 5. Submit
|
| 282 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 283 |
+
try:
|
| 284 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 285 |
+
response.raise_for_status()
|
| 286 |
+
result_data = response.json()
|
| 287 |
+
final_status = (
|
| 288 |
+
f"Submission Successful!\n"
|
| 289 |
+
f"User: {result_data.get('username')}\n"
|
| 290 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 291 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 292 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 293 |
+
)
|
| 294 |
+
print("Submission successful.")
|
| 295 |
+
results_df = pd.DataFrame(results_log)
|
| 296 |
+
return final_status, results_df
|
| 297 |
+
except requests.exceptions.HTTPError as e:
|
| 298 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 299 |
+
try:
|
| 300 |
+
error_json = e.response.json()
|
| 301 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 302 |
+
except requests.exceptions.JSONDecodeError:
|
| 303 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 304 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 305 |
+
print(status_message)
|
| 306 |
+
results_df = pd.DataFrame(results_log)
|
| 307 |
+
return status_message, results_df
|
| 308 |
+
except requests.exceptions.Timeout:
|
| 309 |
+
status_message = "Submission Failed: The request timed out."
|
| 310 |
+
print(status_message)
|
| 311 |
+
results_df = pd.DataFrame(results_log)
|
| 312 |
+
return status_message, results_df
|
| 313 |
+
except requests.exceptions.RequestException as e:
|
| 314 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 315 |
+
print(status_message)
|
| 316 |
+
results_df = pd.DataFrame(results_log)
|
| 317 |
+
return status_message, results_df
|
| 318 |
+
except Exception as e:
|
| 319 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 320 |
+
print(status_message)
|
| 321 |
+
results_df = pd.DataFrame(results_log)
|
| 322 |
+
return status_message, results_df
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# --- Build Gradio Interface using Blocks ---
|
| 326 |
+
with gr.Blocks() as demo:
|
| 327 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 328 |
+
gr.Markdown(
|
| 329 |
+
"""
|
| 330 |
+
**Instructions:**
|
| 331 |
+
|
| 332 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 333 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 334 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 335 |
+
|
| 336 |
+
---
|
| 337 |
+
**Disclaimers:**
|
| 338 |
+
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 339 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 340 |
+
"""
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
gr.LoginButton()
|
| 344 |
+
|
| 345 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 346 |
+
|
| 347 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 348 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 349 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 350 |
+
|
| 351 |
+
run_button.click(
|
| 352 |
+
fn=run_and_submit_all,
|
| 353 |
+
outputs=[status_output, results_table]
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
if __name__ == "__main__":
|
| 357 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 358 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 359 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 360 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 361 |
+
|
| 362 |
+
if space_host_startup:
|
| 363 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 364 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 365 |
+
else:
|
| 366 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 367 |
+
|
| 368 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 369 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 370 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 371 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 372 |
+
else:
|
| 373 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 374 |
+
|
| 375 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 376 |
+
|
| 377 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 378 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
| 3 |
+
dotenv
|
| 4 |
+
gradio[oauth]
|
| 5 |
+
langchain-community
|
| 6 |
+
langgraph
|
| 7 |
+
langchain-huggingface
|
| 8 |
+
langchain_openai
|
| 9 |
+
langchain_tavily
|
| 10 |
+
google-genai
|
| 11 |
+
yt_dlp
|
tavily_searcher.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_tavily import TavilySearch
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
load_dotenv()
|
| 4 |
+
|
| 5 |
+
class TavilySearcher:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.tavily_search = TavilySearch(max_results=5)
|
| 8 |
+
|
| 9 |
+
def search(self, query: str) -> str:
|
| 10 |
+
return self.tavily_search.run(query)
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
searcher = TavilySearcher()
|
| 14 |
+
print(searcher.search("Kuznetsov in Nedoshivina's 2010 paper"))
|
video_question_answer.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import os
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from google import genai
|
| 5 |
+
from google.genai import types
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
class VideoQuestionAnswer:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
|
| 12 |
+
|
| 13 |
+
def answer(self, youtube_url: str, question: str) -> str:
|
| 14 |
+
print(f"Procesando video de YouTube: {youtube_url}")
|
| 15 |
+
print(f"Pregunta: {question}")
|
| 16 |
+
|
| 17 |
+
response = self.client.models.generate_content(
|
| 18 |
+
model="gemini-2.0-flash",
|
| 19 |
+
contents=types.Content(
|
| 20 |
+
parts=[
|
| 21 |
+
types.Part(
|
| 22 |
+
file_data=types.FileData(file_uri=youtube_url)
|
| 23 |
+
),
|
| 24 |
+
types.Part(text=question)
|
| 25 |
+
]
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
print(f"Respuesta: {response.text}")
|
| 30 |
+
return response.text
|
| 31 |
+
|
| 32 |
+
'''if __name__ == "__main__":
|
| 33 |
+
video_question_answer = VideoQuestionAnswer()
|
| 34 |
+
video_question_answer.answer("https://www.youtube.com/watch?v=L1vXCYZAYYM", "what is the highest number of bird species to be on camera simultaneously?")'''
|
| 35 |
+
|
| 36 |
+
'''class VideoQuestionAnswer:
|
| 37 |
+
def __init__(self):
|
| 38 |
+
self.client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
|
| 39 |
+
|
| 40 |
+
def answer(self, video_path: str, question: str) -> str:
|
| 41 |
+
print(f"Uploading video to Google GenAI: {video_path}")
|
| 42 |
+
print(f"Question: {question}")
|
| 43 |
+
myfile = self.client.files.upload(file=video_path)
|
| 44 |
+
|
| 45 |
+
# Check whether the file is ready to be used.
|
| 46 |
+
while myfile.state.name == "PROCESSING":
|
| 47 |
+
print("Waiting for file to be processed...")
|
| 48 |
+
time.sleep(10)
|
| 49 |
+
myfile = self.client.files.get(name=myfile.name)
|
| 50 |
+
|
| 51 |
+
if myfile.state.name == "FAILED":
|
| 52 |
+
print("File processing failed.")
|
| 53 |
+
raise ValueError(myfile.state.name)
|
| 54 |
+
|
| 55 |
+
response = self.client.models.generate_content(
|
| 56 |
+
model="gemini-2.0-flash", contents=[myfile, question]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
print(f"Video question answer: {response.text}")
|
| 60 |
+
return response.text'''
|
| 61 |
+
|
| 62 |
+
'''if __name__ == "__main__":
|
| 63 |
+
video_question_answer = VideoQuestionAnswer()
|
| 64 |
+
video_question_answer.answer("birds_video.mp4", "what is the highest number of bird species to be on camera simultaneously?")'''
|
youtube_video_downloader.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yt_dlp
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
class YoutubeVideoDownloader:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
self.output_basename = None
|
| 7 |
+
|
| 8 |
+
def download_video(self, url: str) -> str:
|
| 9 |
+
# Crear un timestamp único
|
| 10 |
+
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
| 11 |
+
self.output_basename = f"tmp/video_{timestamp}" # sin extensión todavía
|
| 12 |
+
|
| 13 |
+
print(f"Downloading video from YouTube: {url}")
|
| 14 |
+
ydl_opts = {
|
| 15 |
+
'outtmpl': self.output_basename + '.%(ext)s',
|
| 16 |
+
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]',
|
| 17 |
+
'merge_output_format': 'mp4',
|
| 18 |
+
'quiet': True
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 22 |
+
ydl.download([url])
|
| 23 |
+
|
| 24 |
+
# Forzamos que el archivo final debe ser mp4
|
| 25 |
+
final_output_path = self.output_basename + ".mp4"
|
| 26 |
+
print(f"Video downloaded to: {final_output_path}")
|
| 27 |
+
return final_output_path
|
| 28 |
+
|
| 29 |
+
'''if __name__ == "__main__":
|
| 30 |
+
downloader = YoutubeVideoDownloader()
|
| 31 |
+
video_path = downloader.download_video("https://www.youtube.com/watch?v=L1vXCYZAYYM")
|
| 32 |
+
print(f"Path: {video_path}")'''
|
youtube_video_question_answer_tool.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import BaseTool
|
| 2 |
+
from video_question_answer import VideoQuestionAnswer
|
| 3 |
+
from pydantic import BaseModel, Field
|
| 4 |
+
from typing import Type
|
| 5 |
+
import os
|
| 6 |
+
from youtube_video_downloader import YoutubeVideoDownloader
|
| 7 |
+
|
| 8 |
+
class YoutubeVideoQuestionAnswerToolArgs(BaseModel):
|
| 9 |
+
url: str = Field(description="The url of the youtube video")
|
| 10 |
+
question: str = Field(description="The question to answer")
|
| 11 |
+
|
| 12 |
+
class YoutubeVideoQuestionAnswerTool(BaseTool):
|
| 13 |
+
name: str = "youtube_video_question_answer"
|
| 14 |
+
description: str = "Answer the question based on the youtube video."
|
| 15 |
+
args_schema: Type[BaseModel] = YoutubeVideoQuestionAnswerToolArgs
|
| 16 |
+
|
| 17 |
+
def _run(self, url: str, question: str) -> str:
|
| 18 |
+
if url is None:
|
| 19 |
+
return "Error: Video not found."
|
| 20 |
+
# Answer the question
|
| 21 |
+
answer = VideoQuestionAnswer().answer(url, question)
|
| 22 |
+
return answer
|
| 23 |
+
|
| 24 |
+
'''def _run(self, url: str, question: str) -> str:
|
| 25 |
+
if url is None:
|
| 26 |
+
return "Error: Video not found."
|
| 27 |
+
# Download the video
|
| 28 |
+
video_path = YoutubeVideoDownloader().download_video(url)
|
| 29 |
+
# Answer the question
|
| 30 |
+
answer = VideoQuestionAnswer().answer(video_path, question)
|
| 31 |
+
# Delete the video
|
| 32 |
+
os.remove(video_path)
|
| 33 |
+
return answer'''
|