Update app.py
Browse files29 unmodified lines3031323334353632 unmodified lines69707172737475767730 unmodified lines10810911011111211311411511611711811912012112212 unmodified lines1351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741 unmodified line17617717817918018118218318421 unmodified lines20620720820921021124 unmodified lines23623723823924024124224324424526 unmodified lines27227327427527627727827928028128228376 unmodified lines36036136236336436536636736836937037137237337437560 unmodified lines436437438439440441442443142 unmodified lines58658758858959059143 unmodified lines63563663763863964064164264314 unmodified lines65865966066166266325 unmodified lines6896906916926936945 unmodified lines7007017027037047057064 unmodified lines71171271371471571671771871972072172272372412 unmodified lines7377387397407417427437447457467477487493 unmodified lines75375475575675775875976076176276376476576676776876977077177277377477577677710 unmodified lines7887897907917927937947 unmodified lines8028038048058068078085 unmodified lines8148158168178188198208218228238248258268278285 unmodified lines83483583683783883984084120 unmodified lines86286386486586686786886987087187287387487587687726 unmodified lines9049059069079089099103 unmodified lines9149159169179189199209219222 unmodified lines9259269279289299309319329339346 unmodified lines94194294394494594694794894913 unmodified lines96396496596696796896997031 unmodified lines100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510366 unmodified lines104310441045104610471048104918 unmodified lines10681069107010711072107320 unmodified lines10941095109610971098109911001101110211031104110511061107110811091110111111121113111411159 unmodified lines11251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115112 unmodified lines116411651166116711681169117010 unmodified lines118111821183118411851186118713 unmodified lines12011202120312041205120612075 unmodified lines12131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112522 unmodified lines1255125612571258125912601261126212631264126512661267126812698 unmodified lines12781279128012811282128312841285128612871288128924 unmodified lines13141315131613171318131913201321132213231324132513265 unmodified lines1332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814 unmodified lines142314241425142614271428142914309 unmodified lines1440144114421443144414451446144729 unmodified linesATTACHMENT_DIR = Path("/tmp/gaia_attachments")ATTACHMENT_DIR.mkdir(parents=True, exist_ok=True)CACHE_FILE = Path("/tmp/gaia_answer_cache.json")MEDIA_EXTENSIONS = {".png",32 unmodified linesreturn dataexcept Exception as error:print(f"Could not load cache: {error}")return {}30 unmodified linesanswer = answer[len(prefix):].strip()breakif (answer.startswith("```")and answer.endswith("```")):answer = answer[3:-3].strip()first_line, separator, remainder = (answer.partition("\n"))if (separator12 unmodified linesclass BasicAgent:def __init__(self):api_key = os.getenv("GEMINI_API_KEY")if not api_key:raise RuntimeError("GEMINI_API_KEY secret ""is not configured.")self.client = genai.Client(api_key=api_key,http_options=types.HttpOptions(retry_options=types.HttpRetryOptions(attempts=5,initial_delay=2.0,exp_base=2.0,max_delay=30.0,jitter=1.0,http_status_codes=[408,500,502,503,504,],)),)print(f"BasicAgent initialized "f"with {GEMINI_MODEL}.")def download_attachment(1 unmodified linetask_id: str,file_name: str,) -> Path:safe_name = os.path.basename(file_name)if not safe_name:raise RuntimeError(21 unmodified linesf"{task_id}")try:print("Trying official attachment "24 unmodified linesreturn destinationexcept Exception as official_error:print("Official attachment download "f"failed: {official_error}")fallback_url = (26 unmodified lines.lower())if ("text/html" in content_typeand Path(safe_name).suffix.lower()in MEDIA_EXTENSIONS):raise RuntimeError("Fallback returned HTML "76 unmodified linesformula_cell = (ws_formula.cell(row=row_number,column=column_number,))value_cell = (ws_value.cell(row=row_number,column=column_number,))60 unmodified linesif len(text) > 70000:text = (text[:70000]+ "\n"+ "[WORKBOOK TRUNCATED]")return text142 unmodified lines"",))else:page_text = str(page or ""43 unmodified linesFor every task:- solve only the task associated with that task_id- use the supplied research and attachment information- verify calculations and factual claims- ignore irrelevant or misleading web results- use code execution when it improves accuracy- preserve canonical capitalization and spelling- obey the requested answer format exactly14 unmodified linesFor numerical answers, return only the requested numericalformat unless units are explicitly requested."""def solve_text_batch(25 unmodified linessections.append(f"""================ TASK {index} ================TASK_ID:{task["task_id"]}5 unmodified linesWEB RESEARCH:{research}===============================================""")4 unmodified linesDo not merge tasks.Do not omit a task.Do not change TASK_ID values.{''.join(sections)}"""print("Calling "f"{GEMINI_MODEL} for "f"{len(tasks)} text tasks ""in one request...")12 unmodified linesthinking_level="medium"),tools=[types.Tool(code_execution=types.ToolCodeExecution)],response_mime_type="application/json",response_schema=3 unmodified lines)if response.parsed:parsed = response.parsedif isinstance(parsed,BatchAnswers,):batch = parsedelse:batch = (BatchAnswers.model_validate(parsed))else:if not response.text:raise RuntimeError("Gemini returned ""an empty batch response.")batch = (10 unmodified linesanswers = {}for item in batch.answers:if item.task_id not in expected_ids:continuecleaned = clean_answer(7 unmodified linesmissing = (expected_ids- set(answers.keys()))if missing:5 unmodified lines))return answersdef solve_media_task(self,task: dict,) -> str:task_id = task["task_id"]question = task["question"]file_name = task["file_name"]path = self.download_attachment(task_id,5 unmodified linesf"{file_name}")media = self.client.files.upload(file=str(path))print(20 unmodified linesWEB RESEARCH:{research}Inspect the actual media carefully.Solve the question and return only the requested exactanswer in the structured answer field."""print("Calling "f"{GEMINI_MODEL} "f"for media task {task_id}...")response = (26 unmodified linesresponse.parsed,AnswerItem,):parsed = response.parsedelse:parsed = (AnswerItem.model_validate(3 unmodified lineselse:if not response.text:raise RuntimeError("Gemini returned ""an empty media response.")parsed = (2 unmodified lines))if parsed.task_id != task_id:raise RuntimeError("Gemini returned the wrong "f"task ID: {parsed.task_id}")answer = clean_answer(6 unmodified lines"an empty answer.")return answerdef run_and_submit_all(profile: gr.OAuthProfile | None,):13 unmodified linesif not space_id:return ("SPACE_ID environment variable ""is missing.",None,)31 unmodified linesNone,)try:agent = BasicAgent()except Exception as error:return (f"Could not initialize agent: "f"{error}",None,)cache = load_cache()valid_ids = {item.get("task_id")for item in questions_dataif item.get("task_id")}cache = {task_id: answerfor task_id, answerin cache.items()if task_id in valid_ids}save_cache(cache)tasks = []for item in questions_data:6 unmodified lines)file_name = (item.get("file_name")or "")18 unmodified lines})pending = [taskfor task in tasks20 unmodified linesmedia_tasks = []for task in pending:suffix = (Path(task["file_name"]).suffix.lower()if task["file_name"]else "")if (task["file_name"]and suffixin MEDIA_EXTENSIONS):media_tasks.append(task)else:text_tasks.append(task9 unmodified lines// TEXT_BATCH_SIZE)for batch_index in range(0,len(text_tasks),TEXT_BATCH_SIZE,):batch = text_tasks[batch_index:batch_index+ TEXT_BATCH_SIZE]current_number = (batch_index// TEXT_BATCH_SIZE+ 1)print("")print("Processing text batch "f"{current_number}/"f"{total_text_batches}")12 unmodified linesprint(f"Cached answer for "f"{task_id}: {answer}")save_cache(10 unmodified lines):print("")print("Processing media task "f"{index}/"f"{len(media_tasks)}")13 unmodified lines)print("Cached media answer for "f"{task['task_id']}: "f"{answer}")5 unmodified linesf"{error}")results_log = []for task in tasks:task_id = task["task_id"]results_log.append({"Task ID":task_id,"Question":task["question"],"File":task["file_name"],"Answer":cache.get(task_id,"",),"Status":("CACHED"if task_idin cacheelse "PENDING"),})return (("Evaluation paused. "2 unmodified linesf"{len(cache)}/"f"{len(tasks)}\n"f"Remaining: "f"{len(tasks) - len(cache)}\n\n"f"Error: "f"{type(error).__name__}: "f"{error}\n\n""Click the run button again ""to resume from the cached answers."),pd.DataFrame(results_log),)8 unmodified linesreturn (("Evaluation is incomplete. ""Nothing was submitted.\n"f"Cached: "f"{len(cache)}/"f"{len(tasks)}"),None,)answers_payload = [24 unmodified linesprint("")print("All answers are ready.")print(f"Submitting "f"{len(answers_payload)} ""answers...")try:5 unmodified linesresponse.raise_for_status()result = response.json()except Exception as error:results_log = []for task in tasks:task_id = (task["task_id"])results_log.append({"Task ID":task_id,"Question":task["question"],"File":task["file_name"],"Answer":cache[task_id],"Status":"READY",})return (("All 20 answers are cached, ""but submission failed.\n\n"f"Error: {error}\n\n""Click the button again. ""The model will NOT recompute ""the cached answers."),pd.DataFrame(results_log),)results_log = []for task in tasks:task_id = task["task_id"]results_log.append({"Task ID":task_id,"Question":task["question"],"File":task["file_name"],"Submitted Answer":cache[task_id],})final_status = ("Submission Successful!\n"f"User: "14 unmodified linesreturn (final_status,pd.DataFrame(results_log),)9 unmodified lines1. Log in to your Hugging Face account.2. Click **Run / Resume Evaluation & Submit All Answers**.3. Completed answers are cached in the running Space. If a temporary API or quota error occurs, click the same button again to continue from the remaining questions.4. Answers are submitted only after all 20 questions are ready.""")29 unmodified lines3031323334353632 unmodified lines6970717273747530 unmodified lines10610710810911011111211311411512 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631 unmodified line16516616716816917017121 unmodified lines19319419519619719819920024 unmodified lines22522622722822923023123223323423523623723826 unmodified lines26526626726826927027127227327427527627776 unmodified lines35435535635735835936036136236336436536636760 unmodified lines428429430431432433434142 unmodified lines57757857958058158258343 unmodified lines62762862963063163263363463563663714 unmodified lines65265365465565665765865966025 unmodified lines6866876886896906916925 unmodified lines6986997007017027037044 unmodified lines70971071171271371471571671771871972072172272312 unmodified lines7367377387397407413 unmodified lines74574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178210 unmodified lines7937947957967977987998008018027 unmodified lines8108118128138148158168178185 unmodified lines8248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568575 unmodified lines86386486586686786886987087187220 unmodified lines89389489589689789889990090190290390490590690790890991091191291391491591691726 unmodified lines9449459469479489499509519529533 unmodified lines9579589599609619629639649659669679689699709719729739749759769779789792 unmodified lines9829839849859869879889899909919929939949956 unmodified lines10021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106113 unmodified lines1075107610771078107910801081108231 unmodified lines1114111511161117111811196 unmodified lines11261127112811291130113111321133113418 unmodified lines115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118620 unmodified lines1207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212339 unmodified lines12431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912 unmodified lines1282128312841285128612871288128910 unmodified lines130013011302130313041305130613 unmodified lines132013211322132313241325132613275 unmodified lines1333133413351336133713382 unmodified lines13411342134313441345134613471348134913501351135213531354135513561357135813598 unmodified lines136813691370137113721373137413751376137713781379138013811382138324 unmodified lines14081409141014111412141314141415141614171418141914205 unmodified lines14261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814 unmodified lines1473147414751476147714781479148014819 unmodified lines14911492149314941495149614971498149929 unmodified linesATTACHMENT_DIR = Path("/tmp/gaia_attachments")ATTACHMENT_DIR.mkdir(parents=True, exist_ok=True)CACHE_FILE = Path("/tmp/gaia_answer_cache_v3.json")MEDIA_EXTENSIONS = {".png",32 unmodified linesreturn dataexcept Exception as error:print(f"Could not load cache: {error}")return {}30 unmodified linesanswer = answer[len(prefix):].strip()breakif answer.startswith("```") and answer.endswith("```"):answer = answer[3:-3].strip()first_line, separator, remainder = answer.partition("\n")if (separator12 unmodified linesclass BasicAgent:def __init__(self):api_key = os.getenv("GEMINI_API_KEY")if not api_key:raise RuntimeError("GEMINI_API_KEY secret is not configured.")self.client = genai.Client(api_key=api_key,http_options=types.HttpOptions(retry_options=types.HttpRetryOptions(attempts=5,initial_delay=2.0,exp_base=2.0,max_delay=30.0,jitter=1.0,http_status_codes=[408,500,502,503,504,],)),)print(f"BasicAgent initialized with "f"{GEMINI_MODEL}.")def download_attachment(1 unmodified linetask_id: str,file_name: str,) -> Path:safe_name = os.path.basename(file_name)if not safe_name:raise RuntimeError(21 unmodified linesf"{task_id}")official_error = Nonetry:print("Trying official attachment "24 unmodified linesreturn destinationexcept Exception as error:official_error = errorprint("Official attachment download "f"failed: "f"{type(error).__name__}: "f"{error}")fallback_url = (26 unmodified lines.lower())suffix = Path(safe_name).suffix.lower()if ("text/html" in content_typeand suffix in MEDIA_EXTENSIONS):raise RuntimeError("Fallback returned HTML "76 unmodified linesformula_cell = (ws_formula.cell(row=row_number,column=column_number,))value_cell = (ws_value.cell(row=row_number,column=column_number,))60 unmodified linesif len(text) > 70000:text = (text[:70000]+ "\n[WORKBOOK TRUNCATED]")return text142 unmodified lines"",))else:page_text = str(page or ""43 unmodified linesFor every task:- solve only the task associated with that task_id- use the supplied research and attachment information- verify calculations and factual claims carefully- reason through supplied Python code exactly when needed- perform arithmetic and counting carefully- inspect spreadsheet values and formulas carefully- ignore irrelevant or misleading web results- preserve canonical capitalization and spelling- obey the requested answer format exactly14 unmodified linesFor numerical answers, return only the requested numericalformat unless units are explicitly requested.Before returning each answer, internally check that theanswer corresponds to the correct task_id."""def solve_text_batch(25 unmodified linessections.append(f"""================ TASK {index} ================TASK_ID:{task["task_id"]}5 unmodified linesWEB RESEARCH:{research}================ END TASK {index} ================""")4 unmodified linesDo not merge tasks.Do not omit a task.Do not alter any TASK_ID.Treat each task independently.Carefully check exact answer formatting before returning.{''.join(sections)}"""print(f"Calling {GEMINI_MODEL} for "f"{len(tasks)} text tasks ""in one request...")12 unmodified linesthinking_level="medium"),response_mime_type="application/json",response_schema=3 unmodified lines)if response.parsed:if isinstance(response.parsed,BatchAnswers,):batch = response.parsedelse:batch = (BatchAnswers.model_validate(response.parsed))else:if not response.text:finish_reason = "UNKNOWN"try:finish_reason = str(response.candidates[0].finish_reason)except Exception:passraise RuntimeError("Gemini returned an empty ""batch response. "f"Finish reason: "f"{finish_reason}")batch = (10 unmodified linesanswers = {}for item in batch.answers:if (item.task_idnot in expected_ids):continuecleaned = clean_answer(7 unmodified linesmissing = (expected_ids- set(answers.keys()))if missing:5 unmodified lines))for task in tasks:task_id = task["task_id"]print(f"Batch answer "f"{task_id}: "f"{answers[task_id]}")return answersdef solve_media_task(self,task: dict,) -> str:task_id = task["task_id"]question = task["question"]file_name = task["file_name"]path = self.download_attachment(task_id,5 unmodified linesf"{file_name}")media = (self.client.files.upload(file=str(path)))print(20 unmodified linesWEB RESEARCH:{research}Inspect the actual attached media carefully.For an image, analyze the image itself rather than relyingonly on web research.For chess, reconstruct the board and obey the requestedchess notation exactly.For audio, listen to the actual recording carefully and usewhat is spoken in the recording.Return only the requested exact answer in the structuredanswer field."""print(f"Calling {GEMINI_MODEL} "f"for media task "f"{task_id}...")response = (26 unmodified linesresponse.parsed,AnswerItem,):parsed = (response.parsed)else:parsed = (AnswerItem.model_validate(3 unmodified lineselse:if not response.text:finish_reason = "UNKNOWN"try:finish_reason = str(response.candidates[0].finish_reason)except Exception:passraise RuntimeError("Gemini returned an empty ""media response. "f"Finish reason: "f"{finish_reason}")parsed = (2 unmodified lines))if (parsed.task_id!= task_id):raise RuntimeError("Gemini returned the wrong "f"task ID: "f"{parsed.task_id}")answer = clean_answer(6 unmodified lines"an empty answer.")print(f"Media answer "f"{task_id}: "f"{answer}")return answerdef build_results_table(tasks: list[dict],cache: dict,) -> pd.DataFrame:rows = []for task in tasks:task_id = task["task_id"]if task_id in cache:status = "READY"answer = cache[task_id]else:status = "PENDING"answer = ""rows.append({"Task ID":task_id,"Question":task["question"],"File":task["file_name"],"Answer":answer,"Status":status,})return pd.DataFrame(rows)def run_and_submit_all(profile: gr.OAuthProfile | None,):13 unmodified linesif not space_id:return ("SPACE_ID environment ""variable is missing.",None,)31 unmodified linesNone,)tasks = []for item in questions_data:6 unmodified lines)file_name = (item.get("file_name")or "")18 unmodified lines})try:agent = BasicAgent()except Exception as error:return (f"Could not initialize "f"agent: {error}",None,)cache = load_cache()valid_ids = {task["task_id"]for task in tasks}cache = {task_id: answerfor task_id, answerin cache.items()if task_id in valid_ids}save_cache(cache)pending = [taskfor task in tasks20 unmodified linesmedia_tasks = []for task in pending:file_name = task["file_name"]suffix = (Path(file_name).suffix.lower()if file_nameelse "")if (file_nameand suffixin MEDIA_EXTENSIONS):media_tasks.append(task)else:text_tasks.append(task9 unmodified lines// TEXT_BATCH_SIZE)for batch_start in range(0,len(text_tasks),TEXT_BATCH_SIZE,):batch = text_tasks[batch_start:batch_start+ TEXT_BATCH_SIZE]batch_number = (batch_start// TEXT_BATCH_SIZE+ 1)print("")print(f"Processing text batch "f"{batch_number}/"f"{total_text_batches}")12 unmodified linesprint(f"Cached answer for "f"{task_id}: "f"{answer}")save_cache(10 unmodified lines):print("")print(f"Processing media task "f"{index}/"f"{len(media_tasks)}")13 unmodified lines)print("Cached media answer "f"for "f"{task['task_id']}: "f"{answer}")5 unmodified linesf"{error}")return (("Evaluation paused. "2 unmodified linesf"{len(cache)}/"f"{len(tasks)}\n"f"Remaining: "f"{len(tasks) - len(cache)}""\n\n"f"Error: "f"{type(error).__name__}: "f"{error}""\n\n""Click the same button ""again to resume from ""the saved answers."),build_results_table(tasks,cache,),)8 unmodified linesreturn (("Evaluation is incomplete. ""Nothing was submitted.""\n\n"f"Saved answers: "f"{len(cache)}/"f"{len(tasks)}"),build_results_table(tasks,cache,),)answers_payload = [24 unmodified linesprint("")print("All 20 answers are ready.")print(f"Submitting "f"{len(answers_payload)} "f"answers...")try:5 unmodified linesresponse.raise_for_status()result = (response.json())except Exception as error:print(f"Submission failed: "f"{error}")return (("All answers are saved, ""but submission failed.""\n\n"f"Error: {error}""\n\n""Click the same button ""again. Cached answers ""will not be recomputed."),build_results_table(tasks,cache,),)final_status = ("Submission Successful!\n"f"User: "14 unmodified linesreturn (final_status,build_results_table(tasks,cache,),)9 unmodified lines1. Log in to your Hugging Face account.2. Click **Run / Resume Evaluation & Submit All Answers**.3. Completed answers are cached during the running Space session.4. If a temporary API or quota error occurs, click the same button again to resume.5. Answers are submitted only after all 20 questions are ready.""")
app.py+294-242