Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,18 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import json
|
| 3 |
import spaces
|
| 4 |
import torch
|
|
|
|
|
|
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import requests
|
| 7 |
import pandas as pd
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
from ddgs import DDGS
|
| 10 |
|
| 11 |
-
DEFAULT_API_URL = "https://
|
| 12 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 13 |
|
| 14 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
@@ -18,49 +22,121 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 18 |
device_map="auto",
|
| 19 |
)
|
| 20 |
|
| 21 |
-
def
|
|
|
|
|
|
|
| 22 |
try:
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
except Exception:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
SYSTEM_PROMPT = """You are a precise AI assistant answering GAIA benchmark questions.
|
| 29 |
-
CRITICAL OUTPUT RULES:
|
| 30 |
-
- Reply with ONLY the exact final answer and nothing else.
|
| 31 |
-
- Do NOT include 'FINAL ANSWER', explanations, units unless requested, or full sentences.
|
| 32 |
-
- If the answer is a number, output only the digits (e.g., 42).
|
| 33 |
-
- If the answer is a list, separate items with a comma and a single space (e.g., apple, banana).
|
| 34 |
-
"""
|
| 35 |
-
|
| 36 |
-
@spaces.GPU(duration=60)
|
| 37 |
-
def generate_answer(question: str, context: str = "") -> str:
|
| 38 |
-
user_prompt = question
|
| 39 |
-
if context:
|
| 40 |
-
user_prompt += f"\n\nWeb Search Context:\n{context}"
|
| 41 |
-
|
| 42 |
-
messages = [
|
| 43 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 44 |
-
{"role": "user", "content": user_prompt},
|
| 45 |
-
]
|
| 46 |
-
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 47 |
-
inputs = tokenizer([text], return_tensors="pt").to("cuda")
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
| 55 |
-
return response.strip()
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 66 |
space_id = os.getenv("SPACE_ID")
|
|
@@ -70,12 +146,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 70 |
username = f"{profile.username}"
|
| 71 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 72 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 73 |
-
agent_code = f"https://huggingface.co
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
agent = BasicAgent()
|
| 77 |
-
except Exception as e:
|
| 78 |
-
return f"Error initializing agent: {e}", None
|
| 79 |
|
| 80 |
questions_data = None
|
| 81 |
try:
|
|
@@ -90,24 +161,35 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 90 |
questions_data = json.load(f)
|
| 91 |
|
| 92 |
if not questions_data:
|
| 93 |
-
return "Error: Could not
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
for item in questions_data:
|
| 98 |
task_id = item.get("task_id")
|
| 99 |
question_text = item.get("question")
|
|
|
|
| 100 |
if not task_id or question_text is None:
|
| 101 |
continue
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 113 |
try:
|
|
@@ -122,14 +204,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 122 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 123 |
)
|
| 124 |
return final_status, pd.DataFrame(results_log)
|
| 125 |
-
except requests.exceptions.HTTPError as e:
|
| 126 |
-
detail = e.response.text[:500]
|
| 127 |
-
return f"Submission Failed ({e.response.status_code}): {detail}", pd.DataFrame(results_log)
|
| 128 |
except Exception as e:
|
| 129 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 130 |
|
| 131 |
with gr.Blocks() as demo:
|
| 132 |
-
gr.Markdown("#
|
| 133 |
gr.LoginButton()
|
| 134 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 135 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import json
|
| 4 |
import spaces
|
| 5 |
import torch
|
| 6 |
+
import tempfile
|
| 7 |
+
import subprocess
|
| 8 |
+
import wikipedia
|
| 9 |
import gradio as gr
|
| 10 |
import requests
|
| 11 |
import pandas as pd
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 13 |
from ddgs import DDGS
|
| 14 |
|
| 15 |
+
DEFAULT_API_URL = "https://hf.space"
|
| 16 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 17 |
|
| 18 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
|
|
| 22 |
device_map="auto",
|
| 23 |
)
|
| 24 |
|
| 25 |
+
def download_file(task_id: str, file_name: str) -> str | None:
|
| 26 |
+
if not file_name:
|
| 27 |
+
return None
|
| 28 |
try:
|
| 29 |
+
resp = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=30)
|
| 30 |
+
if resp.status_code == 200 and resp.content:
|
| 31 |
+
tmp_dir = tempfile.mkdtemp()
|
| 32 |
+
path = os.path.join(tmp_dir, file_name)
|
| 33 |
+
with open(path, "wb") as f:
|
| 34 |
+
f.write(resp.content)
|
| 35 |
+
return path
|
| 36 |
except Exception:
|
| 37 |
+
pass
|
| 38 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
def read_non_audio_file(file_path: str) -> str:
|
| 41 |
+
if not file_path or not os.path.exists(file_path):
|
| 42 |
+
return ""
|
| 43 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 44 |
+
if ext == ".py":
|
| 45 |
+
res = subprocess.run(["python3", file_path], capture_output=True, text=True, timeout=15)
|
| 46 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 47 |
+
code = f.read()
|
| 48 |
+
return f"Python Code:\n{code}\n\nExact Execution Output:\n{res.stdout.strip()}"
|
| 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 [".txt", ".csv", ".json"]:
|
| 53 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 54 |
+
return f.read()[:6000]
|
| 55 |
+
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 56 |
+
|
| 57 |
+
def search_web_and_wiki(query: str) -> str:
|
| 58 |
+
snippets = []
|
| 59 |
+
try:
|
| 60 |
+
ddg_results = DDGS().text(query, max_results=4, backend="lite")
|
| 61 |
+
for r in ddg_results or []:
|
| 62 |
+
snippets.append(f"[Web] {r['title']}: {r['body']}")
|
| 63 |
+
except Exception:
|
| 64 |
+
pass
|
| 65 |
+
try:
|
| 66 |
+
titles = wikipedia.search(query, results=2)
|
| 67 |
+
for title in titles:
|
| 68 |
+
summary = wikipedia.summary(title, sentences=5, auto_suggest=False)
|
| 69 |
+
snippets.append(f"[Wikipedia: {title}] {summary}")
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
return "\n".join(snippets)
|
| 73 |
|
| 74 |
+
SYSTEM_PROMPT = """You are an expert AI assistant solving GAIA benchmark questions.
|
| 75 |
+
Think step-by-step briefly, then output the exact final answer on the very last line prefixed with 'FINAL_ANSWER: '.
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
STRICT FORMATTING RULES FOR FINAL_ANSWER:
|
| 78 |
+
- Output ONLY the raw answer after 'FINAL_ANSWER: ' with no period at the end, no extra words, and no units unless asked.
|
| 79 |
+
- If a number is requested, write only digits (e.g., FINAL_ANSWER: 42).
|
| 80 |
+
- If USD with two decimal places is requested, write e.g. FINAL_ANSWER: 123.45 (no dollar sign unless standard).
|
| 81 |
+
- If a comma-separated list is requested, follow exact alphabetical/ascending order and spacing (e.g., FINAL_ANSWER: apple, banana).
|
| 82 |
+
"""
|
| 83 |
|
| 84 |
+
def extract_final_answer(raw_text: str) -> str:
|
| 85 |
+
match = re.search(r"FINAL_ANSWER:\s*(.+)", raw_text, re.IGNORECASE)
|
| 86 |
+
if match:
|
| 87 |
+
return match.group(1).strip().strip('"').strip("'")
|
| 88 |
+
lines = [line.strip() for line in raw_text.strip().splitlines() if line.strip()]
|
| 89 |
+
return lines[-1] if lines else raw_text.strip()
|
| 90 |
+
|
| 91 |
+
@spaces.GPU(duration=180)
|
| 92 |
+
def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
|
| 93 |
+
# 1. Transcribe any attached .mp3 files using Whisper on GPU
|
| 94 |
+
asr = None
|
| 95 |
+
for entry in items_with_files:
|
| 96 |
+
fp = entry.get("file_path")
|
| 97 |
+
if fp and fp.lower().endswith(".mp3"):
|
| 98 |
+
if asr is None:
|
| 99 |
+
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small", device="cuda")
|
| 100 |
+
transcript = asr(fp)["text"]
|
| 101 |
+
entry["context"] += f"\n\nAudio Transcript ({os.path.basename(fp)}):\n{transcript}"
|
| 102 |
+
|
| 103 |
+
# 2. Generate short search queries for text questions that don't have attached files
|
| 104 |
+
for entry in items_with_files:
|
| 105 |
+
if not entry.get("file_path"):
|
| 106 |
+
q_messages = [
|
| 107 |
+
{"role": "system", "content": "Extract a concise 4-7 word web search query to answer the user's question. Reply with ONLY the search query."},
|
| 108 |
+
{"role": "user", "content": entry["question"]},
|
| 109 |
+
]
|
| 110 |
+
q_text = tokenizer.apply_chat_template(q_messages, tokenize=False, add_generation_prompt=True)
|
| 111 |
+
q_in = tokenizer([q_text], return_tensors="pt").to("cuda")
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
q_out = model.generate(**q_in, max_new_tokens=24, do_sample=False)
|
| 114 |
+
clean_query = tokenizer.decode(q_out[q_in.input_ids.shape:], skip_special_tokens=True).strip().strip('"')
|
| 115 |
+
web_ctx = search_web_and_wiki(clean_query)
|
| 116 |
+
if web_ctx:
|
| 117 |
+
entry["context"] += f"\n\nSearch Results for '{clean_query}':\n{web_ctx}"
|
| 118 |
+
|
| 119 |
+
# 3. Solve each question with chain-of-thought and extract FINAL_ANSWER
|
| 120 |
+
answers = []
|
| 121 |
+
for entry in items_with_files:
|
| 122 |
+
user_prompt = entry["question"]
|
| 123 |
+
if entry["context"]:
|
| 124 |
+
user_prompt += f"\n\n--- Supporting Context ---\n{entry['context']}"
|
| 125 |
+
|
| 126 |
+
messages = [
|
| 127 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 128 |
+
{"role": "user", "content": user_prompt},
|
| 129 |
+
]
|
| 130 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 131 |
+
inputs = tokenizer([text], return_tensors="pt").to("cuda")
|
| 132 |
+
|
| 133 |
+
with torch.no_grad():
|
| 134 |
+
outputs = model.generate(**inputs, max_new_tokens=320, do_sample=False)
|
| 135 |
+
|
| 136 |
+
raw_response = tokenizer.decode(outputs[inputs.input_ids.shape:], skip_special_tokens=True)
|
| 137 |
+
answers.append(extract_final_answer(raw_response))
|
| 138 |
+
|
| 139 |
+
return answers
|
| 140 |
|
| 141 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 142 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 146 |
username = f"{profile.username}"
|
| 147 |
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 148 |
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 149 |
+
agent_code = f"https://huggingface.co{space_id}/tree/main"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
questions_data = None
|
| 152 |
try:
|
|
|
|
| 161 |
questions_data = json.load(f)
|
| 162 |
|
| 163 |
if not questions_data:
|
| 164 |
+
return "Error: Could not load questions.", None
|
| 165 |
|
| 166 |
+
# Download attached files on CPU first
|
| 167 |
+
prepared_items = []
|
| 168 |
for item in questions_data:
|
| 169 |
task_id = item.get("task_id")
|
| 170 |
question_text = item.get("question")
|
| 171 |
+
file_name = item.get("file_name", "")
|
| 172 |
if not task_id or question_text is None:
|
| 173 |
continue
|
| 174 |
+
fp = download_file(task_id, file_name)
|
| 175 |
+
file_ctx = read_non_audio_file(fp) if fp else ""
|
| 176 |
+
prepared_items.append({
|
| 177 |
+
"task_id": task_id,
|
| 178 |
+
"question": question_text,
|
| 179 |
+
"file_path": fp,
|
| 180 |
+
"context": file_ctx,
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
try:
|
| 184 |
+
final_answers = process_all_on_gpu(prepared_items)
|
| 185 |
+
except Exception as e:
|
| 186 |
+
return f"ZeroGPU execution failed: {e}", None
|
| 187 |
|
| 188 |
+
results_log = []
|
| 189 |
+
answers_payload = []
|
| 190 |
+
for entry, ans in zip(prepared_items, final_answers):
|
| 191 |
+
answers_payload.append({"task_id": entry["task_id"], "submitted_answer": ans})
|
| 192 |
+
results_log.append({"Task ID": entry["task_id"], "Question": entry["question"], "Submitted Answer": ans})
|
| 193 |
|
| 194 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 195 |
try:
|
|
|
|
| 204 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 205 |
)
|
| 206 |
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 207 |
except Exception as e:
|
| 208 |
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 209 |
|
| 210 |
with gr.Blocks() as demo:
|
| 211 |
+
gr.Markdown("# Multi-Modal ZeroGPU Agent Evaluation Runner")
|
| 212 |
gr.LoginButton()
|
| 213 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 214 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|