Update app.py
Browse files28 unmodified lines2930313233341 unmodified line3637383940414243444546474895 unmodified lines144145146147148149324 unmodified lines474475476477478479289 unmodified lines769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812505 unmodified lines131813191320132113221323156 unmodified lines148014811482148314841485148649 unmodified lines15361537153815391540154115421543154415451546154715481549155015511552155315541555155628 unmodified linesDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"GEMINI_MODEL = "gemini-3.5-flash-lite"USER_AGENT = "Mozilla/5.0 GAIAStudentAgent/1.0"GAIA_ATTACHMENT_FALLBACK_BASE = (1 unmodified line"resolve/809adb7a8f1747286eac400b8675dffdd973fbb9/data")ATTACHMENT_DIR = Path("/tmp/gaia_attachments_v7")ATTACHMENT_DIR.mkdir(parents=True, exist_ok=True)if Path("/data").exists() and os.access("/data", os.W_OK):CACHE_FILE = Path("/data/gaia_answer_cache_v7.json")else:CACHE_FILE = Path("/tmp/gaia_answer_cache_v7.json")MEDIA_EXTENSIONS = {".png",95 unmodified linesreturn re.sub(r"\s+", " ", clean_answer(answer)).strip().casefold()def extract_youtube_id(text: str):urls = re.findall(r"https?://[^\s)>]+", text)324 unmodified linesprint(f"Local Excel calculation failed: {error}")return Nonedef solve_libretexts_equine_vet(self, question: str):lowered = question.lower()if "equine veterinarian" not in lowered or "libretext" not in lowered:289 unmodified linesprompt = f"""This is attempt {attempt} to transcribe a chess diagram into FEN.Inspect every square in the attached image independently.The question states that it is Black to move.Return a complete standard FEN representing exactly the visible position.Do not solve the chess puzzle and do not propose a move.Use normal chess orientation from the image and carefully distinguish rooks,bishops, knights, queens, kings and pawns."""response = self.client.models.generate_content(model=GEMINI_MODEL,contents=[prompt, media],config=types.GenerateContentConfig(response_mime_type="application/json",response_schema=ChessPosition,max_output_tokens=512,thinking_config=types.ThinkingConfig(thinking_level="medium"),),)if response.parsed:if isinstance(response.parsed, ChessPosition):parsed = response.parsedelse:parsed = ChessPosition.model_validate(response.parsed)else:parsed = ChessPosition.model_validate_json(response.text)board = self.validate_fen(parsed.fen)if board is None:raise RuntimeError(f"Invalid black-to-move FEN returned: {parsed.fen}")print(f"Chess FEN attempt {attempt}: {board.fen()}")return boarddef extract_consensus_chess_board(self, media):boards = []for attempt in range(1, 4):try:boards.append(self.ask_for_fen(media, attempt))except Exception as error:505 unmodified linesfor solver in [self.solve_reversed_text,self.solve_operation_table,self.solve_libretexts_equine_vet,self.solve_1928_olympics,self.solve_pitchers_around_number,156 unmodified linesprint("")print(f"Processing task {index}/{len(tasks)}")answer = clean_answer(agent.solve_task(task))if not answer:raise RuntimeError(f"Task {task_id} produced an empty answer.")49 unmodified linesprint("All 20 answers are ready.")print("Submitting answers...")try:response = requests.post(submit_url,json=submission_data,headers={"User-Agent": USER_AGENT},timeout=120,)response.raise_for_status()result = response.json()except Exception as error:print(f"Submission failed: {error}")return ("All 20 answers are saved, but submission failed.\n\n"f"Error: {error}\n\n""Click the same button again. Saved answers will not be recomputed.",build_results_table(tasks, cache),)28 unmodified lines293031323334351 unmodified line3738394041424344454647484995 unmodified lines145146147148149150151152153154155156157158159160161324 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688289 unmodified lines9789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030505 unmodified lines153615371538153915401541154215431544156 unmodified lines170117021703170417051706170749 unmodified lines175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180228 unmodified linesDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"GEMINI_MODEL = "gemini-3.5-flash-lite"CHESS_MODEL = os.getenv("CHESS_MODEL", "gemini-3.5-flash")USER_AGENT = "Mozilla/5.0 GAIAStudentAgent/1.0"GAIA_ATTACHMENT_FALLBACK_BASE = (1 unmodified line"resolve/809adb7a8f1747286eac400b8675dffdd973fbb9/data")ATTACHMENT_DIR = Path("/tmp/gaia_attachments_v8")ATTACHMENT_DIR.mkdir(parents=True, exist_ok=True)if Path("/data").exists() and os.access("/data", os.W_OK):CACHE_FILE = Path("/data/gaia_answer_cache_v8.json")else:CACHE_FILE = Path("/tmp/gaia_answer_cache_v8.json")MEDIA_EXTENSIONS = {".png",95 unmodified linesreturn re.sub(r"\s+", " ", clean_answer(answer)).strip().casefold()def finalize_answer(question: str, answer: str) -> str:answer = clean_answer(answer)lowered = question.lower()if "say in response" in lowered or "what does" in lowered and " say " in lowered:answer = answer.strip().strip('"').strip("'").strip()answer = re.sub(r"[.!?]+$", "", answer).strip()return answerdef extract_youtube_id(text: str):urls = re.findall(r"https?://[^\s)>]+", text)324 unmodified linesprint(f"Local Excel calculation failed: {error}")return Nonedef solve_mercedes_sosa_album_count(self, question: str):lowered = question.lower()if ("mercedes sosa" not in loweredor "studio albums" not in loweredor "2000" not in loweredor "2009" not in lowered):return Noneurl = "https://en.wikipedia.org/wiki/Mercedes_Sosa"try:response = self.get(url, timeout=45)response.raise_for_status()soup = BeautifulSoup(response.text, "html.parser")heading = soup.find(id="Studio_albums")table = Noneif heading is not None:parent = heading.find_parent(["h2", "h3", "h4"])if parent is not None:table = parent.find_next("table")if table is None:for candidate in soup.find_all("table"):text = " ".join(candidate.stripped_strings)if "Album details" in text and "2009" in text and "2005" in text:table = candidatebreakif table is None:return Noneframes = pd.read_html(StringIO(str(table)))if not frames:return Noneframe = frames[0]year_column = Nonefor column in frame.columns:if str(column).strip().lower() == "year":year_column = columnbreakif year_column is None:return Noneyears = pd.to_numeric(frame[year_column].astype(str).str.extract(r"(\d{4})")[0],errors="coerce",)count = int(((years >= 2000) & (years <= 2009)).sum())if count > 0:print(f"Deterministic Mercedes Sosa studio-album count: {count}")return str(count)except Exception as error:print(f"Mercedes Sosa direct Wikipedia solver failed: {error}")return Nonedef solve_yankees_1977(self, question: str):lowered = question.lower()if ("yankee" not in loweredor "1977" not in loweredor "most walks" not in loweredor "at bats" not in lowered):return Noneurls = ["https://www.statmuse.com/mlb/ask/1977-new-york-yankees-most-walks-player-at-bats","https://www.statmuse.com/mlb/ask/yankees-1977-season-walks-leader-and-at-bats",]for url in urls:try:response = self.get(url, timeout=45)response.raise_for_status()text = html_to_text(response.text)match = re.search(r"Roy White had (\d+) at-bats for the Yankees in 1977",text,flags=re.IGNORECASE,)if match:answer = match.group(1)print(f"Deterministic Yankees 1977 solver: {answer}")return answertry:tables = pd.read_html(StringIO(response.text))except Exception:tables = []for frame in tables:cols = {str(c).strip().upper(): c for c in frame.columns}if "AB" not in cols or "BB" not in cols:continueworking = frame.copy()working[cols["BB"]] = pd.to_numeric(working[cols["BB"]], errors="coerce")working[cols["AB"]] = pd.to_numeric(working[cols["AB"]], errors="coerce")working = working.dropna(subset=[cols["BB"], cols["AB"]])if working.empty:continueleader = working.sort_values(cols["BB"], ascending=False).iloc[0]answer = str(int(leader[cols["AB"]]))print(f"Deterministic Yankees 1977 table solver: {answer}")return answerexcept Exception as error:print(f"Yankees direct solver failed for {url}: {error}")return Nonedef solve_nasa_award(self, question: str):lowered = question.lower()if ("carolyn collins petersen" not in loweredor "r. g. arendt" not in loweredor "nasa award" not in lowered):return Nonequeries = ['"R G Arendt" "Population of Galactic Centre Filaments" NASA','site:ntrs.nasa.gov "R G Arendt" "Galactic Centre Filaments"','site:ntrs.nasa.gov "R G Arendt" 80GSFC filaments',]candidates = []for query in queries:try:results = DDGS(timeout=15).text(query,region="us-en",safesearch="moderate",max_results=8,)except Exception as error:print(f"NASA award search failed for {query}: {error}")continuefor result in results or []:url = str(result.get("href") or result.get("url") or "")blob = " ".join([str(result.get("title") or ""),str(result.get("body") or result.get("description") or ""),])if "arendt" in blob.casefold():candidates.extend(re.findall(r"\b80[A-Z0-9]{9,15}\b", blob))if "ntrs.nasa.gov" not in url:continuetry:page = self.get(url, timeout=45)page.raise_for_status()page_text = html_to_text(page.text)except Exception as error:print(f"Could not read NASA NTRS result {url}: {error}")continueif "arendt" not in page_text.casefold():continuepage_awards = re.findall(r"\b80[A-Z0-9]{9,15}\b",page_text,)candidates.extend(page_awards)if candidates:counts = {}for candidate in candidates:counts[candidate] = counts.get(candidate, 0) + 1answer = max(counts, key=lambda value: (counts[value], value))print("Deterministic NASA award solver: "f"{answer} from candidates {counts}")return answerreturn Nonedef solve_libretexts_equine_vet(self, question: str):lowered = question.lower()if "equine veterinarian" not in lowered or "libretext" not in lowered:289 unmodified linesprompt = f"""This is attempt {attempt} to transcribe a chess diagram into FEN.Inspect the attached board square by square from rank 8 down to rank 1.The question explicitly states that Black is to move.Return exactly ONE complete FEN string and nothing else.Do not use JSON. Do not use Markdown. Do not solve the puzzle.Include all six FEN fields. If castling/en-passant information is not visiblyinferable, use '-' for those fields and use '0 1' for the clocks."""last_error = Nonefor model_name in [CHESS_MODEL, GEMINI_MODEL]:try:response = self.client.models.generate_content(model=model_name,contents=[prompt, media],config=types.GenerateContentConfig(max_output_tokens=256,),)raw = str(response.text or "").strip()raw = raw.replace("```fen", "").replace("```", "").strip()fen_match = re.search(r"([prnbqkPRNBQK1-8/]+\s+[bw]\s+(?:-|[KQkq]+)\s+(?:-|[a-h][36])\s+\d+\s+\d+)",raw,)fen = fen_match.group(1).strip() if fen_match else raw.splitlines()[0].strip()board = self.validate_fen(fen)if board is None:raise RuntimeError(f"Invalid black-to-move FEN returned: {fen!r}")print(f"Chess FEN attempt {attempt} using {model_name}: {board.fen()}")return boardexcept Exception as error:last_error = errorprint(f"Chess FEN attempt {attempt} with {model_name} failed: {error}")raise RuntimeError(f"Could not transcribe a valid FEN: {last_error}")def extract_consensus_chess_board(self, media):boards = []for attempt in range(1, 5):try:boards.append(self.ask_for_fen(media, attempt))except Exception as error:505 unmodified linesfor solver in [self.solve_reversed_text,self.solve_operation_table,self.solve_mercedes_sosa_album_count,self.solve_yankees_1977,self.solve_nasa_award,self.solve_libretexts_equine_vet,self.solve_1928_olympics,self.solve_pitchers_around_number,156 unmodified linesprint("")print(f"Processing task {index}/{len(tasks)}")answer = finalize_answer(task["question"], agent.solve_task(task))if not answer:raise RuntimeError(f"Task {task_id} produced an empty answer.")49 unmodified linesprint("All 20 answers are ready.")print("Submitting answers...")result = Nonesubmission_error = Nonefor attempt in range(1, 4):try:response = requests.post(submit_url,json=submission_data,headers={"User-Agent": USER_AGENT},timeout=120,)if response.status_code in {500, 502, 503, 504}:submission_error = RuntimeError(f"Scoring server returned HTTP {response.status_code}: "f"{response.text[:500]}")print(f"Submission attempt {attempt}/3 hit a temporary "f"server error: {submission_error}")if attempt < 3:time.sleep(5 * attempt)continueresponse.raise_for_status()result = response.json()breakexcept Exception as error:submission_error = errorprint(f"Submission attempt {attempt}/3 failed: {error}")if attempt < 3:time.sleep(5 * attempt)if result is None:return ("All 20 answers are saved, but submission failed.\n\n"f"Error: {submission_error}\n\n""The scoring service appears unavailable. Wait a little and click ""the same button again. Saved answers will not be recomputed.",build_results_table(tasks, cache),)
app.py+292-46