Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,199 +1,547 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
import traceback
|
| 5 |
import tempfile
|
| 6 |
import subprocess
|
|
|
|
| 7 |
import wikipedia
|
| 8 |
import gradio as gr
|
| 9 |
import requests
|
| 10 |
import pandas as pd
|
|
|
|
| 11 |
from ddgs import DDGS
|
| 12 |
from groq import Groq
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
GROQ_MODEL = "openai/gpt-oss-120b"
|
| 16 |
AUDIO_MODEL = "whisper-large-v3"
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def get_groq_client():
|
| 19 |
api_key = os.getenv("GROQ_API_KEY")
|
|
|
|
| 20 |
if not api_key:
|
| 21 |
-
raise RuntimeError(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
return Groq(api_key=api_key)
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def download_file(task_id: str, file_name: str) -> str | None:
|
|
|
|
| 25 |
if not file_name:
|
| 26 |
return None
|
|
|
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
tmp_dir = tempfile.mkdtemp()
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return None
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def read_attached_file(file_path: str) -> str:
|
|
|
|
| 40 |
if not file_path or not os.path.exists(file_path):
|
| 41 |
return ""
|
|
|
|
| 42 |
ext = os.path.splitext(file_path)[1].lower()
|
|
|
|
| 43 |
try:
|
|
|
|
|
|
|
| 44 |
if ext == ".py":
|
| 45 |
-
|
| 46 |
-
with open(file_path, "r", encoding="utf-8") as
|
| 47 |
-
code =
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
elif ext in [".xlsx", ".xls"]:
|
|
|
|
| 50 |
df = pd.read_excel(file_path)
|
| 51 |
-
return f"Excel Table Contents:\n{df.to_string(index=False)}"
|
| 52 |
-
elif ext in [".mp3", ".wav", ".m4a", ".ogg", ".webm", ".flac"]:
|
| 53 |
-
client = get_groq_client()
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
elif ext in [".txt", ".csv", ".json"]:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
def build_clean_query(question: str) -> str:
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
return " ".join(words[:10])
|
| 74 |
|
|
|
|
| 75 |
def search_web_and_wiki(question: str) -> str:
|
|
|
|
| 76 |
query = build_clean_query(question)
|
|
|
|
| 77 |
if not query:
|
| 78 |
return ""
|
|
|
|
| 79 |
snippets = []
|
|
|
|
|
|
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
try:
|
|
|
|
| 87 |
titles = wikipedia.search(query, results=2)
|
|
|
|
| 88 |
for title in titles:
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
return "\n".join(snippets)
|
| 94 |
|
| 95 |
-
SYSTEM_PROMPT = """You are a precise AI assistant solving GAIA benchmark questions.
|
| 96 |
-
CRITICAL OUTPUT RULES:
|
| 97 |
-
- Reply with ONLY the exact final answer and nothing else.
|
| 98 |
-
- Do NOT write 'FINAL ANSWER', explanations, full sentences, or trailing periods.
|
| 99 |
-
- If a number is requested, output only the digits (e.g., 42).
|
| 100 |
-
- If USD with two decimal places is requested, output e.g. 123.45.
|
| 101 |
-
- If a comma-separated list is requested, follow exact alphabetical or ascending order and spacing (e.g., apple, banana).
|
| 102 |
-
"""
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
answers = []
|
| 109 |
-
for user_prompt in prompts:
|
| 110 |
-
messages = [
|
| 111 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 112 |
-
{"role": "user", "content": user_prompt},
|
| 113 |
-
]
|
| 114 |
-
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 115 |
-
inputs = tokenizer([text], return_tensors="pt").to("cuda")
|
| 116 |
|
| 117 |
-
|
| 118 |
-
outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
return answers
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
| 127 |
try:
|
| 128 |
-
|
|
|
|
| 129 |
if not profile:
|
| 130 |
-
return
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
username =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 134 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
questions_data = None
|
|
|
|
| 138 |
try:
|
| 139 |
-
response = requests.get(questions_url, timeout=15)
|
| 140 |
-
if response.status_code == 200 and response.text.strip():
|
| 141 |
-
questions_data = response.json()
|
| 142 |
-
except Exception:
|
| 143 |
-
pass
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
if not questions_data and os.path.exists("questions.json"):
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
if not questions_data:
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
valid_items = []
|
| 153 |
prompts = []
|
| 154 |
-
|
|
|
|
|
|
|
| 155 |
task_id = item.get("task_id")
|
| 156 |
question_text = item.get("question")
|
| 157 |
file_name = item.get("file_name", "")
|
|
|
|
| 158 |
if not task_id or question_text is None:
|
| 159 |
continue
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
valid_items.append(item)
|
| 164 |
prompts.append(user_prompt)
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
final_answers = generate_answers(prompts)
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
results_log = []
|
| 169 |
answers_payload = []
|
| 170 |
-
for item, ans in zip(valid_items, final_answers):
|
| 171 |
-
answers_payload.append({"task_id": item["task_id"], "submitted_answer": ans})
|
| 172 |
-
results_log.append({"Task ID": item["task_id"], "Question": item["question"], "Submitted Answer": ans})
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
response.raise_for_status()
|
|
|
|
| 177 |
result_data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
final_status = (
|
| 179 |
-
|
| 180 |
-
f"User: {result_data.get('username')}\n"
|
| 181 |
-
f"Overall Score: {result_data.get('score', 'N/A')}%
|
| 182 |
-
f"
|
|
|
|
| 183 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 184 |
)
|
|
|
|
| 185 |
return final_status, pd.DataFrame(results_log)
|
| 186 |
|
| 187 |
except Exception:
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
with gr.Blocks() as demo:
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
gr.LoginButton()
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
if __name__ == "__main__":
|
|
|
|
| 199 |
demo.launch()
|
|
|
|
| 1 |
+
|
| 2 |
import os
|
| 3 |
import re
|
| 4 |
import json
|
| 5 |
import traceback
|
| 6 |
import tempfile
|
| 7 |
import subprocess
|
| 8 |
+
|
| 9 |
import wikipedia
|
| 10 |
import gradio as gr
|
| 11 |
import requests
|
| 12 |
import pandas as pd
|
| 13 |
+
|
| 14 |
from ddgs import DDGS
|
| 15 |
from groq import Groq
|
| 16 |
|
| 17 |
+
|
| 18 |
+
# =========================================================
|
| 19 |
+
# CONFIGURATION
|
| 20 |
+
# =========================================================
|
| 21 |
+
|
| 22 |
+
# Hugging Face Agents Course evaluation API
|
| 23 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 24 |
+
|
| 25 |
GROQ_MODEL = "openai/gpt-oss-120b"
|
| 26 |
AUDIO_MODEL = "whisper-large-v3"
|
| 27 |
|
| 28 |
+
SYSTEM_PROMPT = """
|
| 29 |
+
You are a precise AI assistant solving GAIA benchmark questions.
|
| 30 |
+
|
| 31 |
+
CRITICAL OUTPUT RULES:
|
| 32 |
+
- Reply with ONLY the exact final answer and nothing else.
|
| 33 |
+
- Do NOT write 'FINAL ANSWER', explanations, full sentences, or trailing periods.
|
| 34 |
+
- If a number is requested, output only the digits (e.g., 42).
|
| 35 |
+
- If USD with two decimal places is requested, output e.g. 123.45.
|
| 36 |
+
- If a comma-separated list is requested, follow exact alphabetical or ascending order and spacing (e.g., apple, banana).
|
| 37 |
+
- Carefully inspect the question and supporting context before answering.
|
| 38 |
+
- Never invent facts. If the answer cannot be determined, make your best evidence-based attempt.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# =========================================================
|
| 43 |
+
# GROQ CLIENT
|
| 44 |
+
# =========================================================
|
| 45 |
+
|
| 46 |
def get_groq_client():
|
| 47 |
api_key = os.getenv("GROQ_API_KEY")
|
| 48 |
+
|
| 49 |
if not api_key:
|
| 50 |
+
raise RuntimeError(
|
| 51 |
+
"GROQ_API_KEY is missing. "
|
| 52 |
+
"Add it in Hugging Face Space Settings > Variables and secrets."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
return Groq(api_key=api_key)
|
| 56 |
|
| 57 |
+
|
| 58 |
+
# =========================================================
|
| 59 |
+
# FILE DOWNLOAD
|
| 60 |
+
# =========================================================
|
| 61 |
+
|
| 62 |
def download_file(task_id: str, file_name: str) -> str | None:
|
| 63 |
+
|
| 64 |
if not file_name:
|
| 65 |
return None
|
| 66 |
+
|
| 67 |
try:
|
| 68 |
+
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 69 |
+
|
| 70 |
+
response = requests.get(url, timeout=30)
|
| 71 |
+
response.raise_for_status()
|
| 72 |
+
|
| 73 |
+
if response.content:
|
| 74 |
tmp_dir = tempfile.mkdtemp()
|
| 75 |
+
safe_name = os.path.basename(file_name)
|
| 76 |
+
file_path = os.path.join(tmp_dir, safe_name)
|
| 77 |
+
|
| 78 |
+
with open(file_path, "wb") as file:
|
| 79 |
+
file.write(response.content)
|
| 80 |
+
|
| 81 |
+
return file_path
|
| 82 |
+
|
| 83 |
+
except Exception as error:
|
| 84 |
+
print(f"File download failed for {task_id}: {error}")
|
| 85 |
+
|
| 86 |
return None
|
| 87 |
|
| 88 |
+
|
| 89 |
+
# =========================================================
|
| 90 |
+
# ATTACHED FILE READER
|
| 91 |
+
# =========================================================
|
| 92 |
+
|
| 93 |
def read_attached_file(file_path: str) -> str:
|
| 94 |
+
|
| 95 |
if not file_path or not os.path.exists(file_path):
|
| 96 |
return ""
|
| 97 |
+
|
| 98 |
ext = os.path.splitext(file_path)[1].lower()
|
| 99 |
+
|
| 100 |
try:
|
| 101 |
+
|
| 102 |
+
# Python files
|
| 103 |
if ext == ".py":
|
| 104 |
+
|
| 105 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
| 106 |
+
code = file.read()
|
| 107 |
+
|
| 108 |
+
result = subprocess.run(
|
| 109 |
+
["python3", file_path],
|
| 110 |
+
capture_output=True,
|
| 111 |
+
text=True,
|
| 112 |
+
timeout=15
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
return (
|
| 116 |
+
f"Python Code:\n{code}\n\n"
|
| 117 |
+
f"Execution Output:\n{result.stdout.strip()}\n\n"
|
| 118 |
+
f"Execution Errors:\n{result.stderr.strip()}"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Excel files
|
| 122 |
elif ext in [".xlsx", ".xls"]:
|
| 123 |
+
|
| 124 |
df = pd.read_excel(file_path)
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
return (
|
| 127 |
+
"Excel Table Contents:\n"
|
| 128 |
+
+ df.to_string(index=False)
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Audio files
|
| 132 |
+
elif ext in [
|
| 133 |
+
".mp3",
|
| 134 |
+
".wav",
|
| 135 |
+
".m4a",
|
| 136 |
+
".ogg",
|
| 137 |
+
".webm",
|
| 138 |
+
".flac"
|
| 139 |
+
]:
|
| 140 |
+
|
| 141 |
+
client = get_groq_client()
|
| 142 |
+
|
| 143 |
+
with open(file_path, "rb") as audio_file:
|
| 144 |
|
| 145 |
+
transcript = client.audio.transcriptions.create(
|
| 146 |
+
file=(
|
| 147 |
+
os.path.basename(file_path),
|
| 148 |
+
audio_file.read()
|
| 149 |
+
),
|
| 150 |
+
model=AUDIO_MODEL,
|
| 151 |
+
response_format="text"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return (
|
| 155 |
+
f"Audio Transcript "
|
| 156 |
+
f"({os.path.basename(file_path)}):\n"
|
| 157 |
+
f"{transcript}"
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Text, CSV and JSON files
|
| 161 |
elif ext in [".txt", ".csv", ".json"]:
|
| 162 |
+
|
| 163 |
+
with open(
|
| 164 |
+
file_path,
|
| 165 |
+
"r",
|
| 166 |
+
encoding="utf-8",
|
| 167 |
+
errors="ignore"
|
| 168 |
+
) as file:
|
| 169 |
+
|
| 170 |
+
return file.read()[:6000]
|
| 171 |
+
|
| 172 |
+
except Exception as error:
|
| 173 |
+
|
| 174 |
+
return (
|
| 175 |
+
f"File read error "
|
| 176 |
+
f"({os.path.basename(file_path)}): {error}"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 180 |
|
| 181 |
+
|
| 182 |
+
# =========================================================
|
| 183 |
+
# WEB SEARCH
|
| 184 |
+
# =========================================================
|
| 185 |
+
|
| 186 |
def build_clean_query(question: str) -> str:
|
| 187 |
+
|
| 188 |
+
query = re.sub(r"https?://\S+", "", question)
|
| 189 |
+
|
| 190 |
+
words = [
|
| 191 |
+
word
|
| 192 |
+
for word in re.findall(r"[A-Za-z0-9'-]+", query)
|
| 193 |
+
if len(word) > 2
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
return " ".join(words[:10])
|
| 197 |
|
| 198 |
+
|
| 199 |
def search_web_and_wiki(question: str) -> str:
|
| 200 |
+
|
| 201 |
query = build_clean_query(question)
|
| 202 |
+
|
| 203 |
if not query:
|
| 204 |
return ""
|
| 205 |
+
|
| 206 |
snippets = []
|
| 207 |
+
|
| 208 |
+
# DuckDuckGo search
|
| 209 |
try:
|
| 210 |
+
|
| 211 |
+
ddg_results = DDGS().text(
|
| 212 |
+
query,
|
| 213 |
+
max_results=4,
|
| 214 |
+
backend="lite"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
for result in ddg_results or []:
|
| 218 |
+
|
| 219 |
+
snippets.append(
|
| 220 |
+
f"[Web] {result.get('title', '')}: "
|
| 221 |
+
f"{result.get('body', '')}"
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
except Exception as error:
|
| 225 |
+
print(f"Web search error: {error}")
|
| 226 |
+
|
| 227 |
+
# Wikipedia search
|
| 228 |
try:
|
| 229 |
+
|
| 230 |
titles = wikipedia.search(query, results=2)
|
| 231 |
+
|
| 232 |
for title in titles:
|
| 233 |
+
|
| 234 |
+
summary = wikipedia.summary(
|
| 235 |
+
title,
|
| 236 |
+
sentences=4,
|
| 237 |
+
auto_suggest=False
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
snippets.append(
|
| 241 |
+
f"[Wikipedia: {title}] {summary}"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
except Exception as error:
|
| 245 |
+
print(f"Wikipedia search error: {error}")
|
| 246 |
+
|
| 247 |
return "\n".join(snippets)
|
| 248 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
# =========================================================
|
| 251 |
+
# GROQ ANSWER GENERATION
|
| 252 |
+
# =========================================================
|
| 253 |
+
|
| 254 |
+
def generate_answers(prompts: list[str]) -> list[str]:
|
| 255 |
+
|
| 256 |
+
client = get_groq_client()
|
| 257 |
+
|
| 258 |
answers = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
for index, user_prompt in enumerate(prompts, start=1):
|
|
|
|
| 261 |
|
| 262 |
+
print(f"Generating answer {index}/{len(prompts)}")
|
| 263 |
+
|
| 264 |
+
completion = client.chat.completions.create(
|
| 265 |
+
model=GROQ_MODEL,
|
| 266 |
+
messages=[
|
| 267 |
+
{
|
| 268 |
+
"role": "system",
|
| 269 |
+
"content": SYSTEM_PROMPT
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"role": "user",
|
| 273 |
+
"content": user_prompt
|
| 274 |
+
}
|
| 275 |
+
],
|
| 276 |
+
max_completion_tokens=256
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
answer = (
|
| 280 |
+
completion.choices[0].message.content or ""
|
| 281 |
+
).strip()
|
| 282 |
+
|
| 283 |
+
answer = answer.strip('"').strip("'").strip()
|
| 284 |
+
|
| 285 |
+
answers.append(answer)
|
| 286 |
|
| 287 |
return answers
|
| 288 |
|
| 289 |
+
|
| 290 |
+
# =========================================================
|
| 291 |
+
# MAIN EVALUATION AND SUBMISSION
|
| 292 |
+
# =========================================================
|
| 293 |
+
|
| 294 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 295 |
+
|
| 296 |
try:
|
| 297 |
+
|
| 298 |
+
# Check Hugging Face login
|
| 299 |
if not profile:
|
| 300 |
+
return (
|
| 301 |
+
"Please log in to Hugging Face using the Login button.",
|
| 302 |
+
None
|
| 303 |
+
)
|
| 304 |
|
| 305 |
+
username = profile.username
|
| 306 |
+
|
| 307 |
+
# Get Space ID
|
| 308 |
+
space_id = os.getenv("SPACE_ID")
|
| 309 |
+
|
| 310 |
+
if not space_id:
|
| 311 |
+
return (
|
| 312 |
+
"Error: SPACE_ID environment variable is missing.",
|
| 313 |
+
None
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
space_id = space_id.strip("/")
|
| 317 |
+
|
| 318 |
+
# Evaluation API endpoints
|
| 319 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 320 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 321 |
+
|
| 322 |
+
agent_code = (
|
| 323 |
+
f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# -------------------------------------------------
|
| 327 |
+
# FETCH QUESTIONS
|
| 328 |
+
# -------------------------------------------------
|
| 329 |
|
| 330 |
questions_data = None
|
| 331 |
+
|
| 332 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
|
| 334 |
+
response = requests.get(
|
| 335 |
+
questions_url,
|
| 336 |
+
timeout=30
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
response.raise_for_status()
|
| 340 |
+
|
| 341 |
+
questions_data = response.json()
|
| 342 |
+
|
| 343 |
+
except Exception as error:
|
| 344 |
+
|
| 345 |
+
print(f"Question API error: {error}")
|
| 346 |
+
|
| 347 |
+
# Local fallback
|
| 348 |
if not questions_data and os.path.exists("questions.json"):
|
| 349 |
+
|
| 350 |
+
with open(
|
| 351 |
+
"questions.json",
|
| 352 |
+
"r",
|
| 353 |
+
encoding="utf-8"
|
| 354 |
+
) as file:
|
| 355 |
+
|
| 356 |
+
questions_data = json.load(file)
|
| 357 |
|
| 358 |
if not questions_data:
|
| 359 |
+
|
| 360 |
+
return (
|
| 361 |
+
"Error: Could not load evaluation questions.",
|
| 362 |
+
None
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# -------------------------------------------------
|
| 366 |
+
# PROCESS QUESTIONS
|
| 367 |
+
# -------------------------------------------------
|
| 368 |
|
| 369 |
valid_items = []
|
| 370 |
prompts = []
|
| 371 |
+
|
| 372 |
+
for index, item in enumerate(questions_data, start=1):
|
| 373 |
+
|
| 374 |
task_id = item.get("task_id")
|
| 375 |
question_text = item.get("question")
|
| 376 |
file_name = item.get("file_name", "")
|
| 377 |
+
|
| 378 |
if not task_id or question_text is None:
|
| 379 |
continue
|
| 380 |
+
|
| 381 |
+
print(
|
| 382 |
+
f"Processing question {index}/"
|
| 383 |
+
f"{len(questions_data)}"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
# Download attached file
|
| 387 |
+
file_path = download_file(
|
| 388 |
+
task_id,
|
| 389 |
+
file_name
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
# Read attachment or search for context
|
| 393 |
+
if file_path:
|
| 394 |
+
|
| 395 |
+
context = read_attached_file(file_path)
|
| 396 |
+
|
| 397 |
+
else:
|
| 398 |
+
|
| 399 |
+
context = search_web_and_wiki(
|
| 400 |
+
question_text
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Build prompt
|
| 404 |
+
user_prompt = question_text
|
| 405 |
+
|
| 406 |
+
if context:
|
| 407 |
+
|
| 408 |
+
user_prompt += (
|
| 409 |
+
"\n\n--- Supporting Context ---\n"
|
| 410 |
+
+ context
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
valid_items.append(item)
|
| 414 |
prompts.append(user_prompt)
|
| 415 |
|
| 416 |
+
if not prompts:
|
| 417 |
+
|
| 418 |
+
return (
|
| 419 |
+
"Error: No valid questions were found.",
|
| 420 |
+
None
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# -------------------------------------------------
|
| 424 |
+
# GENERATE ANSWERS USING GROQ
|
| 425 |
+
# -------------------------------------------------
|
| 426 |
+
|
| 427 |
final_answers = generate_answers(prompts)
|
| 428 |
|
| 429 |
+
# -------------------------------------------------
|
| 430 |
+
# PREPARE SUBMISSION
|
| 431 |
+
# -------------------------------------------------
|
| 432 |
+
|
| 433 |
results_log = []
|
| 434 |
answers_payload = []
|
|
|
|
|
|
|
|
|
|
| 435 |
|
| 436 |
+
for item, answer in zip(valid_items, final_answers):
|
| 437 |
+
|
| 438 |
+
answers_payload.append(
|
| 439 |
+
{
|
| 440 |
+
"task_id": item["task_id"],
|
| 441 |
+
"submitted_answer": answer
|
| 442 |
+
}
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
results_log.append(
|
| 446 |
+
{
|
| 447 |
+
"Task ID": item["task_id"],
|
| 448 |
+
"Question": item["question"],
|
| 449 |
+
"Submitted Answer": answer
|
| 450 |
+
}
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
submission_data = {
|
| 454 |
+
"username": username.strip(),
|
| 455 |
+
"agent_code": agent_code,
|
| 456 |
+
"answers": answers_payload
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
# -------------------------------------------------
|
| 460 |
+
# SUBMIT ANSWERS
|
| 461 |
+
# -------------------------------------------------
|
| 462 |
+
|
| 463 |
+
response = requests.post(
|
| 464 |
+
submit_url,
|
| 465 |
+
json=submission_data,
|
| 466 |
+
timeout=60
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
response.raise_for_status()
|
| 470 |
+
|
| 471 |
result_data = response.json()
|
| 472 |
+
|
| 473 |
+
# -------------------------------------------------
|
| 474 |
+
# DISPLAY RESULT
|
| 475 |
+
# -------------------------------------------------
|
| 476 |
+
|
| 477 |
final_status = (
|
| 478 |
+
"Submission Successful!\n"
|
| 479 |
+
f"User: {result_data.get('username', username)}\n"
|
| 480 |
+
f"Overall Score: {result_data.get('score', 'N/A')}%\n"
|
| 481 |
+
f"Correct: {result_data.get('correct_count', '?')}/"
|
| 482 |
+
f"{result_data.get('total_attempted', '?')}\n"
|
| 483 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 484 |
)
|
| 485 |
+
|
| 486 |
return final_status, pd.DataFrame(results_log)
|
| 487 |
|
| 488 |
except Exception:
|
| 489 |
+
|
| 490 |
+
error_details = traceback.format_exc()
|
| 491 |
+
|
| 492 |
+
print(error_details)
|
| 493 |
+
|
| 494 |
+
return (
|
| 495 |
+
f"Detailed Error:\n{error_details}",
|
| 496 |
+
None
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# =========================================================
|
| 501 |
+
# GRADIO INTERFACE
|
| 502 |
+
# =========================================================
|
| 503 |
|
| 504 |
with gr.Blocks() as demo:
|
| 505 |
+
|
| 506 |
+
gr.Markdown(
|
| 507 |
+
"# Multi-Modal GAIA Agent Evaluation Runner"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
gr.Markdown(
|
| 511 |
+
"Log in with Hugging Face and run the evaluation."
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
gr.LoginButton()
|
| 515 |
+
|
| 516 |
+
run_button = gr.Button(
|
| 517 |
+
"Run Evaluation & Submit All Answers",
|
| 518 |
+
variant="primary"
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
status_output = gr.Textbox(
|
| 522 |
+
label="Run Status / Submission Result",
|
| 523 |
+
lines=8,
|
| 524 |
+
interactive=False
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
results_table = gr.DataFrame(
|
| 528 |
+
label="Questions and Agent Answers",
|
| 529 |
+
wrap=True
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
run_button.click(
|
| 533 |
+
fn=run_and_submit_all,
|
| 534 |
+
outputs=[
|
| 535 |
+
status_output,
|
| 536 |
+
results_table
|
| 537 |
+
]
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
# =========================================================
|
| 542 |
+
# APPLICATION START
|
| 543 |
+
# =========================================================
|
| 544 |
|
| 545 |
if __name__ == "__main__":
|
| 546 |
+
|
| 547 |
demo.launch()
|