Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files225 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582594 unmodified lines26426526626726826960 unmodified lines3303313323333343353363373383393403413423438 unmodified lines3523533543553563573583593603614 unmodified lines36636736836937037137237337437555 unmodified lines4314324334344354364376 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654663 unmodified lines4704714724734744754762 unmodified lines479480481482483484485562 unmodified lines1048104910501051105210531772 unmodified lines28262827282828292830283127 unmodified lines2859286028612862286328642865308 unmodified lines3174317531763177317831793180318131823183318431853186225 unmodified linestask_id: str,output_dir: str = "/tmp/gaia_files",preferred_filename: str = "",) -> str:"""Downloads a task attachment from the course API by task_id and returns the local file path.Args:task_id: Task identifier from the evaluation dataset.output_dir: Local directory where the file should be saved.preferred_filename: Optional original attachment filename from the task metadata."""import reimport timefrom urllib.parse import unquoteclean_id = (task_id or "").strip()if not clean_id:return "Error downloading file: missing task_id."safe_out_dir = (output_dir or "").strip() or "/tmp/gaia_files"os.makedirs(safe_out_dir, exist_ok=True)safe_pref_name = os.path.basename((preferred_filename or "").strip())if safe_pref_name:cached_pref_path = os.path.join(safe_out_dir, safe_pref_name)if os.path.isfile(cached_pref_path) and os.path.getsize(cached_pref_path) > 0:return cached_pref_pathbase_url = DEFAULT_API_URL.rstrip("/")candidate_urls = [f"{base_url}/files/{clean_id}",f"{base_url}/attachments/{clean_id}",]last_err = Nonefor url in candidate_urls:4 unmodified linesurl,timeout=(8.0, _tool_timeout(25.0, min_timeout=5.0)),headers={"User-Agent": "Mozilla/5.0"},)if resp.status_code in {429, 502, 503, 504} and attempt < 2:_tool_timeout(4.0, min_timeout=1.0)60 unmodified lines"application/pdf": ".pdf","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx","application/vnd.ms-excel": ".xls","image/png": ".png","image/jpeg": ".jpg","audio/mpeg": ".mp3","audio/wav": ".wav","text/x-python": ".py",}ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin"filename = f"{clean_id}{ext}"out_path = os.path.join(safe_out_dir, filename)with open(out_path, "wb") as f:8 unmodified lines@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, DOCX, PPTX, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""import reimport xml.etree.ElementTree as ETimport zipfile4 unmodified linessheets = pd.read_excel(path, sheet_name=None)if not sheets:return "Empty Excel workbook."text = "\n\n".join(f"=== Sheet: {s_name} ===\n{df.to_csv(index=False)}"for s_name, df in sheets.items())elif f_ext == ".pdf":try:from pypdf import PdfReader55 unmodified linesexcept Exception as pptx_exc:return f"Error reading PPTX '{path}': {str(pptx_exc)}"elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)."elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)."else:6 unmodified linesreturn text[:half] + "\n...\n" + text[-half:]try:if not os.path.isfile(file_path):return f"File not found: '{file_path}'"ext = os.path.splitext(file_path)[1].lower()office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"}if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(file_path)):extract_dir = os.path.join(os.path.dirname(file_path),f"extracted_{os.path.basename(file_path)}",)os.makedirs(extract_dir, exist_ok=True)base_extract = os.path.realpath(extract_dir)sections = []with zipfile.ZipFile(file_path, "r") as zf:members = [m for m in zf.namelist() if not m.endswith("/")]sections.append(f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}")for member in members:target_path = os.path.realpath(os.path.join(extract_dir, member))if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)):3 unmodified lineswith zf.open(member, "r") as src, open(target_path, "wb") as dst:dst.write(src.read())try:content_str = _read_single(target_path, max_chars=24000)sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}")except Exception as m_exc:sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}")2 unmodified linesreturn joined_zipreturn joined_zip[:24000] + "\n...\n" + joined_zip[-24000:]return _read_single(file_path, max_chars=48000)except Exception as e:return f"Error reading file '{file_path}': {str(e)}"562 unmodified linesprint(f"[IMAGE ERR] path={image_path}: {type(e).__name__}: {e}", flush=True)raise RuntimeError(f"Error inspecting image '{image_path}': {str(e)}") from e@tooldef inspect_youtube(url: str,1772 unmodified linesdownload_task_file,read_local_file,inspect_image,inspect_youtube,transcribe_audio,],27 unmodified lines"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"executor_kwargs": {"additional_functions": allowed_funcs},"max_steps": 4,"verbosity_level": 0,}308 unmodified linesprompt_lower = prompt.lower()if "chess" in prompt_lower or "algebraic notation" in prompt_lower:prompt += ("\n\nIMPORTANT for chess tasks:\n""1. Call inspect_image(image_path=..., question='List the exact board orientation (which side is at the bottom, rank 1 or rank 8), ""every single piece with its exact square (e.g., White King on g1, Black Queen on d8), whose turn it is, and the exact FEN string.').\n""2. In Python, verify the board state from that exact piece list, check all legal moves for Black (especially checks, forks, pins, and mate threats), ""and pick the winning move.\n""3. Output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, Qxd4) with NO move numbers ('1...' or '1.') and NO commentary.")if ("|*|" in prompt225 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752764 unmodified lines28128228328428528628760 unmodified lines3483493503513523533543553563573583593603613623638 unmodified lines3723733743753763773783793803813824 unmodified lines38738838939039139239339439539639739839940040140240340440540640740840941041155 unmodified lines4674684694704714724736 unmodified lines4804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115123 unmodified lines5165175185195205215222 unmodified lines525526527528529530531562 unmodified lines109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521772 unmodified lines292529262927292829292930293127 unmodified lines2959296029612962296329642965308 unmodified lines3274327532763277327832793280328132823283328432853286328732883289225 unmodified linestask_id: str,output_dir: str = "/tmp/gaia_files",preferred_filename: str = "",file_url: str = "",) -> str:"""Downloads a task attachment from the course API (or direct URL) and returns the local file path.Args:task_id: Task identifier from the evaluation dataset.output_dir: Local directory where the file should be saved.preferred_filename: Optional original attachment filename from the task metadata.file_url: Optional direct URL if mentioned in the task prompt."""import reimport timefrom urllib.parse import unquoteclean_id = (task_id or "").strip()clean_url = (file_url or "").strip()if not clean_id and not clean_url:return "Error downloading file: missing task_id and file_url."safe_out_dir = (output_dir or "").strip() or "/tmp/gaia_files"os.makedirs(safe_out_dir, exist_ok=True)safe_pref_name = os.path.basename((preferred_filename or "").strip())# Sprawdź najpierw czy plik już istnieje w output_dir lub podkatalogach roboczychsearch_names = [n for n in (safe_pref_name, f"{clean_id}.bin", clean_id) if n]for s_name in search_names:direct_cand = os.path.join(safe_out_dir, s_name)if os.path.isfile(direct_cand) and os.path.getsize(direct_cand) > 0:return direct_candif clean_id:for fname in os.listdir(safe_out_dir):f_full = os.path.join(safe_out_dir, fname)if os.path.isfile(f_full) and os.path.getsize(f_full) > 0:if fname.startswith(clean_id) or (safe_pref_name and fname == safe_pref_name):return f_fullbase_url = DEFAULT_API_URL.rstrip("/")candidate_urls = []if clean_url.startswith(("http://", "https://")):candidate_urls.append(clean_url)if clean_id:candidate_urls.extend([f"{base_url}/files/{clean_id}",f"{base_url}/attachments/{clean_id}",f"{base_url}/tasks/{clean_id}/file",])last_err = Nonefor url in candidate_urls:4 unmodified linesurl,timeout=(8.0, _tool_timeout(25.0, min_timeout=5.0)),headers={"User-Agent": "Mozilla/5.0"},allow_redirects=True,)if resp.status_code in {429, 502, 503, 504} and attempt < 2:_tool_timeout(4.0, min_timeout=1.0)60 unmodified lines"application/pdf": ".pdf","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx","application/vnd.ms-excel": ".xls","application/zip": ".zip","image/png": ".png","image/jpeg": ".jpg","image/webp": ".webp","audio/mpeg": ".mp3","audio/wav": ".wav","text/x-python": ".py",}ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin"filename = f"{clean_id or 'attachment'}{ext}"out_path = os.path.join(safe_out_dir, filename)with open(out_path, "wb") as f:8 unmodified lines@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, DOCX, PPTX, ZIP archive, CSV/JSON, or spreadsheet content from a local file.Args:file_path: Local path to the downloaded file."""import jsonimport reimport xml.etree.ElementTree as ETimport zipfile4 unmodified linessheets = pd.read_excel(path, sheet_name=None)if not sheets:return "Empty Excel workbook."parts_out = []for s_name, df in sheets.items():summary = (f"=== Sheet: {s_name} (rows={len(df)}, cols={list(df.columns)}) ===\n"f"{df.to_csv(index=False)}")parts_out.append(summary)text = "\n\n".join(parts_out)elif f_ext == ".csv":df = pd.read_csv(path)text = f"=== CSV (rows={len(df)}, cols={list(df.columns)}) ===\n{df.to_csv(index=False)}"elif f_ext == ".json":with open(path, "r", encoding="utf-8", errors="replace") as f:raw_j = f.read()try:parsed_j = json.loads(raw_j)text = json.dumps(parsed_j, ensure_ascii=False, indent=2)except Exception:text = raw_jelif f_ext == ".pdf":try:from pypdf import PdfReader55 unmodified linesexcept Exception as pptx_exc:return f"Error reading PPTX '{path}': {str(pptx_exc)}"elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...) or analyze_chessboard(image_path='{path}')."elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)."else:6 unmodified linesreturn text[:half] + "\n...\n" + text[-half:]try:resolved = file_pathif not os.path.isfile(resolved):base_name = os.path.basename(file_path or "")for cand_dir in ("/tmp/gaia_files", "."):cand_p = os.path.join(cand_dir, base_name)if base_name and os.path.isfile(cand_p):resolved = cand_pbreakif not os.path.isfile(resolved):return f"File not found: '{file_path}'"ext = os.path.splitext(resolved)[1].lower()office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"}if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(resolved)):extract_dir = os.path.join(os.path.dirname(resolved),f"extracted_{os.path.basename(resolved)}",)os.makedirs(extract_dir, exist_ok=True)base_extract = os.path.realpath(extract_dir)sections = []with zipfile.ZipFile(resolved, "r") as zf:members = [m for m in zf.namelist() if not m.endswith("/")]sections.append(f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}")per_member_cap = max(4000, min(24000, 44000 // max(1, len(members))))for member in members:target_path = os.path.realpath(os.path.join(extract_dir, member))if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)):3 unmodified lineswith zf.open(member, "r") as src, open(target_path, "wb") as dst:dst.write(src.read())try:content_str = _read_single(target_path, max_chars=per_member_cap)sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}")except Exception as m_exc:sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}")2 unmodified linesreturn joined_zipreturn joined_zip[:24000] + "\n...\n" + joined_zip[-24000:]return _read_single(resolved, max_chars=48000)except Exception as e:return f"Error reading file '{file_path}': {str(e)}"562 unmodified linesprint(f"[IMAGE ERR] path={image_path}: {type(e).__name__}: {e}", flush=True)raise RuntimeError(f"Error inspecting image '{image_path}': {str(e)}") from e@tooldef analyze_chessboard(image_path: str, side_to_move: str = "black") -> str:"""Extracts a structured chessboard position from an image and evaluates candidate legal moves for the side to move.Args:image_path: Local path to the chessboard image (.png, .jpg, .jpeg, .webp).side_to_move: Side whose turn it is ('black' or 'white')."""chess_prompt = ("Carefully examine this chessboard image rank by rank from rank 8 down to rank 1, ""and file by file from file 'a' to file 'h' (standard algebraic coordinates where a1 is White's ""leftmost square and h8 is Black's leftmost square, regardless of visual rotation—state which rank ""is at the bottom of the image).\n""List EVERY piece currently on the board with its exact square:\n""- White pieces (K, Q, R, B, N, P)\n""- Black pieces (k, q, r, b, n, p)\n""Also provide the exact FEN placement string (8 ranks separated by '/') and list all immediate ""checks, captures, forks, pins, and mating threats available to "f"{(side_to_move or 'black').upper()}, plus the best winning move in Standard Algebraic Notation (SAN).")vision_summary = inspect_image(image_path=image_path, question=chess_prompt)# Jeśli zainstalowana jest biblioteka python-chess, spróbuj zweryfikować legalne ruchy z podanego FEN-atry:import reimport chessfen_match = re.search(r"\b([rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}(?:/[rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}){7})\b",vision_summary,flags=re.IGNORECASE,)if fen_match:raw_placement = fen_match.group(1)turn_char = "b" if (side_to_move or "black").strip().lower().startswith("b") else "w"board = chess.Board(f"{raw_placement} {turn_char} - - 0 1")legal_sans = [board.san(mv) for mv in board.legal_moves]forcing_sans = [board.san(mv)for mv in board.legal_movesif board.gives_check(mv) or board.is_capture(mv)]return (f"{vision_summary}\n\n"f"[Verified FEN]: {board.fen()}\n"f"[Legal moves count]: {len(legal_sans)}\n"f"[Checks / Captures]: {', '.join(forcing_sans[:25]) or 'none'}\n"f"[All legal SANs]: {', '.join(legal_sans[:40])}")except Exception:passreturn vision_summary@tooldef inspect_youtube(url: str,1772 unmodified linesdownload_task_file,read_local_file,inspect_image,analyze_chessboard,inspect_youtube,transcribe_audio,],27 unmodified lines"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"executor_kwargs": {"additional_functions": allowed_funcs},"max_steps": 6,"verbosity_level": 0,}308 unmodified linesprompt_lower = prompt.lower()if "chess" in prompt_lower or "algebraic notation" in prompt_lower:side_hint = "white" if "white's turn" in prompt_lower or "white to move" in prompt_lower else "black"img_hint = f"'{prefetched_path}'" if "prefetched_path" in locals() and prefetched_path else "the downloaded image path"prompt += ("\n\nIMPORTANT for chess tasks:\n"f"1. Call analyze_chessboard(image_path={img_hint}, side_to_move='{side_hint}') first ""(and if needed, inspect_image with the exact piece list per square from rank 8 to rank 1, file a to h).\n"f"2. In Python, verify the board state and candidate moves for {side_hint.upper()} ""(checks, captures, forks, pins, discovered attacks, and forced mate lines), and pick the winning move.\n""3. Output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, Qxd4) ""with NO move numbers ('1...' or '1.') and NO commentary.")if ("|*|" in prompt
app.py+135-32