OhBrian commited on
Commit
23060b1
·
1 Parent(s): 81917a3

初版多模态工具解析

Browse files
Files changed (3) hide show
  1. README.md +58 -3
  2. app.py +759 -95
  3. requirements.txt +5 -1
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Template Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
@@ -8,8 +8,63 @@ 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: GAIA 问答 Agent 评测
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
 
8
  app_file: app.py
9
  pinned: false
10
  hf_oauth: true
11
+ # 可选配置。默认有效期为 8 小时/480 分钟,最长为 30 天/43200 分钟。
12
  hf_oauth_expiration_minutes: 480
13
  ---
14
 
15
+ 这是 Hugging Face Agents Course Final Assignment 的基础 Space,用于运行并提交 GAIA 风格问题的 Agent 作答结果。
16
+
17
+ 当前版本仍是基础骨架:
18
+
19
+ - `app.py` 会通过课程评测接口拉取问题。
20
+ - `BasicAgent` 目前只返回固定答案,需要替换为真实的问题回答 Agent。
21
+ - 登录 Hugging Face 后,界面会使用当前 HF 用户名提交答案。
22
+ - 提交时会携带当前 Space 的代码仓库链接,便于评测系统记录实现来源。
23
+
24
+ Space 配置参考:https://huggingface.co/docs/hub/spaces-config-reference
25
+
26
+ ## 本地 GAIA 测试设计
27
+
28
+ 本地测试不要直接等同于官方评分。课程评分接口的 `/questions` 可以返回问题列表,但不会返回标准答案;带附件的问题还需要额外处理文件。因此,本地测试应该拆成两层:
29
+
30
+ 1. 流程测试:验证 Agent 能稳定读取问题、处理附件路径、调用工具、生成答案、记录日志,并输出符合提交接口要求的 JSON。
31
+ 2. 正确率测试:使用你自己维护的本地 gold 数据,或公开/可访问的 GAIA 数据子集,对 Agent 的答案做离线比对。
32
+
33
+ 建议的本地目录结构:
34
+
35
+ ```text
36
+ .
37
+ ├── app.py
38
+ ├── agent.py
39
+ ├── gaia_local_eval.py
40
+ ├── data/
41
+ │ ├── questions.json
42
+ │ ├── gold_local.jsonl
43
+ │ └── attachments/
44
+ │ └── <task_id>/
45
+ │ └── <file_name>
46
+ └── runs/
47
+ └── <timestamp>.jsonl
48
+ ```
49
+
50
+ 建议的执行流程:
51
+
52
+ 1. 缓存题目:从 `https://agents-course-unit4-scoring.hf.space/questions` 拉取当前题目,保存为 `data/questions.json`,避免频繁请求接口导致限流或不稳定。
53
+ 2. 准备附件:如果题目有 `file_name`,优先尝试用裸 `task_id` 请求 `/files/{task_id}`;如果接口不可用,就把附件手动放到 `data/attachments/<task_id>/` 下。
54
+ 3. 抽离 Agent:把真实作答逻辑放入 `agent.py`,提供统一入口,例如 `answer(question: str, file_path: str | None = None) -> str`。
55
+ 4. 编写本地 runner:`gaia_local_eval.py` 只负责读取 `questions.json`、定位附件、调用 Agent、保存每题的答案、耗时、错误、工具轨迹和置信度。
56
+ 5. 编写答案规整器:对数字、货币、日期、大小写、逗号分隔列表、空格和标点做标准化,避免因为格式差异误判。
57
+ 6. 维护 gold 文件:`gold_local.jsonl` 每行包含 `task_id`、`expected_answer`、`match_type` 和备注。没有标准答案的问题只做流程测试,不纳入正确率统计。
58
+ 7. 分层运行:先跑 1 到 3 道 smoke test,再跑全部本地题;确认稳定后再通过 Space 按官方流程提交。
59
+
60
+ 真实 Agent 至少应该具备这些工具能力:
61
+
62
+ - 网页检索和网页阅读,用于维基、论文、新闻、体育数据等开放网络问题。
63
+ - Python 执行沙箱,用于数学、表格、代码题和可复现计算。
64
+ - 文件解析能力,包括图片、音频、Excel、CSV、Python 文件和普通文本。
65
+ - 音频转写能力,用于 `.mp3` 附件。
66
+ - 视频处理能力,用于 YouTube 问题,可结合字幕、抽帧和视觉模型。
67
+ - 棋类分析能力,用于棋盘图像和最优走法题。
68
+ - 答案格式控制能力,严格输出题目要求的最终答案,不输出推理过程。
69
+
70
+ 本地 runner 的目标不是替代官方评分,而是在提交前暴露三类问题:Agent 崩溃、工具链缺失、答案格式错误。最终分数仍以官方 `/submit` 返回结果为准。
app.py CHANGED
@@ -1,196 +1,860 @@
 
 
 
1
  import os
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
- import requests
4
- import inspect
5
  import pandas as pd
 
 
6
 
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
  """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
  else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
 
37
  api_url = DEFAULT_API_URL
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # 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)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
 
 
 
 
49
  print(agent_code)
50
 
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
53
  try:
54
  response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
79
  if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
 
 
 
97
  print(status_update)
98
 
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
  result_data = response.json()
105
  final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
- print("Submission successful.")
113
  results_df = pd.DataFrame(results_log)
114
  return final_status, results_df
115
  except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
  try:
118
  error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
  except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
  print(status_message)
124
  results_df = pd.DataFrame(results_log)
125
  return status_message, results_df
126
  except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
  print(status_message)
129
  results_df = pd.DataFrame(results_log)
130
  return status_message, results_df
131
  except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
  print(status_message)
134
  results_df = pd.DataFrame(results_log)
135
  return status_message, results_df
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
  print(status_message)
139
  results_df = pd.DataFrame(results_log)
140
  return status_message, results_df
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
- **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
153
 
154
  ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
170
  fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
  )
173
 
 
174
  if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
1
+ import base64
2
+ import html
3
+ import mimetypes
4
  import os
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Any
12
+ from urllib.parse import parse_qs, unquote, urlparse
13
+
14
  import gradio as gr
 
 
15
  import pandas as pd
16
+ import requests
17
+ from bs4 import BeautifulSoup
18
 
19
+
20
+ # --- 常量 ---
21
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
+ HF_ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
23
+ HF_TEXT_MODEL = os.getenv("HF_TEXT_MODEL", "openai/gpt-oss-20b:cheapest")
24
+ HF_AUDIO_MODEL = os.getenv("HF_AUDIO_MODEL", "openai/whisper-large-v3-turbo")
25
+ HF_VISION_MODEL = os.getenv("HF_VISION_MODEL", "")
26
+ MAX_EVIDENCE_CHARS = int(os.getenv("MAX_EVIDENCE_CHARS", "18000"))
27
+ CACHE_DIR = Path(tempfile.gettempdir()) / "gaia_agent_files"
28
+ REQUEST_HEADERS = {
29
+ "User-Agent": (
30
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
31
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
32
+ "Chrome/125.0.0.0 Safari/537.36"
33
+ )
34
+ }
35
+
36
+
37
+ def get_hf_token() -> str | None:
38
+ """读取 Hugging Face Token。Space Secrets 中建议使用 HF_TOKEN。"""
39
+ return (
40
+ os.getenv("HF_TOKEN")
41
+ or os.getenv("HUGGING_FACE_HUB_TOKEN")
42
+ or os.getenv("HUGGINGFACEHUB_API_TOKEN")
43
+ )
44
+
45
+
46
+ def truncate_text(text: str, limit: int = MAX_EVIDENCE_CHARS) -> str:
47
+ if len(text) <= limit:
48
+ return text
49
+ return text[:limit] + "\n\n[内容过长,已截断。]"
50
+
51
+
52
+ def normalize_answer(answer: str) -> str:
53
+ """清理模型常见废话,只保留适合提交的最终答案字符串。"""
54
+ answer = answer.strip()
55
+ answer = re.sub(r"^```(?:text|markdown)?", "", answer, flags=re.IGNORECASE).strip()
56
+ answer = re.sub(r"```$", "", answer).strip()
57
+
58
+ final_markers = [
59
+ "final answer:",
60
+ "final:",
61
+ "answer:",
62
+ "submitted_answer:",
63
+ "最终答案:",
64
+ "答案:",
65
+ ]
66
+ lower_answer = answer.lower()
67
+ for marker in final_markers:
68
+ marker_index = lower_answer.rfind(marker)
69
+ if marker_index != -1:
70
+ answer = answer[marker_index + len(marker):].strip()
71
+ break
72
+
73
+ if "\n" in answer:
74
+ non_empty_lines = [line.strip() for line in answer.splitlines() if line.strip()]
75
+ if non_empty_lines:
76
+ answer = non_empty_lines[-1]
77
+
78
+ return answer.strip().strip('"').strip("'")
79
+
80
+
81
+ def extract_urls(text: str) -> list[str]:
82
+ urls = re.findall(r"https?://[^\s<>\"]+", text)
83
+ return [url.rstrip(".,);]\"'") for url in urls]
84
+
85
+
86
+ def is_youtube_url(url: str) -> bool:
87
+ host = urlparse(url).netloc.lower()
88
+ return "youtube.com" in host or "youtu.be" in host
89
+
90
+
91
+ def clean_html_text(raw_html: str) -> str:
92
+ soup = BeautifulSoup(raw_html, "html.parser")
93
+ for tag in soup(["script", "style", "noscript", "svg", "nav", "footer"]):
94
+ tag.decompose()
95
+
96
+ title = soup.title.string.strip() if soup.title and soup.title.string else ""
97
+ text = soup.get_text("\n")
98
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
99
+ compact_text = "\n".join(lines)
100
+ if title:
101
+ return f"标题:{title}\n正文:\n{compact_text}"
102
+ return compact_text
103
+
104
+
105
+ def fetch_url_text(url: str, limit: int = 8000) -> str:
106
+ """抓取网页正文。失败时返回错误信息,避免 Agent 直接崩溃。"""
107
+ try:
108
+ response = requests.get(url, headers=REQUEST_HEADERS, timeout=25)
109
+ response.raise_for_status()
110
+ content_type = response.headers.get("content-type", "")
111
+ if "text/html" in content_type or "<html" in response.text[:500].lower():
112
+ return truncate_text(clean_html_text(response.text), limit)
113
+ return truncate_text(response.text, limit)
114
+ except Exception as exc:
115
+ return f"无法读取网页 {url}:{exc}"
116
+
117
+
118
+ def decode_duckduckgo_href(href: str) -> str:
119
+ parsed = urlparse(href)
120
+ query = parse_qs(parsed.query)
121
+ if "uddg" in query:
122
+ return unquote(query["uddg"][0])
123
+ return href
124
+
125
+
126
+ def search_web(query: str, max_results: int = 5) -> list[dict[str, str]]:
127
+ """无 API Key 的轻量搜索。稳定性不如正式搜索 API,但适合省额度。"""
128
+ try:
129
+ response = requests.get(
130
+ "https://duckduckgo.com/html/",
131
+ params={"q": query},
132
+ headers=REQUEST_HEADERS,
133
+ timeout=25,
134
+ )
135
+ response.raise_for_status()
136
+ soup = BeautifulSoup(response.text, "html.parser")
137
+ results = []
138
+ for anchor in soup.select("a.result__a"):
139
+ title = anchor.get_text(" ", strip=True)
140
+ href = decode_duckduckgo_href(anchor.get("href", ""))
141
+ if title and href.startswith("http"):
142
+ results.append({"title": title, "url": href})
143
+ if len(results) >= max_results:
144
+ break
145
+ return results
146
+ except Exception as exc:
147
+ print(f"搜索失败���{exc}")
148
+ return []
149
+
150
+
151
+ def collect_web_evidence(question: str, limit: int = 10000) -> str:
152
+ """先搜,再读取前几个结果,给轻量模型提供证据。"""
153
+ search_results = search_web(question)
154
+ if not search_results:
155
+ return "网页搜索没有返回可用结果。"
156
+
157
+ evidence_parts = ["网页搜索结果:"]
158
+ for index, result in enumerate(search_results, start=1):
159
+ evidence_parts.append(f"{index}. {result['title']} - {result['url']}")
160
+
161
+ for result in search_results[:3]:
162
+ page_text = fetch_url_text(result["url"], limit=3500)
163
+ evidence_parts.append(
164
+ f"\n--- 网页内容:{result['title']} ({result['url']}) ---\n{page_text}"
165
+ )
166
+
167
+ return truncate_text("\n".join(evidence_parts), limit)
168
+
169
+
170
+ def download_task_file(task_id: str, file_name: str) -> Path | None:
171
+ """下载课程接口中的附件,并缓存在 /tmp 下。"""
172
+ if not task_id or not file_name:
173
+ return None
174
+
175
+ destination = CACHE_DIR / task_id / file_name
176
+ if destination.exists() and destination.stat().st_size > 0:
177
+ return destination
178
+
179
+ destination.parent.mkdir(parents=True, exist_ok=True)
180
+ candidate_urls = [
181
+ f"{DEFAULT_API_URL}/files/{task_id}",
182
+ f"{DEFAULT_API_URL}/files/{file_name}",
183
+ f"{DEFAULT_API_URL}/files/{task_id}/{file_name}",
184
+ ]
185
+
186
+ for url in candidate_urls:
187
+ try:
188
+ response = requests.get(url, headers=REQUEST_HEADERS, timeout=45)
189
+ if response.status_code == 404:
190
+ continue
191
+ response.raise_for_status()
192
+ if response.content:
193
+ destination.write_bytes(response.content)
194
+ print(f"已下载附件:{file_name} -> {destination}")
195
+ return destination
196
+ except Exception as exc:
197
+ print(f"尝试下载附件失败:{url},错误:{exc}")
198
+
199
+ return None
200
+
201
+
202
+ def read_plain_file(file_path: Path, limit: int = 12000) -> str:
203
+ try:
204
+ return truncate_text(file_path.read_text(encoding="utf-8", errors="replace"), limit)
205
+ except Exception as exc:
206
+ return f"读取文件失败:{exc}"
207
+
208
+
209
+ def run_python_file(file_path: Path, timeout_seconds: int = 20) -> dict[str, str]:
210
+ """执行 Python 附件。课程文件通常是可运行小脚本。"""
211
+ try:
212
+ completed = subprocess.run(
213
+ [sys.executable, str(file_path)],
214
+ cwd=str(file_path.parent),
215
+ text=True,
216
+ capture_output=True,
217
+ timeout=timeout_seconds,
218
+ check=False,
219
+ )
220
+ return {
221
+ "stdout": truncate_text(completed.stdout, 8000),
222
+ "stderr": truncate_text(completed.stderr, 4000),
223
+ "returncode": str(completed.returncode),
224
+ }
225
+ except subprocess.TimeoutExpired:
226
+ return {"stdout": "", "stderr": "Python 执行超时。", "returncode": "timeout"}
227
+ except Exception as exc:
228
+ return {"stdout": "", "stderr": f"Python 执行失败:{exc}", "returncode": "error"}
229
+
230
+
231
+ def summarize_excel(file_path: Path, limit: int = 14000) -> str:
232
+ """读取 Excel 并生成紧凑摘要,避免把整份表格直接塞给模型。"""
233
+ try:
234
+ sheets = pd.read_excel(file_path, sheet_name=None)
235
+ except Exception as exc:
236
+ return f"读取 Excel 失败:{exc}"
237
+
238
+ parts = []
239
+ for sheet_name, df in sheets.items():
240
+ parts.append(f"工作表:{sheet_name}")
241
+ parts.append(f"行列数:{df.shape[0]} 行 x {df.shape[1]} 列")
242
+ parts.append(f"列名:{', '.join(map(str, df.columns.tolist()))}")
243
+
244
+ numeric_totals = df.select_dtypes(include="number").sum(numeric_only=True)
245
+ if not numeric_totals.empty:
246
+ totals_text = ", ".join(
247
+ f"{column}={value}" for column, value in numeric_totals.items()
248
+ )
249
+ parts.append(f"数值列合计:{totals_text}")
250
+
251
+ row_limit = 120 if len(df) <= 120 else 60
252
+ parts.append("表格样本:")
253
+ parts.append(df.head(row_limit).to_csv(index=False))
254
+
255
+ return truncate_text("\n".join(parts), limit)
256
+
257
+
258
+ def parse_hf_transcription_response(data: Any) -> str:
259
+ if isinstance(data, dict):
260
+ if isinstance(data.get("text"), str):
261
+ return data["text"]
262
+ if isinstance(data.get("error"), str):
263
+ return f"音频转写失败:{data['error']}"
264
+ return str(data)
265
+ if isinstance(data, list):
266
+ texts = []
267
+ for item in data:
268
+ if isinstance(item, dict) and isinstance(item.get("text"), str):
269
+ texts.append(item["text"])
270
+ if texts:
271
+ return "\n".join(texts)
272
+ return str(data)
273
+
274
+
275
+ def transcribe_audio(file_path: Path) -> str:
276
+ """调用 Hugging Face 音频模型转写。没有 HF_TOKEN 时只返回提示。"""
277
+ token = get_hf_token()
278
+ if not token:
279
+ return "未配置 HF_TOKEN,无法调用 Hugging Face 音频转写模型。"
280
+
281
+ endpoint = f"https://api-inference.huggingface.co/models/{HF_AUDIO_MODEL}"
282
+ headers = {"Authorization": f"Bearer {token}"}
283
+
284
+ for attempt in range(3):
285
+ try:
286
+ response = requests.post(
287
+ endpoint,
288
+ headers=headers,
289
+ data=file_path.read_bytes(),
290
+ timeout=180,
291
+ )
292
+ if response.status_code == 503 and attempt < 2:
293
+ try:
294
+ wait_seconds = int(response.json().get("estimated_time", 10)) + 1
295
+ except Exception:
296
+ wait_seconds = 10
297
+ time.sleep(min(wait_seconds, 30))
298
+ continue
299
+ response.raise_for_status()
300
+ return parse_hf_transcription_response(response.json())
301
+ except Exception as exc:
302
+ if attempt == 2:
303
+ return f"音频转写失败:{exc}"
304
+ time.sleep(2)
305
+
306
+ return "音频转写失败。"
307
+
308
+
309
+ def clean_subtitle_text(raw_text: str) -> str:
310
+ lines = []
311
+ for line in raw_text.splitlines():
312
+ line = line.strip()
313
+ if not line:
314
+ continue
315
+ if line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE")):
316
+ continue
317
+ if "-->" in line:
318
+ continue
319
+ if line.isdigit():
320
+ continue
321
+ line = re.sub(r"<[^>]+>", "", line)
322
+ line = html.unescape(line)
323
+ if line and (not lines or lines[-1] != line):
324
+ lines.append(line)
325
+ return " ".join(lines)
326
+
327
+
328
+ def clean_json3_caption(raw_text: str) -> str:
329
+ try:
330
+ data = requests.models.complexjson.loads(raw_text)
331
+ except Exception:
332
+ return clean_subtitle_text(raw_text)
333
+
334
+ pieces = []
335
+ for event in data.get("events", []):
336
+ for segment in event.get("segs", []):
337
+ text = segment.get("utf8", "")
338
+ if text.strip():
339
+ pieces.append(text.strip())
340
+ return " ".join(pieces)
341
+
342
+
343
+ def get_youtube_transcript(url: str, limit: int = 12000) -> str:
344
+ """优先读取 YouTube 字幕,避免下载视频和消耗视觉/音频模型额度。"""
345
+ try:
346
+ from yt_dlp import YoutubeDL
347
+ except Exception as exc:
348
+ return f"yt-dlp 不可用,无法读取 YouTube 字幕:{exc}"
349
+
350
+ try:
351
+ with YoutubeDL({"quiet": True, "skip_download": True}) as ydl:
352
+ info = ydl.extract_info(url, download=False)
353
+
354
+ title = info.get("title", "")
355
+ description = info.get("description", "")
356
+ subtitles = info.get("subtitles") or {}
357
+ automatic_captions = info.get("automatic_captions") or {}
358
+ tracks = (
359
+ subtitles.get("en")
360
+ or subtitles.get("en-US")
361
+ or automatic_captions.get("en")
362
+ or automatic_captions.get("en-US")
363
+ or []
364
+ )
365
+
366
+ if not tracks:
367
+ return truncate_text(
368
+ f"YouTube 标题:{title}\n简介:{description}\n未找到英文字幕。",
369
+ limit,
370
+ )
371
+
372
+ preferred_tracks = sorted(
373
+ tracks,
374
+ key=lambda item: 0 if item.get("ext") in {"vtt", "json3"} else 1,
375
+ )
376
+ for track in preferred_tracks:
377
+ track_url = track.get("url")
378
+ if not track_url:
379
+ continue
380
+ subtitle_response = requests.get(track_url, headers=REQUEST_HEADERS, timeout=45)
381
+ subtitle_response.raise_for_status()
382
+ if track.get("ext") == "json3":
383
+ transcript = clean_json3_caption(subtitle_response.text)
384
+ else:
385
+ transcript = clean_subtitle_text(subtitle_response.text)
386
+ if transcript:
387
+ return truncate_text(
388
+ f"YouTube 标题:{title}\n字幕:\n{transcript}",
389
+ limit,
390
+ )
391
+
392
+ return f"YouTube 标题:{title}\n找到字幕轨道,但未能解析出文本。"
393
+ except Exception as exc:
394
+ return f"读取 YouTube 字幕失败:{exc}"
395
+
396
+
397
+ def call_hf_chat(messages: list[dict[str, Any]], model: str, max_tokens: int = 512) -> str:
398
+ token = get_hf_token()
399
+ if not token:
400
+ raise RuntimeError("未配置 HF_TOKEN。")
401
+
402
+ response = requests.post(
403
+ HF_ROUTER_URL,
404
+ headers={
405
+ "Authorization": f"Bearer {token}",
406
+ "Content-Type": "application/json",
407
+ },
408
+ json={
409
+ "model": model,
410
+ "messages": messages,
411
+ "temperature": 0.1,
412
+ "max_tokens": max_tokens,
413
+ },
414
+ timeout=180,
415
+ )
416
+ response.raise_for_status()
417
+ data = response.json()
418
+ return data["choices"][0]["message"]["content"]
419
+
420
+
421
+ def describe_image_with_vision_model(file_path: Path, question: str) -> str:
422
+ """可选视觉模型。默认关闭,避免普通账号消耗太快。"""
423
+ if not HF_VISION_MODEL:
424
+ return (
425
+ "检测到图片附件,但未配置 HF_VISION_MODEL。"
426
+ "如果是棋局、图表或截图题,需要设置视觉模型。"
427
+ )
428
+
429
+ mime_type = mimetypes.guess_type(str(file_path))[0] or "image/png"
430
+ image_data = base64.b64encode(file_path.read_bytes()).decode("utf-8")
431
+ data_url = f"data:{mime_type};base64,{image_data}"
432
+ prompt = (
433
+ "请仔细分析这张图片,只提取回答问题所需的信息。"
434
+ "如果图片是棋局,请尽量给出棋盘位置、FEN、轮到谁走、候选最佳走法。"
435
+ f"\n\n问题:{question}"
436
+ )
437
+
438
+ try:
439
+ return call_hf_chat(
440
+ [
441
+ {
442
+ "role": "user",
443
+ "content": [
444
+ {"type": "text", "text": prompt},
445
+ {"type": "image_url", "image_url": {"url": data_url}},
446
+ ],
447
+ }
448
+ ],
449
+ model=HF_VISION_MODEL,
450
+ max_tokens=700,
451
+ )
452
+ except Exception as exc:
453
+ return f"视觉模型调用失败:{exc}"
454
+
455
+
456
+ def question_is_self_contained(question: str) -> bool:
457
+ lower_question = question.lower()
458
+ if "|---|" in question or "given this table" in lower_question:
459
+ return True
460
+ if "grocery list" in lower_question or "here's the list" in lower_question:
461
+ return True
462
+ reversed_question = question[::-1].lower()
463
+ if "if you understand this sentence" in reversed_question:
464
+ return True
465
+ return False
466
+
467
+
468
+ def parse_commutativity_counterexample_subset(question: str) -> str | None:
469
+ """解析当前课程中的 Cayley 表,直接求非交换反例涉及的元素集合。"""
470
+ if "|---|" not in question or "not commutative" not in question.lower():
471
+ return None
472
+
473
+ rows = []
474
+ for line in question.splitlines():
475
+ line = line.strip()
476
+ if not line.startswith("|") or "---" in line:
477
+ continue
478
+ cells = [cell.strip() for cell in line.strip("|").split("|")]
479
+ rows.append(cells)
480
+
481
+ if len(rows) < 2:
482
+ return None
483
+
484
+ headers = rows[0][1:]
485
+ table = {}
486
+ for row in rows[1:]:
487
+ if len(row) != len(headers) + 1:
488
+ continue
489
+ row_label = row[0]
490
+ table[row_label] = dict(zip(headers, row[1:]))
491
 
492
+ involved = set()
493
+ for left in headers:
494
+ for right in headers:
495
+ left_right = table.get(left, {}).get(right)
496
+ right_left = table.get(right, {}).get(left)
497
+ if left_right is not None and right_left is not None and left_right != right_left:
498
+ involved.update([left, right])
499
+
500
+ if involved:
501
+ return ", ".join(sorted(involved))
502
+ return None
503
+
504
+
505
+ def parse_reversed_question(question: str) -> str | None:
506
+ reversed_question = question[::-1]
507
+ lower_reversed = reversed_question.lower()
508
+ if "opposite of the word" in lower_reversed and '"left"' in lower_reversed:
509
+ return "right"
510
+ return None
511
+
512
+
513
+ def extract_last_numeric_stdout(stdout: str) -> str | None:
514
+ lines = [line.strip() for line in stdout.splitlines() if line.strip()]
515
+ if not lines:
516
+ return None
517
+ numbers = re.findall(r"[-+]?\d+(?:\.\d+)?", lines[-1])
518
+ if numbers:
519
+ return numbers[-1]
520
+ return lines[-1]
521
+
522
+
523
+ def build_evidence(question: str, task_id: str, file_name: str) -> tuple[str, dict[str, Any]]:
524
+ evidence_parts = []
525
+ tool_data: dict[str, Any] = {}
526
+
527
+ file_path = download_task_file(task_id, file_name) if file_name else None
528
+ if file_name and not file_path:
529
+ evidence_parts.append(f"附件 {file_name} 下载失败。")
530
+
531
+ if file_path:
532
+ tool_data["file_path"] = str(file_path)
533
+ extension = file_path.suffix.lower()
534
+ evidence_parts.append(f"附件路径:{file_path}")
535
+
536
+ if extension == ".py":
537
+ source = read_plain_file(file_path)
538
+ execution = run_python_file(file_path)
539
+ tool_data["python_stdout"] = execution["stdout"]
540
+ tool_data["python_stderr"] = execution["stderr"]
541
+ evidence_parts.append(f"Python 源码:\n{source}")
542
+ evidence_parts.append(
543
+ "Python 执行结果:\n"
544
+ f"returncode={execution['returncode']}\n"
545
+ f"stdout=\n{execution['stdout']}\n"
546
+ f"stderr=\n{execution['stderr']}"
547
+ )
548
+ elif extension in {".xlsx", ".xls"}:
549
+ excel_summary = summarize_excel(file_path)
550
+ tool_data["excel_summary"] = excel_summary
551
+ evidence_parts.append(f"Excel 摘要:\n{excel_summary}")
552
+ elif extension in {".mp3", ".wav", ".m4a", ".flac"}:
553
+ transcript = transcribe_audio(file_path)
554
+ tool_data["audio_transcript"] = transcript
555
+ evidence_parts.append(f"音频转写:\n{transcript}")
556
+ elif extension in {".png", ".jpg", ".jpeg", ".webp"}:
557
+ image_description = describe_image_with_vision_model(file_path, question)
558
+ tool_data["image_description"] = image_description
559
+ evidence_parts.append(f"��片分析:\n{image_description}")
560
+ elif extension in {".txt", ".csv", ".json", ".md"}:
561
+ evidence_parts.append(f"文本附件内容:\n{read_plain_file(file_path)}")
562
+ else:
563
+ evidence_parts.append(f"未知附件类型:{extension}")
564
+
565
+ urls = extract_urls(question)
566
+ for url in urls:
567
+ if is_youtube_url(url):
568
+ youtube_evidence = get_youtube_transcript(url)
569
+ tool_data.setdefault("youtube_transcripts", []).append(youtube_evidence)
570
+ evidence_parts.append(f"YouTube 证据:\n{youtube_evidence}")
571
+ else:
572
+ evidence_parts.append(f"网页 {url} 内容:\n{fetch_url_text(url)}")
573
+
574
+ if not urls and not question_is_self_contained(question):
575
+ evidence_parts.append(f"搜索证据:\n{collect_web_evidence(question)}")
576
+
577
+ return truncate_text("\n\n".join(evidence_parts)), tool_data
578
+
579
+
580
+ def try_direct_answer(question: str, tool_data: dict[str, Any]) -> str | None:
581
+ """低成本直接作答:能用确定性规则解决的题,不调用大模型。"""
582
+ reversed_answer = parse_reversed_question(question)
583
+ if reversed_answer:
584
+ return reversed_answer
585
+
586
+ commutativity_answer = parse_commutativity_counterexample_subset(question)
587
+ if commutativity_answer:
588
+ return commutativity_answer
589
+
590
+ if "final numeric output" in question.lower() and tool_data.get("python_stdout"):
591
+ return extract_last_numeric_stdout(tool_data["python_stdout"])
592
+
593
+ return None
594
+
595
+
596
+ def answer_with_light_model(question: str, evidence: str) -> str:
597
+ """轻量模型只做最后综合,不承担文件处理和大规模检索。"""
598
+ prompt = f"""
599
+ 你是一个 GAIA 问答 Agent。你会收到问题和工具已经整理好的证据。
600
+
601
+ 硬性规则:
602
+ 1. 只输出最终答案,不输出推理过程。
603
+ 2. 严格遵守题目要求的格式、大小写、排序、逗号、单位和小数位。
604
+ 3. 如果证据不足,不要编造;输出你能从证据中最可靠得到的答案。
605
+ 4. 不要添加 "Answer:"、"最终答案:" 或解释性文字。
606
+
607
+ 问题:
608
+ {question}
609
+
610
+ 工具证据:
611
+ {evidence}
612
+ """.strip()
613
+
614
+ raw_answer = call_hf_chat(
615
+ [
616
+ {
617
+ "role": "system",
618
+ "content": "You are a precise GAIA final-answer agent. Return only the final answer.",
619
+ },
620
+ {"role": "user", "content": prompt},
621
+ ],
622
+ model=HF_TEXT_MODEL,
623
+ max_tokens=500,
624
+ )
625
+ return normalize_answer(raw_answer)
626
+
627
+
628
+ # --- 工具优先 Agent 定义 ---
629
  class BasicAgent:
630
  def __init__(self):
631
+ print("工具优先 Agent 已初始化。")
632
+ print(f"文本模型:{HF_TEXT_MODEL}")
633
+ print(f"音频模型:{HF_AUDIO_MODEL}")
634
+ print(f"视觉模型:{HF_VISION_MODEL or '未启用'}")
635
+
636
+ def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
637
+ print(f"Agent 收到问题(前 80 个字符):{question[:80]}...")
638
+ evidence, tool_data = build_evidence(question, task_id, file_name)
639
+
640
+ direct_answer = try_direct_answer(question, tool_data)
641
+ if direct_answer:
642
+ final_answer = normalize_answer(direct_answer)
643
+ print(f"工具直接作答:{final_answer}")
644
+ return final_answer
645
+
646
+ try:
647
+ final_answer = answer_with_light_model(question, evidence)
648
+ print(f"轻量模型最终答案:{final_answer}")
649
+ return final_answer
650
+ except Exception as exc:
651
+ fallback = (
652
+ "LLM_ERROR: "
653
+ f"{exc}. 请检查 HF_TOKEN、HF_TEXT_MODEL 或模型服务商额度。"
654
+ )
655
+ print(fallback)
656
+ return fallback
657
+
658
+
659
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
660
  """
661
+ 拉取全部问题,使用 BasicAgent 逐题作答,提交全部答案,并展示评测结果。
 
662
  """
663
+ # --- 确定 HF Space 运行地址和代码仓库地址 ---
664
+ space_id = os.getenv("SPACE_ID") # 用于生成提交时携带的代码链接。
665
 
666
  if profile:
667
+ username = f"{profile.username}"
668
+ print(f"用户已登录:{username}")
669
  else:
670
+ print("用户未登录。")
671
+ return "请先点击按钮登录 Hugging Face。", None
672
 
673
  api_url = DEFAULT_API_URL
674
  questions_url = f"{api_url}/questions"
675
  submit_url = f"{api_url}/submit"
676
 
677
+ # 1. 实例化 Agent。
678
  try:
679
  agent = BasicAgent()
680
  except Exception as e:
681
+ print(f"实例化 Agent 时出错:{e}")
682
+ return f"Agent 初始化失败:{e}", None
683
+
684
+ # 在 Hugging Face Space 中运行时,这个链接指向你的代码仓库。评测系统会记录它,请保持仓库公开可访问。
685
+ agent_code = (
686
+ f"https://huggingface.co/spaces/{space_id}/tree/main"
687
+ if space_id
688
+ else "本地运行,未提供 SPACE_ID。"
689
+ )
690
  print(agent_code)
691
 
692
+ # 2. 拉取问题。
693
+ print(f"正在从以下地址拉取问题:{questions_url}")
694
  try:
695
  response = requests.get(questions_url, timeout=15)
696
  response.raise_for_status()
697
  questions_data = response.json()
698
  if not questions_data:
699
+ print("拉取到的问题列表为空。")
700
+ return "拉取到的问题列表为空,或返回格式无效。", None
701
+ print(f"已拉取 {len(questions_data)} 个问题。")
702
  except requests.exceptions.RequestException as e:
703
+ print(f"拉取问题时发生网络错误:{e}")
704
+ return f"拉取问题失败:{e}", None
705
  except requests.exceptions.JSONDecodeError as e:
706
+ print(f"解析问题接口的 JSON 响应时出错:{e}")
707
+ print(f"响应文本:{response.text[:500]}")
708
+ return f"解析问题接口响应失败:{e}", None
709
  except Exception as e:
710
+ print(f"拉取问题时发生未预期错误:{e}")
711
+ return f"拉取问题时发生未预期错误:{e}", None
712
 
713
+ # 3. 运行 Agent。
714
  results_log = []
715
  answers_payload = []
716
+ print(f"正在让 Agent 处理 {len(questions_data)} 个问题...")
717
  for item in questions_data:
718
  task_id = item.get("task_id")
719
  question_text = item.get("question")
720
+ file_name = item.get("file_name") or ""
721
  if not task_id or question_text is None:
722
+ print(f"跳过缺少 task_id 或 question 的条目:{item}")
723
  continue
724
  try:
725
+ submitted_answer = agent(question_text, task_id=task_id, file_name=file_name)
726
+ answers_payload.append(
727
+ {"task_id": task_id, "submitted_answer": submitted_answer}
728
+ )
729
+ results_log.append(
730
+ {
731
+ "任务 ID": task_id,
732
+ "附件": file_name,
733
+ "问题": question_text,
734
+ "提交答案": submitted_answer,
735
+ }
736
+ )
737
  except Exception as e:
738
+ print(f"Agent 处理任务 {task_id} 时出错:{e}")
739
+ results_log.append(
740
+ {
741
+ "任务 ID": task_id,
742
+ "附件": file_name,
743
+ "问题": question_text,
744
+ "提交答案": f"AGENT ERROR: {e}",
745
+ }
746
+ )
747
 
748
  if not answers_payload:
749
+ print("Agent 没有生成任何可提交的答案。")
750
+ return "Agent 没有生成任何可提交的答案。", pd.DataFrame(results_log)
751
 
752
+ # 4. 准备提交数据。
753
+ submission_data = {
754
+ "username": username.strip(),
755
+ "agent_code": agent_code,
756
+ "answers": answers_payload,
757
+ }
758
+ status_update = f"Agent 已完成作答。正在为用户 '{username}' 提交 {len(answers_payload)} 个答案..."
759
  print(status_update)
760
 
761
+ # 5. 提交答案。
762
+ print(f"正在向以下地址提交 {len(answers_payload)} 个答案:{submit_url}")
763
  try:
764
  response = requests.post(submit_url, json=submission_data, timeout=60)
765
  response.raise_for_status()
766
  result_data = response.json()
767
  final_status = (
768
+ f"提交成功!\n"
769
+ f"用户:{result_data.get('username')}\n"
770
+ f"总分:{result_data.get('score', 'N/A')}% "
771
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} 正确)\n"
772
+ f"消息:{result_data.get('message', '未收到消息。')}"
773
  )
774
+ print("提交成功。")
775
  results_df = pd.DataFrame(results_log)
776
  return final_status, results_df
777
  except requests.exceptions.HTTPError as e:
778
+ error_detail = f"服务器返回状态码 {e.response.status_code}。"
779
  try:
780
  error_json = e.response.json()
781
+ error_detail += f" 详情:{error_json.get('detail', e.response.text)}"
782
  except requests.exceptions.JSONDecodeError:
783
+ error_detail += f" 响应:{e.response.text[:500]}"
784
+ status_message = f"提交失败:{error_detail}"
785
  print(status_message)
786
  results_df = pd.DataFrame(results_log)
787
  return status_message, results_df
788
  except requests.exceptions.Timeout:
789
+ status_message = "提交失败:请求超时。"
790
  print(status_message)
791
  results_df = pd.DataFrame(results_log)
792
  return status_message, results_df
793
  except requests.exceptions.RequestException as e:
794
+ status_message = f"提交失败:网络错误 - {e}"
795
  print(status_message)
796
  results_df = pd.DataFrame(results_log)
797
  return status_message, results_df
798
  except Exception as e:
799
+ status_message = f"提交过程中发生未预期错误:{e}"
800
  print(status_message)
801
  results_df = pd.DataFrame(results_log)
802
  return status_message, results_df
803
 
804
 
805
+ # --- 使用 Gradio Blocks 构建界面 ---
806
  with gr.Blocks() as demo:
807
+ gr.Markdown("# 工具优先 GAIA Agent 评测运行器")
808
  gr.Markdown(
809
  """
810
+ **使用说明:**
811
 
812
+ 1. 在 Hugging Face Space Secrets 中配置 `HF_TOKEN`。
813
+ 2. 默认文本模型为 `openai/gpt-oss-20b:cheapest`,可以用 `HF_TEXT_MODEL` 替换。
814
+ 3. 默认音频模型为 `openai/whisper-large-v3-turbo`,可以用 `HF_AUDIO_MODEL` 替换。
815
+ 4. 图片题默认不启用视觉模型;如需处理棋局或截图题,设置 `HF_VISION_MODEL`。
816
+ 5. 点击“运行评测并提交全部答案”,系统会先运行工具,再用轻量模型汇总最终答案。
817
 
818
  ---
819
+ **省额度策略:**
820
+ `.py` 会本地执行,`.xlsx` 会本地读取,YouTube 优先读取字幕,网页题先搜索和抓取页面。
821
+ 大模型只在最后根据工具证据生成严格格式的答案。
822
  """
823
  )
824
 
825
  gr.LoginButton()
826
 
827
+ run_button = gr.Button("运行评测并提交全部答案")
828
 
829
+ status_output = gr.Textbox(label="运行状态 / 提交结果", lines=5, interactive=False)
830
+ results_table = gr.DataFrame(label="问题与 Agent 答案", wrap=True)
 
831
 
832
  run_button.click(
833
  fn=run_and_submit_all,
834
+ outputs=[status_output, results_table],
835
  )
836
 
837
+
838
  if __name__ == "__main__":
839
+ print("\n" + "-" * 30 + " 应用启动中 " + "-" * 30)
840
+ # 启动时检查 SPACE_HOST 和 SPACE_ID,方便确认当前运行环境。
841
  space_host_startup = os.getenv("SPACE_HOST")
842
+ space_id_startup = os.getenv("SPACE_ID") # 启动时读取 SPACE_ID。
843
 
844
  if space_host_startup:
845
+ print(f"找到 SPACE_HOST:{space_host_startup}")
846
+ print(f" 运行地址应为:https://{space_host_startup}.hf.space")
847
  else:
848
+ print("未找到 SPACE_HOST 环境变量(可能是在本地运行)。")
849
 
850
+ if space_id_startup: # 找到 SPACE_ID 时打印仓库地址。
851
+ print(f"找到 SPACE_ID:{space_id_startup}")
852
+ print(f" 仓库地址:https://huggingface.co/spaces/{space_id_startup}")
853
+ print(f" 代码树地址:https://huggingface.co/spaces/{space_id_startup}/tree/main")
854
  else:
855
+ print("未找到 SPACE_ID 环境变量(可能是在本地运行)。无法确定仓库地址。")
856
 
857
+ print("-" * (60 + len(" 应用启动中 ")) + "\n")
858
 
859
+ print("正在启动工具优先 GAIA Agent 评测 Gradio 界面...")
860
+ demo.launch(debug=True, share=False)
requirements.txt CHANGED
@@ -1,2 +1,6 @@
1
  gradio
2
- requests
 
 
 
 
 
1
  gradio
2
+ requests
3
+ pandas
4
+ beautifulsoup4
5
+ openpyxl
6
+ yt-dlp