Spaces:
Runtime error
Runtime error
Update app.py
Browse files243 unmodified lines244245246247248249250119 unmodified lines3703713723733743757 unmodified lines38338438538638738838939039139239339439539639739839940040140240376 unmodified lines480481482483484485486487488489490491492493404 unmodified lines898899900901902903217 unmodified lines112111221123112411251126112711281129369 unmodified lines1499150015011502150315041505150615071508150915101511474 unmodified lines19861987198819891990199119921993116 unmodified lines2110211121122113211421152116777 unmodified lines2894289528962897289828992900239 unmodified lines31403141314231433144314574 unmodified lines32203221322232233224322532263227107 unmodified lines33353336333733383339334034 unmodified lines33753376337733783379338033813382226 unmodified lines36093610361136123613361436153616361736183619188 unmodified lines3808380938103811381238133814243 unmodified linesif 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())119 unmodified linesself._download_task_file = download_task_file@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, DOCX, PPTX, ZIP archive, CSV/JSON, or spreadsheet content from a local file.7 unmodified linesdef _read_single(path: str, max_chars: int) -> str:f_ext = os.path.splitext(path)[1].lower()if f_ext in {".xlsx", ".xlsm", ".xls"}:sheets = 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()76 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}'"404 unmodified linesimport iotry:if not os.path.isfile(image_path):return f"Image file not found: '{image_path}'"217 unmodified linesimport 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)369 unmodified linesquestion: Specific transcription or analysis instruction for the audio."""try:resolved_path = audio_pathif not os.path.isfile(resolved_path):target_name = os.path.basename(audio_path)for root, _, files in os.walk("."):if target_name in files:resolved_path = os.path.join(root, target_name)breakif not os.path.isfile(resolved_path):return f"Audio file not found: '{audio_path}'"474 unmodified lineselse:hard_timeout = req_timeout + 3.0call_kwargs["timeout"] = req_timeoutlitellm.request_timeout = req_timeouthard_timeout = req_timeout + 3.0role_map = {"tool-call": "assistant",116 unmodified linesraisefinally:executor.shutdown(wait=False, cancel_futures=True)print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethod777 unmodified lines"os": os,"posixpath": posixpath,"repr": repr,}accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)agent_kwargs = {"tools": [239 unmodified linesdeadline = time.monotonic() + 185.0self._local_state.deadline = deadlineself._task_deadline = deadlinetry:74 unmodified linesif ext in {".xlsx", ".xlsm", ".xls", ".csv"}:prompt += (f"\n\nTask ID: {task_id}. The tabular attachment is saved at '{prefetched_path}'. "f"Use pandas (`pd.read_excel('{prefetched_path}', sheet_name=None)` or `pd.read_csv('{prefetched_path}')`) ""to inspect exact sheet names, columns, and compute exact totals/filters.")read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file")if read_fn is not None:107 unmodified linesbackoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()rate_limited_providers = set()34 unmodified linesbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 7 if rem_now > 60.0 else (5 if rem_now > 25.0 else 4)result = run_agent.run(prompt)raw_result = "" if result is None else str(result).strip()if raw_result.lower().startswith("error in generating"):raise RuntimeError(raw_result)cleaned = self._clean_exact_match_answer(raw_result)226 unmodified linestime.sleep(min(12.0, max(3.0, rem_after_pass - 15.0)))continuebreakfinally:local_state = getattr(self, "_local_state", None)if local_state is not None:try:local_state.deadline = Noneexcept Exception:passself._task_deadline = None188 unmodified linesfor idx, item in enumerate(questions_data):task_id = item.get("task_id")question_text = item.get("question")file_name = str(item.get("file_name") or "").strip()if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continue243 unmodified lines244245246247248249250251119 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334347 unmodified lines44244344444544644744844976 unmodified lines526527528529530531532404 unmodified lines937938939940941942943217 unmodified lines11611162116311641165116611671168369 unmodified lines1538153915401541154215431544474 unmodified lines201920202021202220232024116 unmodified lines214121422143214421452146777 unmodified lines292429252926292729282929293029312932239 unmodified lines317231733174317531763177317874 unmodified lines3253325432553256325732583259326032613262326332643265107 unmodified lines337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734 unmodified lines3462346334643465346634673468346934703471347234733474347534763477226 unmodified lines37043705370637073708370937103711371237133714371537163717371837193720188 unmodified lines390939103911391239133914391539163917391839193920243 unmodified linesif not clean_id and not clean_url:return "Error downloading file: missing task_id and file_url."base_dir = (output_dir or "").strip() or "/tmp/gaia_files"safe_out_dir = os.path.join(base_dir, clean_id) if clean_id else base_diros.makedirs(safe_out_dir, exist_ok=True)safe_pref_name = os.path.basename((preferred_filename or "").strip())119 unmodified linesself._download_task_file = download_task_filedef _resolve_attachment_path(raw_path: str) -> str:if not raw_path:return raw_pathcleaned = str(raw_path).strip().strip("'\"")if os.path.isfile(cleaned):return cleanedbase_name = os.path.basename(cleaned)if not base_name:return cleanedlocal_state = getattr(self, "_local_state", None)cur_tid = getattr(local_state, "task_id", "") if local_state is not None else ""if cur_tid:task_dir = os.path.join("/tmp/gaia_files", cur_tid)if os.path.isdir(task_dir):direct_tid = os.path.join(task_dir, base_name)if os.path.isfile(direct_tid):return direct_tidfor root, _, files in os.walk(task_dir):if base_name in files:cand = os.path.join(root, base_name)if os.path.isfile(cand):return candfor search_root in ("/tmp/gaia_files", "."):if not os.path.isdir(search_root):continuedirect = os.path.join(search_root, base_name)if os.path.isfile(direct):return directfor root, dirs, files in os.walk(search_root):dirs[:] = [d for d in dirs if d not in {".git", "__pycache__", "venv", ".venv", "node_modules"}]if base_name in files:cand = os.path.join(root, base_name)if os.path.isfile(cand):return candreturn cleaneddef inspect_spreadsheet(file_path: str) -> str:"""Dumps all sheets of an Excel/CSV file with row indices and raw cell values."""ext = os.path.splitext(file_path)[1].lower()if ext == ".csv":sheets = {"CSV": pd.read_csv(file_path, header=None)}else:sheets = pd.read_excel(file_path, sheet_name=None, header=None)out_lines = []for s_name, raw_df in sheets.items():out_lines.append(f"=== Sheet: {s_name} (shape={raw_df.shape}) ===")for r_idx, row in raw_df.iterrows():vals = [f"[{c_idx}]={repr(v)}"for c_idx, v in enumerate(row.tolist())if pd.notna(v) and str(v).strip() != ""]if vals:out_lines.append(f"Row {r_idx}: " + " | ".join(vals))return "\n".join(out_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.7 unmodified linesdef _read_single(path: str, max_chars: int) -> str:f_ext = os.path.splitext(path)[1].lower()if f_ext in {".xlsx", ".xlsm", ".xls", ".csv"}:text = inspect_spreadsheet(path) or "Empty spreadsheet."elif f_ext == ".json":with open(path, "r", encoding="utf-8", errors="replace") as f:raw_j = f.read()76 unmodified linesreturn text[:half] + "\n...\n" + text[-half:]try:resolved = _resolve_attachment_path(file_path)if not os.path.isfile(resolved):return f"File not found: '{file_path}'"404 unmodified linesimport iotry:image_path = _resolve_attachment_path(image_path)if not os.path.isfile(image_path):return f"Image file not found: '{image_path}'"217 unmodified linesimport chessfen_match = re.search(r"\b([rnbqkpRNBQKP1-8]{1,8}(?:/[rnbqkpRNBQKP1-8]{1,8}){7})\b",vision_summary,)if fen_match:raw_placement = fen_match.group(1)369 unmodified linesquestion: Specific transcription or analysis instruction for the audio."""try:resolved_path = _resolve_attachment_path(audio_path)if not os.path.isfile(resolved_path):return f"Audio file not found: '{audio_path}'"474 unmodified lineselse:hard_timeout = req_timeout + 3.0call_kwargs["timeout"] = req_timeoutrole_map = {"tool-call": "assistant",116 unmodified linesraisefinally:executor.shutdown(wait=False, cancel_futures=True)@classmethod777 unmodified lines"os": os,"posixpath": posixpath,"repr": repr,"inspect_spreadsheet": inspect_spreadsheet,}accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)agent_kwargs = {"tools": [239 unmodified linesdeadline = time.monotonic() + 185.0self._local_state.deadline = deadlineself._local_state.task_id = (task_id or "").strip()self._task_deadline = deadlinetry:74 unmodified linesif ext in {".xlsx", ".xlsm", ".xls", ".csv"}:prompt += (f"\n\nTask ID: {task_id}. The tabular attachment is saved at '{prefetched_path}'. ""CRITICAL RULES FOR EXCEL/CSV:\n""1. First inspect raw rows with `inspect_spreadsheet(file_path)` or `pd.read_excel(..., sheet_name=None, header=None)` ""so you see exact header rows, footers/Total rows, and categories.\n""2. Do NOT sum a 'Total' summary row together with line items.\n""3. Before summing numeric/currency columns, ALWAYS clean strings with: ""`pd.to_numeric(col.astype(str).str.replace(r'[^0-9.-]', '', regex=True), errors='coerce').fillna(0)`.\n""4. Apply any category exclusions carefully and format decimals exactly as requested (e.g., `f'{total:.2f}'`).")read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file")if read_fn is not None:107 unmodified linesbackoff_rounds = 0global_collected_obs = []last_draft_result = ""def _harvest_agent_memory(agent_obj) -> None:if agent_obj is None:returnmem_steps = getattr(getattr(agent_obj, "memory", None), "steps", None) or []for st in mem_steps:for attr_name in ("observations", "action_output", "model_output"):val = getattr(st, attr_name, None)if val is None:continuetxt = "\n".join(str(x) for x in val) if isinstance(val, list) else str(val)txt = txt.strip()if (txtand "Invalid non-code output" not in txtand "No Python code block produced" not in txtand len(txt) > 10):snippet = txt[:4500]if snippet not in global_collected_obs:global_collected_obs.append(snippet)def _run_emergency_fallback() -> str:evidence_parts = list(global_collected_obs[-5:])if last_draft_result and "max steps" not in last_draft_result.lower():evidence_parts.append(f"Agent partial draft: {last_draft_result[:1500]}")evidence_blob = "\n---\n".join(evidence_parts).strip()fallback_candidates = [m for m in all_candidatesif m not in self._dead_modelsand (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providersand self._get_api_key(m)]for fb_model in fallback_candidates[:3]:hard_fb_deadline = max(deadline + 12.0, time.monotonic() + 10.0)ans = self._direct_extract_answer(model_name=fb_model,question=question.strip(),evidence=evidence_blob[:12000] if evidence_blob else "(No tool output collected; answer from general knowledge.)",deadline=hard_fb_deadline,)if ans:print(f"[EMERGENCY FALLBACK OK] task_id={task_id} model={fb_model} ans={ans!r}", flush=True)return ansreturn ""while time.monotonic() < deadline:rate_limited_models = set()rate_limited_providers = set()34 unmodified linesbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 7 if rem_now > 60.0 else (5 if rem_now > 25.0 else 4)result = Nonetry:result = run_agent.run(prompt)finally:# Zbieramy obserwacje z kroków agenta nawet przy wyjątku_harvest_agent_memory(run_agent)raw_result = "" if result is None else str(result).strip()if raw_result:last_draft_result = raw_resultif raw_result.lower().startswith("error in generating"):raise RuntimeError(raw_result)cleaned = self._clean_exact_match_answer(raw_result)226 unmodified linestime.sleep(min(12.0, max(3.0, rem_after_pass - 15.0)))continuebreakemergency_ans = _run_emergency_fallback()if emergency_ans:return emergency_ansfinally:local_state = getattr(self, "_local_state", None)if local_state is not None:try:local_state.deadline = Nonelocal_state.task_id = ""except Exception:passself._task_deadline = None188 unmodified linesfor idx, item in enumerate(questions_data):task_id = item.get("task_id")question_text = item.get("question")file_name = str(item.get("file_name")or item.get("filename")or item.get("file")or "").strip()if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continue
app.py+146-40