ADD DOWNLOAD_UNIVERSAL
Browse files3 unmodified lines4567895 unmodified lines15161718192021222324252627282930313233343536373839404142434445464718 unmodified lines6667686970717273747576777879808182838468 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901913 unmodified linesimport inspectimport pandas as pdimport time# (Keep Constants as is)# --- Constants ---5 unmodified linesfrom smolagents import CodeAgent, LiteLLMModelfrom my_tools import my_tool_listdef download_file(task_id, filename, save_dir="attachments"):os.makedirs(save_dir, exist_ok=True)url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}/{filename}"save_path = os.path.join(save_dir, filename)print(f"[DEBUG] Try download: url={url} save_path={save_path}")try:resp = requests.get(url, timeout=30)print(f"[DEBUG] HTTP {resp.status_code} for {url}")resp.raise_for_status()if resp.headers.get('content-type', '').startswith('text/html'):print(f"Warning: Received HTML response, file might not exist: {filename}")return Nonewith open(save_path, "wb") as f:f.write(resp.content)print(f"Downloaded attachment for task {task_id} -> {save_path}")return save_pathexcept requests.exceptions.HTTPError as e:if e.response.status_code == 404:print(f"File not found: {filename} for task {task_id}")else:print(f"HTTP error downloading {filename}: {e}")return Noneexcept Exception as e:print(f"Attachment download failed for {task_id}/{filename}: {e}")return Noneclass BasicAgent:def __init__(self):18 unmodified lineselse:print(f"{self.agent_name} received question: {question[:80]}...")try:# system prompt + questionsystem_prompt = """You are Celum, an advanced agent skilled at using external tools and step-by-step reasoning to solve real-world problems.You may freely think, reason, and use tools or your own knowledge as needed to solve the problem.When you are ready to submit your answer,ONLY output your final answer in the exact format required by the question.DO NOT add any extra context.If the answer is a number, output only the number (no units, no commas).If the answer is a word or string, do not use articles or abbreviations, and write digits as plain numbers.If the answer is a comma-separated list, apply the same rules to each item.If you cannot answer, return the word 'unknown'."""files_prompt = ""if files:files_prompt = f"\n[You have the following attached files: {', '.join(files)}]\n"full_question = system_prompt + files_prompt + "\n\n" + questionreturn self.agent.run(full_question)except Exception as e:68 unmodified linesresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for idx, item in enumerate(questions_data[3:4]):task_id = item.get("task_id")question_text = item.get("question")file_list = item.get("files", [])print(f"[DEBUG] Q{idx+1}/{len(questions_data)} | task_id={task_id} | files={file_list}")local_files = []for fname in file_list:fpath = download_file(task_id, fname)if fpath:local_files.append(fpath)if local_files:print(f"Downloaded attachments: {local_files}")print(f"===== [Celum is answering No. {idx+1}/{len(questions_data)} ] =====")try:submitted_answer = safe_run_agent(agent, question_text, local_files, idx, len(questions_data))answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id,"Question": question_text,"Submitted Answer": submitted_answer,"Files": local_files})except Exception as e:print(f"[Celum Error at Q{idx+1}]: {e}")results_log.append({"Task ID": task_id,"Question": question_text,"Submitted Answer": f"AGENT ERROR: {e}","Files": local_files})time.sleep(10)if not answers_payload:print("Agent did not produce any answers to submit.")3 unmodified lines45678910115 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813918 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119268 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233 unmodified linesimport inspectimport pandas as pdimport timeimport mimetypesfrom pathlib import Path# (Keep Constants as is)# --- Constants ---5 unmodified linesfrom smolagents import CodeAgent, LiteLLMModelfrom my_tools import my_tool_listimport mimetypesfrom pathlib import Pathdef download_file_universal(task_id, save_dir="attachments"):"""通用文件下载,自动检测文件类型和扩展名"""os.makedirs(save_dir, exist_ok=True)url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"print(f"[DEBUG] Downloading from: {url}")try:headers = {'Accept': '*/*','User-Agent': 'Mozilla/5.0 (compatible; Agent/1.0)'}resp = requests.get(url, headers=headers, timeout=30, stream=True)print(f"[DEBUG] HTTP {resp.status_code}")print(f"[DEBUG] Content-Type: {resp.headers.get('content-type', 'Unknown')}")print(f"[DEBUG] Content-Disposition: {resp.headers.get('content-disposition', 'Unknown')}")resp.raise_for_status()# 从Content-Disposition获取原始文件名filename = Nonecontent_disp = resp.headers.get('content-disposition', '')if 'filename=' in content_disp:filename = content_disp.split('filename=')[1].strip('"\'')# 如果没有文件名,根据Content-Type推断if not filename:content_type = resp.headers.get('content-type', '').lower()ext = mimetypes.guess_extension(content_type.split(';')[0])if not ext:# 手动映射常见类型type_map = {'image/png': '.png','image/jpeg': '.jpg','image/gif': '.gif','video/mp4': '.mp4','video/avi': '.avi','video/mov': '.mov','audio/mp3': '.mp3','audio/wav': '.wav','audio/mpeg': '.mp3','application/pdf': '.pdf','text/plain': '.txt','application/json': '.json','text/csv': '.csv'}ext = type_map.get(content_type.split(';')[0], '.bin')filename = f"{task_id}{ext}"save_path = os.path.join(save_dir, filename)print(f"[DEBUG] Saving as: {save_path}")# 流式下载,适合大文件with open(save_path, "wb") as f:for chunk in resp.iter_content(chunk_size=8192):f.write(chunk)file_size = os.path.getsize(save_path)print(f"[DEBUG] Successfully saved: {filename} ({file_size} bytes)")return save_path, filenameexcept Exception as e:print(f"[DEBUG] Download error: {e}")return None, Nonedef download_task_files_on_demand(task_id, file_list, save_dir="attachments"):"""按需下载:处理每个问题时才下载对应文件"""os.makedirs(save_dir, exist_ok=True)downloaded_files = []if not file_list:print(f"[INFO] No files listed for task {task_id}, attempting direct download...")file_path, filename = download_file_universal(task_id, save_dir)if file_path:downloaded_files.append(file_path)else:print(f"[INFO] Task {task_id} has {len(file_list)} files to download")for expected_filename in file_list:# 先检查是否已经下载过potential_path = os.path.join(save_dir, expected_filename)if os.path.exists(potential_path):print(f"[CACHE] File already exists: {expected_filename}")downloaded_files.append(potential_path)continue# 下载文件file_path, actual_filename = download_file_universal(task_id, save_dir)if file_path:# 如果实际文件名与期望不符,重命名if actual_filename != expected_filename:new_path = os.path.join(save_dir, expected_filename)try:os.rename(file_path, new_path)file_path = new_pathprint(f"[INFO] Renamed {actual_filename} to {expected_filename}")except:print(f"[WARN] Could not rename file, keeping as {actual_filename}")downloaded_files.append(file_path)print(f"[SUCCESS] Downloaded: {os.path.basename(file_path)}")else:print(f"[FAIL] Could not download: {expected_filename}")# 添加小延迟避免速率限制time.sleep(0.5)return downloaded_filesclass BasicAgent:def __init__(self):18 unmodified lineselse:print(f"{self.agent_name} received question: {question[:80]}...")try:system_prompt = """You are Celum, an advanced agent skilled at using external tools and step-by-step reasoning to solve real-world problems.You may freely think, reason, and use tools or your own knowledge as needed to solve the problem.IMPORTANT OUTPUT INSTRUCTIONS:- When you need to return your final answer, use print() to output it- For example: print("Qxf7") or print("42") or print("unknown")- DO NOT just write the answer as a standalone variable- If you cannot solve the problem, use: print("unknown")Answer format requirements:- If the answer is a number, output only the number (no units, no commas)- If the answer is a word or string, do not use articles or abbreviations, and write digits as plain numbers- If the answer is a comma-separated list, apply the same rules to each item- If you cannot answer, return the word 'unknown'"""files_prompt = ""if files:files_prompt = f"\n[You have the following attached files available: {', '.join(files)}]\n"# 添加文件处理指导files_prompt += """To work with image files, you can:1. Use PIL (from PIL import Image) to load and analyze images2. Use cv2 (import cv2) for image processing3. For chess positions, you might need to analyze the board position pixel by pixel4. Consider using OCR libraries if there's text in the image"""full_question = system_prompt + files_prompt + "\n\n" + questionreturn self.agent.run(full_question)except Exception as e:68 unmodified linesresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for idx, item in enumerate(questions_data[3:4]):task_id = item.get("task_id")question_text = item.get("question")file_list = item.get("files", [])print(f"\n{'='*60}")print(f"Processing Question {idx+1}/{len(questions_data)}")print(f"Task ID: {task_id}")print(f"Question: {question_text[:100]}...")print(f"Expected files: {file_list}")print(f"{'='*60}")# 按需下载文件local_files = []if file_list or True: # 总是尝试下载,因为有些任务可能没有在file_list中列出print(f"[DOWNLOAD] Starting download for task {task_id}...")local_files = download_task_files_on_demand(task_id, file_list)if local_files:print(f"[DOWNLOAD] Successfully got {len(local_files)} files:")for f in local_files:size = os.path.getsize(f)print(f" - {os.path.basename(f)} ({size} bytes)")else:print(f"[DOWNLOAD] No files downloaded for task {task_id}")# 运行Agentprint(f"[AGENT] Running Celum on question {idx+1}...")try:submitted_answer = safe_run_agent(agent, question_text, local_files, idx, len(questions_data))answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id,"Question": question_text[:100] + "...","Submitted Answer": submitted_answer,"Files": [os.path.basename(f) for f in local_files] if local_files else []})print(f"[AGENT] Answer: {submitted_answer}")except Exception as e:error_msg = f"AGENT ERROR: {e}"print(f"[ERROR] {error_msg}")answers_payload.append({"task_id": task_id, "submitted_answer": "unknown"})results_log.append({"Task ID": task_id,"Question": question_text[:100] + "...","Submitted Answer": error_msg,"Files": []})# 每题之间的延迟if idx < len(questions_data) - 1:print(f"[WAIT] Waiting before next question...")time.sleep(2)if not answers_payload:print("Agent did not produce any answers to submit.")
app.py+175-43