Upload folder using huggingface_hub
Browse files- .env-example +7 -0
- .gitignore +7 -0
- README.md +15 -0
- app.py +555 -0
- requirements.txt +19 -0
- results_log_with_correctness.csv +43 -0
- scorer.py +123 -0
.env-example
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
OPENAI_API_KEY=openai_api_key
|
| 2 |
+
OPENAI_MODEL=openai_model
|
| 3 |
+
ASSEMBLYAI_API_KEY=assemblyai_api_key
|
| 4 |
+
|
| 5 |
+
SPACE_ID=space_id
|
| 6 |
+
USERNAME=username
|
| 7 |
+
AGENT_CODE=agent_code
|
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
gaia_files/*
|
| 3 |
+
metadata.py
|
| 4 |
+
metadata.jsonl
|
| 5 |
+
metadata_level_1.json
|
| 6 |
+
results_log.csv
|
| 7 |
+
env/
|
README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Template Final Assignment
|
| 3 |
+
emoji: 🕵🏻♂️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.25.2
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
hf_oauth: true
|
| 11 |
+
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
| 12 |
+
hf_oauth_expiration_minutes: 480
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import requests
|
| 5 |
+
import inspect
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import asyncio
|
| 8 |
+
from typing import ClassVar
|
| 9 |
+
from llama_index.core.agent.workflow import FunctionAgent
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from llama_index.readers.youtube_transcript import YoutubeTranscriptReader
|
| 12 |
+
from llama_index.readers.assemblyai import AssemblyAIAudioTranscriptReader
|
| 13 |
+
from llama_index.core import SimpleDirectoryReader
|
| 14 |
+
from llama_index.readers.json import JSONReader
|
| 15 |
+
from llama_index.readers.pdb import PdbAbstractReader
|
| 16 |
+
from llama_index.readers.file import (
|
| 17 |
+
DocxReader,
|
| 18 |
+
HWPReader,
|
| 19 |
+
PDFReader,
|
| 20 |
+
EpubReader,
|
| 21 |
+
FlatReader,
|
| 22 |
+
HTMLTagReader,
|
| 23 |
+
ImageCaptionReader,
|
| 24 |
+
ImageReader,
|
| 25 |
+
ImageVisionLLMReader,
|
| 26 |
+
IPYNBReader,
|
| 27 |
+
MarkdownReader,
|
| 28 |
+
MboxReader,
|
| 29 |
+
PptxReader,
|
| 30 |
+
PandasCSVReader,
|
| 31 |
+
VideoAudioReader,
|
| 32 |
+
UnstructuredReader,
|
| 33 |
+
PyMuPDFReader,
|
| 34 |
+
ImageTabularChartReader,
|
| 35 |
+
XMLReader,
|
| 36 |
+
PagedCSVReader,
|
| 37 |
+
CSVReader,
|
| 38 |
+
RTFReader,
|
| 39 |
+
)
|
| 40 |
+
from llama_index.core.tools import FunctionTool
|
| 41 |
+
from llama_index.llms.openai import OpenAI
|
| 42 |
+
from tavily import AsyncTavilyClient
|
| 43 |
+
from dotenv import load_dotenv
|
| 44 |
+
|
| 45 |
+
load_dotenv()
|
| 46 |
+
|
| 47 |
+
# (Keep Constants as is)
|
| 48 |
+
# --- Constants ---
|
| 49 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 50 |
+
|
| 51 |
+
# --- TOOLS ---
|
| 52 |
+
|
| 53 |
+
METADATA_FILE_PATH = "metadata_level_1.json"
|
| 54 |
+
GAIA_FILES_DIR = "gaia_files"
|
| 55 |
+
|
| 56 |
+
def get_task_file_content(task_id: str) -> str:
|
| 57 |
+
"""
|
| 58 |
+
Reads the content of a file associated with a given task_id.
|
| 59 |
+
The file information is retrieved from metadata_level_1.json.
|
| 60 |
+
Supported file types are PDF, JSON, PDB, TXT, DOCX, CSV, PY, PPTX, and images.
|
| 61 |
+
Returns the file content as a string or an error/info message if the file cannot be processed.
|
| 62 |
+
"""
|
| 63 |
+
base_dir = Path(__file__).resolve().parent
|
| 64 |
+
gaia_files_full_dir = base_dir / GAIA_FILES_DIR
|
| 65 |
+
|
| 66 |
+
if not gaia_files_full_dir.exists() or not gaia_files_full_dir.is_dir():
|
| 67 |
+
return f"Error: GAIA files directory '{gaia_files_full_dir}' not found."
|
| 68 |
+
|
| 69 |
+
found_files = list(gaia_files_full_dir.glob(f"{task_id}.*"))
|
| 70 |
+
|
| 71 |
+
if not found_files:
|
| 72 |
+
return f"Info: No file found in '{gaia_files_full_dir}' starting with task_id '{task_id}'."
|
| 73 |
+
|
| 74 |
+
# If multiple files match the pattern (e.g., task_id.txt, task_id.pdf), pick the first one.
|
| 75 |
+
# You might want to add more sophisticated logic here if needed (e.g., based on preferred extension).
|
| 76 |
+
file_path = found_files[0]
|
| 77 |
+
file_name = file_path.name
|
| 78 |
+
|
| 79 |
+
if not file_path.is_file(): # Should not happen with glob if directory is not named like a file
|
| 80 |
+
return f"Error: Path '{file_path}' found for task_id '{task_id}' is not a file."
|
| 81 |
+
|
| 82 |
+
# Construct the file path relative to the app.py directory
|
| 83 |
+
gaia_files_full_dir = base_dir / GAIA_FILES_DIR
|
| 84 |
+
file_path = gaia_files_full_dir / file_name
|
| 85 |
+
|
| 86 |
+
if not file_path.exists():
|
| 87 |
+
return f"Error: File '{file_path}' (for task_id '{task_id}') not found."
|
| 88 |
+
|
| 89 |
+
_, extension = os.path.splitext(file_name.lower())
|
| 90 |
+
docs = []
|
| 91 |
+
content = ""
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
if extension == ".json":
|
| 95 |
+
loader = JSONReader()
|
| 96 |
+
docs = loader.load_data(input_file=file_path)
|
| 97 |
+
elif extension == ".pdb":
|
| 98 |
+
loader = PdbAbstractReader(input_files=[str(file_path)])
|
| 99 |
+
docs = loader.load_data()
|
| 100 |
+
elif extension in [".pdf", ".txt", ".docx", ".csv", ".py"]:
|
| 101 |
+
file_extractor = {
|
| 102 |
+
".pdf": PDFReader(),
|
| 103 |
+
".txt": FlatReader(),
|
| 104 |
+
".docx": DocxReader(),
|
| 105 |
+
".csv": CSVReader(),
|
| 106 |
+
".py": FlatReader(),
|
| 107 |
+
# ".pptx": PptxReader()
|
| 108 |
+
}
|
| 109 |
+
loader = SimpleDirectoryReader(input_files=[str(file_path)], file_extractor=file_extractor)
|
| 110 |
+
docs = loader.load_data()
|
| 111 |
+
elif extension in [".png", ".jpg", ".jpeg"]: # Common image types handled by SimpleDirectoryReader
|
| 112 |
+
parser = ImageReader()
|
| 113 |
+
file_extractor = {
|
| 114 |
+
".jpg": parser,
|
| 115 |
+
".jpeg": parser,
|
| 116 |
+
".png": parser,
|
| 117 |
+
}
|
| 118 |
+
loader = SimpleDirectoryReader(input_files=[str(file_path)], file_extractor=file_extractor)
|
| 119 |
+
docs = loader.load_data()
|
| 120 |
+
elif extension in [".mp3", ".wav"]:
|
| 121 |
+
loader = AssemblyAIAudioTranscriptReader(file_path=str(file_path), api_key=os.getenv("ASSEMBLYAI_API_KEY"))
|
| 122 |
+
docs = loader.load_data()
|
| 123 |
+
else:
|
| 124 |
+
return f"Unsupported file type: {extension} for file {file_name}."
|
| 125 |
+
|
| 126 |
+
if docs:
|
| 127 |
+
content = ""
|
| 128 |
+
for doc in docs:
|
| 129 |
+
# se tiver get_text(), usa — caso contrário, pega doc.text
|
| 130 |
+
if hasattr(doc, "get_text"):
|
| 131 |
+
content = "\n".join([content, doc.get_text()])
|
| 132 |
+
else:
|
| 133 |
+
# .text é o campo padrão de qualquer Document em LlamaIndex
|
| 134 |
+
content = "\n".join([content, doc.text or ""])
|
| 135 |
+
print(content)
|
| 136 |
+
return content
|
| 137 |
+
return f"Info: No content extracted from file {file_name}. The file might be empty or the loader did not process it."
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
return f"Error reading file {file_name} for task_id '{task_id}': {str(e)}"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def get_youtube_transcript(url: str) -> str:
|
| 144 |
+
"""
|
| 145 |
+
Given a YouTube URL, fetches its transcript.
|
| 146 |
+
Returns:
|
| 147 |
+
transcript: A string of the transcript text.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
try:
|
| 151 |
+
loader = YoutubeTranscriptReader()
|
| 152 |
+
documents = loader.load_data(
|
| 153 |
+
ytlinks=[url]
|
| 154 |
+
)
|
| 155 |
+
transcript = "\n".join([doc.text for doc in documents])
|
| 156 |
+
return transcript
|
| 157 |
+
except Exception as e:
|
| 158 |
+
return f"Error fetching transcript for URL {url}: {str(e)}"
|
| 159 |
+
|
| 160 |
+
async def search_web(query: str) -> str:
|
| 161 |
+
"""
|
| 162 |
+
Useful for using the web to answer questions.
|
| 163 |
+
Use wisely and do not use more than 3 times per question.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
query: The query to search for.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
search_results: A string of the search results.
|
| 170 |
+
"""
|
| 171 |
+
client = AsyncTavilyClient(api_key=os.environ.get("TAVILY_API_KEY"))
|
| 172 |
+
return str(await client.search(query))
|
| 173 |
+
|
| 174 |
+
# --- Utils ---
|
| 175 |
+
def add_final_answer(row):
|
| 176 |
+
task_id_to_final_answer = {}
|
| 177 |
+
with open(METADATA_FILE_PATH, "r") as f:
|
| 178 |
+
for line in f:
|
| 179 |
+
metadata = json.loads(line)
|
| 180 |
+
task_id_to_final_answer[metadata['task_id']] = metadata['Final answer']
|
| 181 |
+
|
| 182 |
+
row['final_answer'] = task_id_to_final_answer.get(row['Task ID'], "")
|
| 183 |
+
return row
|
| 184 |
+
|
| 185 |
+
# --- Basic Agent Definition ---
|
| 186 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 187 |
+
class BasicAgent(FunctionAgent):
|
| 188 |
+
search_web_count: ClassVar[int] = 0
|
| 189 |
+
max_search_web_calls: ClassVar[int] = 3
|
| 190 |
+
def __init__(self):
|
| 191 |
+
BasicAgent.search_web_count = 0
|
| 192 |
+
BasicAgent.max_search_web_calls = 3
|
| 193 |
+
|
| 194 |
+
get_task_data_tool = FunctionTool.from_defaults(
|
| 195 |
+
fn=get_task_file_content,
|
| 196 |
+
name="get_task_file_content",
|
| 197 |
+
description=(
|
| 198 |
+
"Reads and returns the content of a file associated with a given task_id. "
|
| 199 |
+
"Use this tool if the question implies needing information from a specific file related to the task. "
|
| 200 |
+
"You must provide the 'task_id' to this tool. The task_id will be part of the input question."
|
| 201 |
+
)
|
| 202 |
+
)
|
| 203 |
+
get_youtube_transcript_tool = FunctionTool.from_defaults(
|
| 204 |
+
fn=get_youtube_transcript,
|
| 205 |
+
name="get_youtube_transcript",
|
| 206 |
+
description=(
|
| 207 |
+
"Reads and returns the transcript of a YouTube video associated with a given URL. "
|
| 208 |
+
"Use this tool if the question implies needing information from a specific YouTube video related to the task. "
|
| 209 |
+
"You must provide the 'url' to this tool. The url will be part of the input question."
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
search_web_tool = FunctionTool.from_defaults(
|
| 213 |
+
fn=self._search_web_wrapper,
|
| 214 |
+
name="search_web",
|
| 215 |
+
description=(
|
| 216 |
+
"Useful for using the web to answer questions. "
|
| 217 |
+
"Use wisely and do not use more than 3 times per question."
|
| 218 |
+
)
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
super().__init__(
|
| 222 |
+
tools=[get_task_data_tool, get_youtube_transcript_tool, search_web_tool],
|
| 223 |
+
llm=OpenAI(model=os.getenv("OPENAI_MODEL")),
|
| 224 |
+
system_prompt="""
|
| 225 |
+
You are a general AI assistant. I will ask you a question.
|
| 226 |
+
The question will be prefixed with 'Task ID: <id>. Question: '.
|
| 227 |
+
If the question requires information from a file associated with this Task ID,
|
| 228 |
+
extract the <id> and use the 'get_task_file_content' tool, providing the extracted Task ID to it.
|
| 229 |
+
If you can't retrieve the file content or it doesn't exists, try your best to answer the question.
|
| 230 |
+
|
| 231 |
+
Your answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 232 |
+
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign
|
| 233 |
+
unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations
|
| 234 |
+
(e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma
|
| 235 |
+
separated list, apply the above rules depending of whether the element to be put in the list is a number or a
|
| 236 |
+
string.
|
| 237 |
+
""",
|
| 238 |
+
verbose=True
|
| 239 |
+
)
|
| 240 |
+
print("BasicAgent initialized.")
|
| 241 |
+
|
| 242 |
+
async def _search_web_wrapper(self, query: str) -> str:
|
| 243 |
+
"""
|
| 244 |
+
Wrapper for the search_web tool to limit its usage per question.
|
| 245 |
+
"""
|
| 246 |
+
if BasicAgent.search_web_count >= BasicAgent.max_search_web_calls:
|
| 247 |
+
return "Search limit reached. You have already used the web search tool 3 times for this question."
|
| 248 |
+
BasicAgent.search_web_count += 1
|
| 249 |
+
# Call the original/global search_web function
|
| 250 |
+
return await search_web(query)
|
| 251 |
+
|
| 252 |
+
def reset_search_web_count(self):
|
| 253 |
+
"""Resets the search_web call counter."""
|
| 254 |
+
BasicAgent.search_web_count = 0
|
| 255 |
+
|
| 256 |
+
async def __call__(self, question: str) -> str:
|
| 257 |
+
print(f"Agent received question {question}...")
|
| 258 |
+
answer = await self.run(question)
|
| 259 |
+
print(f"Agent returned answer: {answer}")
|
| 260 |
+
return answer
|
| 261 |
+
|
| 262 |
+
def run_random_one(profile: gr.OAuthProfile | None):
|
| 263 |
+
"""
|
| 264 |
+
Fetches a random question, runs the BasicAgent on it, submits the answer,
|
| 265 |
+
and displays the result.
|
| 266 |
+
"""
|
| 267 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 268 |
+
api_url = os.getenv("API_URL") or DEFAULT_API_URL
|
| 269 |
+
|
| 270 |
+
if profile:
|
| 271 |
+
username= f"{profile.username}"
|
| 272 |
+
print(f"User logged in: {username}")
|
| 273 |
+
else:
|
| 274 |
+
print("User not logged in.")
|
| 275 |
+
return "Please Login to Hugging Face with the button.", None
|
| 276 |
+
|
| 277 |
+
# --- Fetch Random Question ---
|
| 278 |
+
random_question_url = f"{api_url}/random-question"
|
| 279 |
+
response = requests.get(random_question_url)
|
| 280 |
+
if response.status_code != 200:
|
| 281 |
+
return "Failed to fetch a random question.", None
|
| 282 |
+
response_data = response.json()
|
| 283 |
+
question = response_data["question"]
|
| 284 |
+
task_id = response_data["task_id"]
|
| 285 |
+
print("----------------")
|
| 286 |
+
print(response_data)
|
| 287 |
+
print("----------------")
|
| 288 |
+
print(task_id)
|
| 289 |
+
print(question)
|
| 290 |
+
print("----------------")
|
| 291 |
+
|
| 292 |
+
basic_agent = BasicAgent()
|
| 293 |
+
# Augment the question with task_id context for the agent's tool
|
| 294 |
+
question_for_agent = f"Task ID: {task_id}. Question: {question}"
|
| 295 |
+
print(f"Augmented question for agent: {question_for_agent}") # For debugging
|
| 296 |
+
answer = asyncio.run(basic_agent(question_for_agent))
|
| 297 |
+
answer = answer.response.blocks[0].text
|
| 298 |
+
print("----------------")
|
| 299 |
+
print(answer)
|
| 300 |
+
print("----------------")
|
| 301 |
+
|
| 302 |
+
# --- Submit Answer ---
|
| 303 |
+
# submit_url = f"{api_url}/submit"
|
| 304 |
+
# submission_data = {
|
| 305 |
+
# "username": os.getenv("USERNAME"),
|
| 306 |
+
# "agent_code": os.getenv("AGENT_CODE"),
|
| 307 |
+
# "answers": [
|
| 308 |
+
# {"task_id": task_id, "question": question, "answer": answer}
|
| 309 |
+
# ]
|
| 310 |
+
# }
|
| 311 |
+
# response = requests.post(submit_url, json=submission_data)
|
| 312 |
+
# if response.status_code != 200:
|
| 313 |
+
# return "Failed to submit the answer.", None
|
| 314 |
+
# result = response.json()
|
| 315 |
+
|
| 316 |
+
# --- Display Result ---
|
| 317 |
+
# print("-------------------------------")
|
| 318 |
+
# print(result)
|
| 319 |
+
# print("-------------------------------")
|
| 320 |
+
return "Success", pd.DataFrame([{"task_id": task_id, "question": question, "answer": answer}])
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _fetch_questions(questions_url: str):
|
| 324 |
+
"""Fetches questions from the specified URL."""
|
| 325 |
+
print(f"Fetching questions from: {questions_url}")
|
| 326 |
+
try:
|
| 327 |
+
response = requests.get(questions_url, timeout=15)
|
| 328 |
+
response.raise_for_status()
|
| 329 |
+
questions_data = response.json()
|
| 330 |
+
if not questions_data:
|
| 331 |
+
print("Fetched questions list is empty.")
|
| 332 |
+
return None, "Fetched questions list is empty or invalid format."
|
| 333 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 334 |
+
return questions_data, None
|
| 335 |
+
except requests.exceptions.RequestException as e:
|
| 336 |
+
print(f"Error fetching questions: {e}")
|
| 337 |
+
return None, f"Error fetching questions: {e}"
|
| 338 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 339 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 340 |
+
# It's good practice to check if response exists before accessing .text
|
| 341 |
+
response_text = response.text[:500] if hasattr(response, 'text') else "No response text available"
|
| 342 |
+
print(f"Response text: {response_text}")
|
| 343 |
+
return None, f"Error decoding server response for questions: {e}"
|
| 344 |
+
except Exception as e:
|
| 345 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 346 |
+
return None, f"An unexpected error occurred fetching questions: {e}"
|
| 347 |
+
|
| 348 |
+
def _run_agent_on_questions(basic_agent: BasicAgent, questions_data: list):
|
| 349 |
+
"""Runs the agent on the provided questions and logs results."""
|
| 350 |
+
results_log = []
|
| 351 |
+
answers_payload = []
|
| 352 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 353 |
+
for item in questions_data:
|
| 354 |
+
basic_agent.reset_search_web_count() # Reset counter for each new question
|
| 355 |
+
task_id = item.get("task_id")
|
| 356 |
+
question = item.get("question")
|
| 357 |
+
if not task_id or question is None:
|
| 358 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 359 |
+
continue
|
| 360 |
+
try:
|
| 361 |
+
question_for_agent = f"Task ID: {task_id}. Question: {question}"
|
| 362 |
+
# Ensure basic_agent is an async function or handle appropriately
|
| 363 |
+
# For this refactor, assuming basic_agent call is correct as is.
|
| 364 |
+
submitted_answer_obj = asyncio.run(basic_agent(question_for_agent))
|
| 365 |
+
submitted_answer = submitted_answer_obj.response.blocks[0].text
|
| 366 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 367 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": submitted_answer})
|
| 368 |
+
except Exception as e:
|
| 369 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 370 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 371 |
+
|
| 372 |
+
if not answers_payload:
|
| 373 |
+
print("Agent did not produce any answers to submit.")
|
| 374 |
+
return None, results_log, "Agent did not produce any answers to submit."
|
| 375 |
+
|
| 376 |
+
return answers_payload, results_log, None
|
| 377 |
+
|
| 378 |
+
def _prepare_submission_payload(username: str, agent_code: str, answers_payload: list):
|
| 379 |
+
"""Prepares the submission payload."""
|
| 380 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 381 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 382 |
+
print(status_update)
|
| 383 |
+
return submission_data
|
| 384 |
+
|
| 385 |
+
def _submit_and_process_results(submit_url: str, submission_data: dict, results_log: list):
|
| 386 |
+
"""Submits answers and processes the results from the server."""
|
| 387 |
+
print(f"Submitting {len(submission_data.get('answers', []))} answers to: {submit_url}")
|
| 388 |
+
try:
|
| 389 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 390 |
+
response.raise_for_status()
|
| 391 |
+
result_data = response.json()
|
| 392 |
+
final_status = (
|
| 393 |
+
f"Submission Successful!\n"
|
| 394 |
+
f"User: {result_data.get('username')}\n"
|
| 395 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 396 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 397 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 398 |
+
)
|
| 399 |
+
print("Submission successful.")
|
| 400 |
+
return final_status, results_log
|
| 401 |
+
except requests.exceptions.HTTPError as e:
|
| 402 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 403 |
+
try:
|
| 404 |
+
error_json = e.response.json()
|
| 405 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 406 |
+
except requests.exceptions.JSONDecodeError:
|
| 407 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 408 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 409 |
+
print(status_message)
|
| 410 |
+
return status_message, results_log
|
| 411 |
+
except requests.exceptions.Timeout:
|
| 412 |
+
status_message = "Submission Failed: The request timed out."
|
| 413 |
+
print(status_message)
|
| 414 |
+
return status_message, results_log
|
| 415 |
+
except requests.exceptions.RequestException as e:
|
| 416 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 417 |
+
print(status_message)
|
| 418 |
+
return status_message, results_log
|
| 419 |
+
except Exception as e:
|
| 420 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 421 |
+
print(status_message)
|
| 422 |
+
return status_message, results_log
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 426 |
+
"""
|
| 427 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 428 |
+
and displays the results.
|
| 429 |
+
"""
|
| 430 |
+
space_id = os.getenv("SPACE_ID")
|
| 431 |
+
|
| 432 |
+
if profile:
|
| 433 |
+
username = f"{profile.username}"
|
| 434 |
+
print(f"User logged in: {username}")
|
| 435 |
+
else:
|
| 436 |
+
print("User not logged in.")
|
| 437 |
+
return "Please Login to Hugging Face with the button.", None
|
| 438 |
+
|
| 439 |
+
api_url = DEFAULT_API_URL
|
| 440 |
+
questions_url = f"{api_url}/questions"
|
| 441 |
+
submit_url = f"{api_url}/submit"
|
| 442 |
+
|
| 443 |
+
# 1. Instantiate Agent
|
| 444 |
+
try:
|
| 445 |
+
basic_agent = BasicAgent()
|
| 446 |
+
except Exception as e:
|
| 447 |
+
print(f"Error instantiating agent: {e}")
|
| 448 |
+
return f"Error initializing agent: {e}", None
|
| 449 |
+
|
| 450 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 451 |
+
print(f"Agent code URL: {agent_code}")
|
| 452 |
+
|
| 453 |
+
# 2. Fetch Questions
|
| 454 |
+
questions_data, error_message = _fetch_questions(questions_url)
|
| 455 |
+
if error_message:
|
| 456 |
+
return error_message, None # No DataFrame to return here
|
| 457 |
+
|
| 458 |
+
# 3. Run your Agent
|
| 459 |
+
answers_payload, results_log, error_message = _run_agent_on_questions(basic_agent, questions_data)
|
| 460 |
+
if error_message:
|
| 461 |
+
# If agent produced no answers, results_log might still be useful
|
| 462 |
+
return error_message, pd.DataFrame(results_log if results_log else [])
|
| 463 |
+
|
| 464 |
+
# 4. Save logs
|
| 465 |
+
results_log = pd.DataFrame(results_log)
|
| 466 |
+
results_log = results_log.apply(add_final_answer, axis=1)
|
| 467 |
+
results_log.to_csv("results_log.csv", index=False)
|
| 468 |
+
|
| 469 |
+
# 5. Prepare Submission
|
| 470 |
+
submission_data = _prepare_submission_payload(username, agent_code, answers_payload)
|
| 471 |
+
|
| 472 |
+
# 6. Submit and Process Results
|
| 473 |
+
final_status, results_df = _submit_and_process_results(submit_url, submission_data, results_log)
|
| 474 |
+
return final_status, results_df
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# --- Build Gradio Interface using Blocks ---
|
| 478 |
+
with gr.Blocks() as demo:
|
| 479 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 480 |
+
gr.Markdown(
|
| 481 |
+
"""
|
| 482 |
+
**Instructions:**
|
| 483 |
+
|
| 484 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 485 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 486 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 487 |
+
|
| 488 |
+
---
|
| 489 |
+
**Disclaimers:**
|
| 490 |
+
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).
|
| 491 |
+
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.
|
| 492 |
+
"""
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
gr.LoginButton()
|
| 496 |
+
|
| 497 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 498 |
+
|
| 499 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 500 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 501 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
run_button.click(
|
| 505 |
+
fn=run_and_submit_all,
|
| 506 |
+
outputs=[status_output, results_table]
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
random_button = gr.Button("Run Random Question")
|
| 510 |
+
random_button.click(
|
| 511 |
+
fn=run_random_one,
|
| 512 |
+
outputs=[status_output, results_table]
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
# task_id = gr.Textbox(label="Task ID")
|
| 516 |
+
# task_content_output = gr.Textbox(label="Task Content", lines=5, interactive=True)
|
| 517 |
+
# get_task_content_button = gr.Button("Get Task Content")
|
| 518 |
+
# get_task_content_button.click(
|
| 519 |
+
# fn=get_task_file_content,
|
| 520 |
+
# inputs=[task_id],
|
| 521 |
+
# outputs=[task_content_output]
|
| 522 |
+
# )
|
| 523 |
+
|
| 524 |
+
# youtube_url = gr.Textbox(label="Youtube URL")
|
| 525 |
+
# youtube_transcript_output = gr.Textbox(label="Youtube Transcript", lines=5, interactive=True)
|
| 526 |
+
# get_youtube_transcript_button = gr.Button("Get Youtube Transcript")
|
| 527 |
+
# get_youtube_transcript_button.click(
|
| 528 |
+
# fn=get_youtube_transcript,
|
| 529 |
+
# inputs=[youtube_url],
|
| 530 |
+
# outputs=[youtube_transcript_output]
|
| 531 |
+
# )
|
| 532 |
+
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 535 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 536 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 537 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 538 |
+
|
| 539 |
+
if space_host_startup:
|
| 540 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 541 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 542 |
+
else:
|
| 543 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 544 |
+
|
| 545 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 546 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 547 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 548 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 549 |
+
else:
|
| 550 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 551 |
+
|
| 552 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 553 |
+
|
| 554 |
+
print("Launching Gradio Interface for Agent Evaluation...")
|
| 555 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio[oauth]
|
| 2 |
+
requests
|
| 3 |
+
llama-index==0.12.33
|
| 4 |
+
llama-index-llms-openai==0.3.44
|
| 5 |
+
llama-index-readers-file
|
| 6 |
+
llama-index-readers-json
|
| 7 |
+
llama-index-readers-pdb
|
| 8 |
+
llama-hub-youtube-transcript
|
| 9 |
+
llama-index-readers-youtube-transcript
|
| 10 |
+
llama-index-readers-assemblyai
|
| 11 |
+
docx2txt
|
| 12 |
+
python-dotenv
|
| 13 |
+
pandas
|
| 14 |
+
torch
|
| 15 |
+
transformers
|
| 16 |
+
python-pptx
|
| 17 |
+
Pillow
|
| 18 |
+
youtube_transcript_api
|
| 19 |
+
tavily-python
|
results_log_with_correctness.csv
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Task ID,Question,Submitted Answer,final_answer,correct
|
| 2 |
+
8e867cd7-cff9-4e6c-867a-ff5ddc2550be,How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.,3,3,correct
|
| 3 |
+
a1e91b78-d3d8-4675-bb8d-62741b4b68a6,"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",14,3,wrong
|
| 4 |
+
2d83110e-a098-4ebb-9987-066c06fa42d0,".rewsna eht sa ""tfel"" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",right,Right,correct
|
| 5 |
+
cca530fc-4052-43b2-b130-b30968d8aa44,Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.,Qh3,Rd5,wrong
|
| 6 |
+
4fc2f1ae-8625-45b5-ab34-ad4433bc21f8,Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?,Icewhiz,FunkMonk,wrong
|
| 7 |
+
6f37996b-2ac7-44b0-8e68-6d28256631b4,"Given this table defining * on the set S = {a, b, c, d, e}
|
| 8 |
+
|
| 9 |
+
|*|a|b|c|d|e|
|
| 10 |
+
|---|---|---|---|---|---|
|
| 11 |
+
|a|a|b|c|b|d|
|
| 12 |
+
|b|b|c|a|e|c|
|
| 13 |
+
|c|c|a|b|b|a|
|
| 14 |
+
|d|b|e|b|e|d|
|
| 15 |
+
|e|d|b|a|d|c|
|
| 16 |
+
|
| 17 |
+
provide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.","b,c,e","b, e",wrong
|
| 18 |
+
9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
|
| 19 |
+
|
| 20 |
+
What does Teal'c say in response to the question ""Isn't that hot?""",Indeed,Extremely,wrong
|
| 21 |
+
cabe07ed-9eca-40ea-8ead-410ef5e83f91,What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?,Anderson,Louvrier,wrong
|
| 22 |
+
3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
|
| 23 |
+
|
| 24 |
+
milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
|
| 25 |
+
|
| 26 |
+
I need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.","broccoli, celery, lettuce, sweet potatoes","broccoli, celery, fresh basil, lettuce, sweet potatoes",wrong
|
| 27 |
+
99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3,"Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.
|
| 28 |
+
|
| 29 |
+
In your response, please only list the ingredients, not any measurements. So if the recipe calls for ""a pinch of salt"" or ""two cups of ripe strawberries"" the ingredients on the list would be ""salt"" and ""ripe strawberries"".
|
| 30 |
+
|
| 31 |
+
Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.","cornstarch, freshly squeezed lemon juice, granulated sugar, pure vanilla extract, ripe strawberries","cornstarch, freshly squeezed lemon juice, granulated sugar, pure vanilla extract, ripe strawberries",correct
|
| 32 |
+
305ac316-eef6-4446-960a-92d80d542f82,Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.,Pawel,Wojciech,wrong
|
| 33 |
+
f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,0,0,correct
|
| 34 |
+
3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,516,519,wrong
|
| 35 |
+
1f975693-876d-457b-a649-393859e79bf3,"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(
|
| 36 |
+
|
| 37 |
+
Could you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.","132,133,134,197,245","132, 133, 134, 197, 245",correct
|
| 38 |
+
840bfca7-4f7b-481a-8794-c560c340185d,"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",80NSSC18K0526,80GSFC21M0002,wrong
|
| 39 |
+
bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,Saint Petersburg,Saint Petersburg,correct
|
| 40 |
+
cf106601-ab4f-4af9-b045-5295fe67b37d,"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",MON,CUB,wrong
|
| 41 |
+
a0c07678-e491-4bbc-8f0b-07405144218f,"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.","Takeyama, Wakita","Yoshida, Uehara",wrong
|
| 42 |
+
7bd855d8-463d-4ed5-93ca-5fe35145f733,The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.,Unable to access file.,89706.00,wrong
|
| 43 |
+
5a0c1adf-205e-4841-a666-7c3ef95def9d,What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?,Eri,Claus,wrong
|
scorer.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import string
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def normalize_number_str(number_str: str) -> float:
|
| 11 |
+
# we replace these common units and commas to allow
|
| 12 |
+
# conversion to float
|
| 13 |
+
for char in ["$", "%", ","]:
|
| 14 |
+
number_str = number_str.replace(char, "")
|
| 15 |
+
try:
|
| 16 |
+
return float(number_str)
|
| 17 |
+
except ValueError:
|
| 18 |
+
print(f"String {number_str} cannot be normalized to number str.")
|
| 19 |
+
return float("inf")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def split_string(
|
| 23 |
+
s: str,
|
| 24 |
+
char_list: list[str] = [",", ";"],
|
| 25 |
+
) -> list[str]:
|
| 26 |
+
pattern = f"[{''.join(char_list)}]"
|
| 27 |
+
return re.split(pattern, s)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def question_scorer(
|
| 31 |
+
model_answer: str,
|
| 32 |
+
ground_truth: str,
|
| 33 |
+
) -> bool:
|
| 34 |
+
def is_float(element: any) -> bool:
|
| 35 |
+
try:
|
| 36 |
+
float(element)
|
| 37 |
+
return True
|
| 38 |
+
except ValueError:
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
if model_answer is None:
|
| 42 |
+
model_answer = "None"
|
| 43 |
+
|
| 44 |
+
# if gt is a number
|
| 45 |
+
if is_float(ground_truth):
|
| 46 |
+
print(f"Evaluating {model_answer} as a number.")
|
| 47 |
+
normalized_answer = normalize_number_str(model_answer)
|
| 48 |
+
return normalized_answer == float(ground_truth)
|
| 49 |
+
|
| 50 |
+
# if gt is a list
|
| 51 |
+
elif any(char in ground_truth for char in [",", ";"]):
|
| 52 |
+
print(f"Evaluating {model_answer} as a comma separated list.")
|
| 53 |
+
# question with the fish: normalization removes punct
|
| 54 |
+
|
| 55 |
+
gt_elems = split_string(ground_truth)
|
| 56 |
+
ma_elems = split_string(model_answer)
|
| 57 |
+
|
| 58 |
+
# check length is the same
|
| 59 |
+
if len(gt_elems) != len(ma_elems):
|
| 60 |
+
warnings.warn(
|
| 61 |
+
"Answer lists have different lengths, returning False.", UserWarning
|
| 62 |
+
)
|
| 63 |
+
return False
|
| 64 |
+
|
| 65 |
+
# compare each element as float or str
|
| 66 |
+
comparisons = []
|
| 67 |
+
for ma_elem, gt_elem in zip(ma_elems, gt_elems):
|
| 68 |
+
if is_float(gt_elem):
|
| 69 |
+
normalized_ma_elem = normalize_number_str(ma_elem)
|
| 70 |
+
comparisons.append(normalized_ma_elem == float(gt_elem))
|
| 71 |
+
else:
|
| 72 |
+
# we do not remove punct since comparisons can include punct
|
| 73 |
+
comparisons.append(
|
| 74 |
+
normalize_str(ma_elem, remove_punct=False)
|
| 75 |
+
== normalize_str(gt_elem, remove_punct=False)
|
| 76 |
+
)
|
| 77 |
+
return all(comparisons)
|
| 78 |
+
|
| 79 |
+
# if gt is a str
|
| 80 |
+
else:
|
| 81 |
+
print(f"Evaluating {model_answer} as a string.")
|
| 82 |
+
return normalize_str(model_answer) == normalize_str(ground_truth)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def normalize_str(input_str, remove_punct=True) -> str:
|
| 86 |
+
"""
|
| 87 |
+
Normalize a string by:
|
| 88 |
+
- Removing all white spaces
|
| 89 |
+
- Optionally removing punctuation (if remove_punct is True)
|
| 90 |
+
- Converting to lowercase
|
| 91 |
+
Parameters:
|
| 92 |
+
- input_str: str, the string to normalize
|
| 93 |
+
- remove_punct: bool, whether to remove punctuation (default: True)
|
| 94 |
+
Returns:
|
| 95 |
+
- str, the normalized string
|
| 96 |
+
"""
|
| 97 |
+
# Remove all white spaces. Required e.g for seagull vs. sea gull
|
| 98 |
+
no_spaces = re.sub(r"\s", "", input_str)
|
| 99 |
+
|
| 100 |
+
# Remove punctuation, if specified.
|
| 101 |
+
if remove_punct:
|
| 102 |
+
translator = str.maketrans("", "", string.punctuation)
|
| 103 |
+
return no_spaces.lower().translate(translator)
|
| 104 |
+
else:
|
| 105 |
+
return no_spaces.lower()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def add_correctness_column(input_filename: str, output_filename: str):
|
| 109 |
+
"""
|
| 110 |
+
Reads in a results_log.csv file, adds a column to say if the submitted answer is correct or not
|
| 111 |
+
and writes the result to a new csv file.
|
| 112 |
+
Parameters:
|
| 113 |
+
- input_filename: str, the name of the input csv file
|
| 114 |
+
- output_filename: str, the name of the output csv file
|
| 115 |
+
"""
|
| 116 |
+
df = pd.read_csv(input_filename)
|
| 117 |
+
df["correct"] = df.apply(
|
| 118 |
+
lambda x: "correct" if question_scorer(x["Submitted Answer"], x["final_answer"]) else "wrong",
|
| 119 |
+
axis=1,
|
| 120 |
+
)
|
| 121 |
+
df.to_csv(output_filename, index=False)
|
| 122 |
+
|
| 123 |
+
add_correctness_column("results_log.csv", "results_log_with_correctness.csv")
|