Spaces:
Sleeping
Sleeping
Update app.py
Browse files61 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619761 unmodified linesdef run_and_submit_all(profile: gr.OAuthProfile | None):# Проверка логинаif not profile:return "Please login to Hugging Face via the button above.", Noneusername = profile.usernameapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Инициализация агента и инструментовtry:llm = ChatOpenAI(model_name=config.OPENAI_MODEL,openai_api_key=config.OPENAI_API_KEY,temperature=0.2)tool_classes = [GaiaQATool, WikiSearchTool, SearchSummaryTool,YouTubeSpeciesTool, YouTubeTranscriptionTool, ExcelTool,CodeGenTool, WebSearchTool, StringTool, ChessTool,GroupTool, GroceryTool, PythonExecTool]tools = []for cls in tool_classes:inst = cls()tools.append(Tool(name=inst.name, func=inst._run, description=inst.description))agent = initialize_agent(tools=tools,llm=llm,agent="zero-shot-react-description",verbose=False,max_iterations=30,early_stopping_method="generate",handle_parsing_errors=True)except Exception as e:return f"Error initializing agent: {e}", None# 2. Загрузка всех вопросов с retry/backoffquestions = Nonebackoff = 5for attempt in range(5):try:r = requests.get(questions_url, timeout=15)if r.status_code == 429:time.sleep(backoff)backoff *= 2continuer.raise_for_status()questions = r.json()breakexcept Exception as e:if attempt == 4:return f"Error fetching questions: {e}", Nonetime.sleep(backoff)backoff *= 2if not questions:return "No questions retrieved.", None# 3. Обработка каждого вопросаresults = []payload = []for item in questions:tid = item.get("task_id")q = item.get("question", "").strip()if not tid or not q:continue# 3.1 GAIA override для вопросов "how many"if q.lower().startswith("how many"):raw = GaiaQATool()._run(q)ans = normalize_answer(raw)else:# 3.2 Загрузка вложенного файла через APIfile_entry = item.get("file") or item.get("file_url") or item.get("attachment")file_path = Noneif file_entry:try:resp = requests.get(f"{api_url}/files/{tid}", timeout=15)resp.raise_for_status()ext = os.path.splitext(str(file_entry))[-1] or ""tmp_path = f"/tmp/{tid}{ext}"with open(tmp_path, "wb") as f:f.write(resp.content)file_path = tmp_pathexcept Exception:file_path = None# 3.3 Прямое исполнение .pyif file_path and file_path.lower().endswith(".py"):raw = PythonExecTool()._run(file_path)ans = normalize_answer(raw)else:# 3.4 Общий случай: invoke agentprompt = qif file_path:prompt += f"\nFilePath: {file_path}"raw = agent.invoke(prompt)if hasattr(raw, "content"):raw = raw.contenttry:parsed = json.loads(raw)raw = parsed.get("output", raw)except Exception:passans = normalize_answer(raw)results.append({"Task ID": tid, "Question": q, "Answer": ans})payload.append({"task_id": tid, "submitted_answer": ans})# 4. Отправка ответовsubmission = {"username": username,"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID','unknown')}/tree/main","answers": payload}try:resp2 = requests.post(submit_url, json=submission, timeout=60)resp2.raise_for_status()data = resp2.json()status = (f"Submission Successful!\n"f"User: {data.get('username')}\n"f"Score: {data.get('score','N/A')} ({data.get('correct_count','?')}/"f"{data.get('total_attempted','?')})\n"f"{data.get('message','')}")except Exception as e:status = f"Submission Failed: {e}"return status, pd.DataFrame(results)# --- Интерфейс Gradio ---61 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416561 unmodified linesdef run_and_submit_all(profile: gr.OAuthProfile | None):if not profile:return "Please login …", Noneusername = profile.usernameapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Инициализация LLM и инструментовllm = ChatOpenAI(model_name=config.OPENAI_MODEL,openai_api_key=config.OPENAI_API_KEY,temperature=0.2)tool_classes = [GaiaQATool, WikiSearchTool, SearchSummaryTool,YouTubeSpeciesTool, YouTubeTranscriptionTool,ExcelTool, CodeGenTool, WebSearchTool,StringTool, ChessTool, GroupTool, GroceryTool,PythonExecTool]tools = [Tool(name=tc().name, func=tc()._run, description=tc().description)for tc in tool_classes]agent = initialize_agent(tools=tools, llm=llm,agent="zero-shot-react-description",max_iterations=30,early_stopping_method="generate",handle_parsing_errors=True,verbose=False,)# 2. Загрузка вопросов с retry/backoffquestions, backoff = None, 5for i in range(5):r = requests.get(questions_url, timeout=15)if r.status_code == 429:time.sleep(backoff)backoff *= 2continuer.raise_for_status()questions = r.json()breakif not questions:return "Error fetching questions or none returned.", Noneresults, payload = [], []for item in questions:tid = item.get("task_id"); q = item.get("question","").strip()if not tid or not q:continue# 3.1 GAIA-override для “how many”if q.lower().startswith("how many"):raw = GaiaQATool()._run(q)ans = normalize_answer(raw)else:# 3.2 скачиваем вложенный файл, если естьif item.get("has_file"):file_resp = requests.get(f"{api_url}/files/{tid}", timeout=15)file_resp.raise_for_status()# предположим: API отдаёт extensionext = os.path.splitext(item.get("file_name",""))[-1] or ".bin"local = f"/tmp/{tid}{ext}"with open(local,"wb") as f: f.write(file_resp.content)# 3.3 по расширению выбираем инструментif ext==".py":raw = PythonExecTool()._run(local)elif ext in (".xls",".xlsx"):raw = ExcelTool()._run(f"{local},filter=Category=='Food',col=Sales,agg=sum")elif ext==".mp3":raw = YouTubeTranscriptionTool()._run(local)elif ext in (".png",".jpg",".jpeg"):raw = ChessTool()._run(local)else:raw = agent.invoke(q)ans = normalize_answer(raw)else:# 3.4 общий вызов агентаraw = agent.invoke(q)if hasattr(raw,"content"): raw = raw.contenttry:parsed = json.loads(raw)raw = parsed.get("output", raw)except:passans = normalize_answer(raw)results.append({"Task ID":tid, "Question":q, "Answer":ans})payload.append({"task_id":tid, "submitted_answer":ans})# 4. submitsubmission = {"username":username,"agent_code":f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main","answers":payload}resp2 = requests.post(submit_url, json=submission, timeout=60)resp2.raise_for_status()data = resp2.json()status = (f"Submission Successful!\n"f"Score: {data['score']}% "f"({data['correct_count']}/{data['total_attempted']})")return status, pd.DataFrame(results)# --- Интерфейс Gradio ---
app.py+71-103