ADD DOWNLOAD_UNIVERSAL
Browse files
app.py
CHANGED
|
@@ -4,6 +4,8 @@ import requests
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
import time
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
|
@@ -15,33 +17,123 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 15 |
from smolagents import CodeAgent, LiteLLMModel
|
| 16 |
from my_tools import my_tool_list
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
os.makedirs(save_dir, exist_ok=True)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
resp.raise_for_status()
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
with open(save_path, "wb") as f:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
return None
|
| 42 |
except Exception as e:
|
| 43 |
-
print(f"
|
| 44 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
class BasicAgent:
|
| 47 |
def __init__(self):
|
|
@@ -66,19 +158,35 @@ class BasicAgent:
|
|
| 66 |
else:
|
| 67 |
print(f"{self.agent_name} received question: {question[:80]}...")
|
| 68 |
try:
|
| 69 |
-
# system prompt + question
|
| 70 |
system_prompt = """
|
| 71 |
You are Celum, an advanced agent skilled at using external tools and step-by-step reasoning to solve real-world problems.
|
| 72 |
You may freely think, reason, and use tools or your own knowledge as needed to solve the problem.
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
"""
|
|
|
|
| 79 |
files_prompt = ""
|
| 80 |
if files:
|
| 81 |
-
files_prompt = f"\n[You have the following attached files: {', '.join(files)}]\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
full_question = system_prompt + files_prompt + "\n\n" + question
|
| 83 |
return self.agent.run(full_question)
|
| 84 |
except Exception as e:
|
|
@@ -153,39 +261,63 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 153 |
results_log = []
|
| 154 |
answers_payload = []
|
| 155 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 156 |
for idx, item in enumerate(questions_data[3:4]):
|
| 157 |
task_id = item.get("task_id")
|
| 158 |
question_text = item.get("question")
|
| 159 |
file_list = item.get("files", [])
|
| 160 |
-
print(f"[DEBUG] Q{idx+1}/{len(questions_data)} | task_id={task_id} | files={file_list}")
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
local_files = []
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
|
|
|
|
| 171 |
try:
|
| 172 |
submitted_answer = safe_run_agent(agent, question_text, local_files, idx, len(questions_data))
|
|
|
|
| 173 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 174 |
results_log.append({
|
| 175 |
"Task ID": task_id,
|
| 176 |
-
"Question": question_text,
|
| 177 |
"Submitted Answer": submitted_answer,
|
| 178 |
-
"Files": local_files
|
| 179 |
})
|
|
|
|
|
|
|
|
|
|
| 180 |
except Exception as e:
|
| 181 |
-
|
|
|
|
|
|
|
| 182 |
results_log.append({
|
| 183 |
"Task ID": task_id,
|
| 184 |
-
"Question": question_text,
|
| 185 |
-
"Submitted Answer":
|
| 186 |
-
"Files":
|
| 187 |
})
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
if not answers_payload:
|
| 191 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
import time
|
| 7 |
+
import mimetypes
|
| 8 |
+
from pathlib import Path
|
| 9 |
|
| 10 |
# (Keep Constants as is)
|
| 11 |
# --- Constants ---
|
|
|
|
| 17 |
from smolagents import CodeAgent, LiteLLMModel
|
| 18 |
from my_tools import my_tool_list
|
| 19 |
|
| 20 |
+
import mimetypes
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
def download_file_universal(task_id, save_dir="attachments"):
|
| 24 |
+
"""
|
| 25 |
+
通用文件下载,自动检测文件类型和扩展名
|
| 26 |
+
"""
|
| 27 |
os.makedirs(save_dir, exist_ok=True)
|
| 28 |
+
|
| 29 |
+
url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
|
| 30 |
+
|
| 31 |
+
print(f"[DEBUG] Downloading from: {url}")
|
| 32 |
+
|
| 33 |
try:
|
| 34 |
+
headers = {
|
| 35 |
+
'Accept': '*/*',
|
| 36 |
+
'User-Agent': 'Mozilla/5.0 (compatible; Agent/1.0)'
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
resp = requests.get(url, headers=headers, timeout=30, stream=True)
|
| 40 |
+
print(f"[DEBUG] HTTP {resp.status_code}")
|
| 41 |
+
print(f"[DEBUG] Content-Type: {resp.headers.get('content-type', 'Unknown')}")
|
| 42 |
+
print(f"[DEBUG] Content-Disposition: {resp.headers.get('content-disposition', 'Unknown')}")
|
| 43 |
+
|
| 44 |
resp.raise_for_status()
|
| 45 |
|
| 46 |
+
# 从Content-Disposition获取原始文件名
|
| 47 |
+
filename = None
|
| 48 |
+
content_disp = resp.headers.get('content-disposition', '')
|
| 49 |
+
if 'filename=' in content_disp:
|
| 50 |
+
filename = content_disp.split('filename=')[1].strip('"\'')
|
| 51 |
+
|
| 52 |
+
# 如果没有文件名,根据Content-Type推断
|
| 53 |
+
if not filename:
|
| 54 |
+
content_type = resp.headers.get('content-type', '').lower()
|
| 55 |
+
ext = mimetypes.guess_extension(content_type.split(';')[0])
|
| 56 |
+
if not ext:
|
| 57 |
+
# 手动映射常见类型
|
| 58 |
+
type_map = {
|
| 59 |
+
'image/png': '.png',
|
| 60 |
+
'image/jpeg': '.jpg',
|
| 61 |
+
'image/gif': '.gif',
|
| 62 |
+
'video/mp4': '.mp4',
|
| 63 |
+
'video/avi': '.avi',
|
| 64 |
+
'video/mov': '.mov',
|
| 65 |
+
'audio/mp3': '.mp3',
|
| 66 |
+
'audio/wav': '.wav',
|
| 67 |
+
'audio/mpeg': '.mp3',
|
| 68 |
+
'application/pdf': '.pdf',
|
| 69 |
+
'text/plain': '.txt',
|
| 70 |
+
'application/json': '.json',
|
| 71 |
+
'text/csv': '.csv'
|
| 72 |
+
}
|
| 73 |
+
ext = type_map.get(content_type.split(';')[0], '.bin')
|
| 74 |
+
filename = f"{task_id}{ext}"
|
| 75 |
+
|
| 76 |
+
save_path = os.path.join(save_dir, filename)
|
| 77 |
+
print(f"[DEBUG] Saving as: {save_path}")
|
| 78 |
+
|
| 79 |
+
# 流式下载,适合大文件
|
| 80 |
with open(save_path, "wb") as f:
|
| 81 |
+
for chunk in resp.iter_content(chunk_size=8192):
|
| 82 |
+
f.write(chunk)
|
| 83 |
+
|
| 84 |
+
file_size = os.path.getsize(save_path)
|
| 85 |
+
print(f"[DEBUG] Successfully saved: {filename} ({file_size} bytes)")
|
| 86 |
+
|
| 87 |
+
return save_path, filename
|
| 88 |
+
|
|
|
|
| 89 |
except Exception as e:
|
| 90 |
+
print(f"[DEBUG] Download error: {e}")
|
| 91 |
+
return None, None
|
| 92 |
+
|
| 93 |
+
def download_task_files_on_demand(task_id, file_list, save_dir="attachments"):
|
| 94 |
+
"""
|
| 95 |
+
按需下载:处理每个问题时才下载对应文件
|
| 96 |
+
"""
|
| 97 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 98 |
+
downloaded_files = []
|
| 99 |
+
|
| 100 |
+
if not file_list:
|
| 101 |
+
print(f"[INFO] No files listed for task {task_id}, attempting direct download...")
|
| 102 |
+
file_path, filename = download_file_universal(task_id, save_dir)
|
| 103 |
+
if file_path:
|
| 104 |
+
downloaded_files.append(file_path)
|
| 105 |
+
else:
|
| 106 |
+
print(f"[INFO] Task {task_id} has {len(file_list)} files to download")
|
| 107 |
+
for expected_filename in file_list:
|
| 108 |
+
# 先检查是否已经下载过
|
| 109 |
+
potential_path = os.path.join(save_dir, expected_filename)
|
| 110 |
+
if os.path.exists(potential_path):
|
| 111 |
+
print(f"[CACHE] File already exists: {expected_filename}")
|
| 112 |
+
downloaded_files.append(potential_path)
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
# 下载文件
|
| 116 |
+
file_path, actual_filename = download_file_universal(task_id, save_dir)
|
| 117 |
+
if file_path:
|
| 118 |
+
# 如果实际文件名与期望不符,重命名
|
| 119 |
+
if actual_filename != expected_filename:
|
| 120 |
+
new_path = os.path.join(save_dir, expected_filename)
|
| 121 |
+
try:
|
| 122 |
+
os.rename(file_path, new_path)
|
| 123 |
+
file_path = new_path
|
| 124 |
+
print(f"[INFO] Renamed {actual_filename} to {expected_filename}")
|
| 125 |
+
except:
|
| 126 |
+
print(f"[WARN] Could not rename file, keeping as {actual_filename}")
|
| 127 |
+
|
| 128 |
+
downloaded_files.append(file_path)
|
| 129 |
+
print(f"[SUCCESS] Downloaded: {os.path.basename(file_path)}")
|
| 130 |
+
else:
|
| 131 |
+
print(f"[FAIL] Could not download: {expected_filename}")
|
| 132 |
+
|
| 133 |
+
# 添加小延迟避免速率限制
|
| 134 |
+
time.sleep(0.5)
|
| 135 |
+
|
| 136 |
+
return downloaded_files
|
| 137 |
|
| 138 |
class BasicAgent:
|
| 139 |
def __init__(self):
|
|
|
|
| 158 |
else:
|
| 159 |
print(f"{self.agent_name} received question: {question[:80]}...")
|
| 160 |
try:
|
|
|
|
| 161 |
system_prompt = """
|
| 162 |
You are Celum, an advanced agent skilled at using external tools and step-by-step reasoning to solve real-world problems.
|
| 163 |
You may freely think, reason, and use tools or your own knowledge as needed to solve the problem.
|
| 164 |
+
|
| 165 |
+
IMPORTANT OUTPUT INSTRUCTIONS:
|
| 166 |
+
- When you need to return your final answer, use print() to output it
|
| 167 |
+
- For example: print("Qxf7") or print("42") or print("unknown")
|
| 168 |
+
- DO NOT just write the answer as a standalone variable
|
| 169 |
+
- If you cannot solve the problem, use: print("unknown")
|
| 170 |
+
|
| 171 |
+
Answer format requirements:
|
| 172 |
+
- If the answer is a number, output only the number (no units, no commas)
|
| 173 |
+
- If the answer is a word or string, do not use articles or abbreviations, and write digits as plain numbers
|
| 174 |
+
- If the answer is a comma-separated list, apply the same rules to each item
|
| 175 |
+
- If you cannot answer, return the word 'unknown'
|
| 176 |
"""
|
| 177 |
+
|
| 178 |
files_prompt = ""
|
| 179 |
if files:
|
| 180 |
+
files_prompt = f"\n[You have the following attached files available: {', '.join(files)}]\n"
|
| 181 |
+
# 添加文件处理指导
|
| 182 |
+
files_prompt += """
|
| 183 |
+
To work with image files, you can:
|
| 184 |
+
1. Use PIL (from PIL import Image) to load and analyze images
|
| 185 |
+
2. Use cv2 (import cv2) for image processing
|
| 186 |
+
3. For chess positions, you might need to analyze the board position pixel by pixel
|
| 187 |
+
4. Consider using OCR libraries if there's text in the image
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
full_question = system_prompt + files_prompt + "\n\n" + question
|
| 191 |
return self.agent.run(full_question)
|
| 192 |
except Exception as e:
|
|
|
|
| 261 |
results_log = []
|
| 262 |
answers_payload = []
|
| 263 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 264 |
+
|
| 265 |
for idx, item in enumerate(questions_data[3:4]):
|
| 266 |
task_id = item.get("task_id")
|
| 267 |
question_text = item.get("question")
|
| 268 |
file_list = item.get("files", [])
|
|
|
|
| 269 |
|
| 270 |
+
print(f"\n{'='*60}")
|
| 271 |
+
print(f"Processing Question {idx+1}/{len(questions_data)}")
|
| 272 |
+
print(f"Task ID: {task_id}")
|
| 273 |
+
print(f"Question: {question_text[:100]}...")
|
| 274 |
+
print(f"Expected files: {file_list}")
|
| 275 |
+
print(f"{'='*60}")
|
| 276 |
+
|
| 277 |
+
# 按需下载文件
|
| 278 |
local_files = []
|
| 279 |
+
if file_list or True: # 总是尝试下载,因为有些任务可能没有在file_list中列出
|
| 280 |
+
print(f"[DOWNLOAD] Starting download for task {task_id}...")
|
| 281 |
+
local_files = download_task_files_on_demand(task_id, file_list)
|
| 282 |
+
|
| 283 |
+
if local_files:
|
| 284 |
+
print(f"[DOWNLOAD] Successfully got {len(local_files)} files:")
|
| 285 |
+
for f in local_files:
|
| 286 |
+
size = os.path.getsize(f)
|
| 287 |
+
print(f" - {os.path.basename(f)} ({size} bytes)")
|
| 288 |
+
else:
|
| 289 |
+
print(f"[DOWNLOAD] No files downloaded for task {task_id}")
|
| 290 |
|
| 291 |
+
# 运行Agent
|
| 292 |
+
print(f"[AGENT] Running Celum on question {idx+1}...")
|
| 293 |
try:
|
| 294 |
submitted_answer = safe_run_agent(agent, question_text, local_files, idx, len(questions_data))
|
| 295 |
+
|
| 296 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 297 |
results_log.append({
|
| 298 |
"Task ID": task_id,
|
| 299 |
+
"Question": question_text[:100] + "...",
|
| 300 |
"Submitted Answer": submitted_answer,
|
| 301 |
+
"Files": [os.path.basename(f) for f in local_files] if local_files else []
|
| 302 |
})
|
| 303 |
+
|
| 304 |
+
print(f"[AGENT] Answer: {submitted_answer}")
|
| 305 |
+
|
| 306 |
except Exception as e:
|
| 307 |
+
error_msg = f"AGENT ERROR: {e}"
|
| 308 |
+
print(f"[ERROR] {error_msg}")
|
| 309 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": "unknown"})
|
| 310 |
results_log.append({
|
| 311 |
"Task ID": task_id,
|
| 312 |
+
"Question": question_text[:100] + "...",
|
| 313 |
+
"Submitted Answer": error_msg,
|
| 314 |
+
"Files": []
|
| 315 |
})
|
| 316 |
+
|
| 317 |
+
# 每题之间的延迟
|
| 318 |
+
if idx < len(questions_data) - 1:
|
| 319 |
+
print(f"[WAIT] Waiting before next question...")
|
| 320 |
+
time.sleep(2)
|
| 321 |
|
| 322 |
if not answers_payload:
|
| 323 |
print("Agent did not produce any answers to submit.")
|