Spaces:
Sleeping
Sleeping
Update app.py
#21
by olcapone - opened
710 unmodified lines71171271371471571671771871972072172272322 unmodified lines7467477487497507517524 unmodified lines75775875976076176276311 unmodified lines77577677777877978078115 unmodified lines79779879980080180280319 unmodified lines82382482582682782882983083183283383483583683783883984084184214 unmodified lines857858859860861862863864865866867710 unmodified lines# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""if profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")return "Please Login to Hugging Face with the button.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"22 unmodified linesprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")4 unmodified lines# 3. Run your Agentresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")11 unmodified linesif not answers_payload:print("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}15 unmodified lines)print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:19 unmodified linesstatus_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfanswers_state = gr.State([])def build_jsonl(answers):import json, ospath = "/tmp/submission.jsonl"with open(path, "w", encoding="utf-8") as f:for a in answers:f.write(json.dumps({"task_id": a["task_id"], "model_answer": a["submitted_answer"]},ensure_ascii=False) + "\n")return path # gr.File/DownloadButton will serve this file# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:14 unmodified lines)gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)jsonl_file = gr.File(label="submission.jsonl", interactive=False)save_btn = gr.Button("Build JSONL for Leaderboard")710 unmodified lines71171271371471571671771871972072172272372422 unmodified lines7477487497507517527534 unmodified lines75875976076176276311 unmodified lines77577677777877978078115 unmodified lines79779879980080180280380419 unmodified lines82482582682782882983083183283383483583683783883984084184284384414 unmodified lines859860861862863864865866867868869870710 unmodified lines# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""answers_payload = []if profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")return "Please Login to Hugging Face with the button.", pd.DataFrame([]), answers_payloadapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"22 unmodified linesprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", pd.DataFrame([]), answers_payloadexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")4 unmodified lines# 3. Run your Agentresults_log = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")11 unmodified linesif not answers_payload:print("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log), answers_payload# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}15 unmodified lines)print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_df, answers_payloadexcept requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:19 unmodified linesstatus_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df, answers_payloaddef build_jsonl(answers):import json, ospath = "/tmp/submission.jsonl"if not isinstance(answers, list):answers = []with open(path, "w", encoding="utf-8") as f:for a in answers:tid = a.get("task_id")ans = a.get("submitted_answer")if tid is None or ans is None:continuef.write(json.dumps({"task_id": tid, "model_answer": ans}, ensure_ascii=False) + "\n")return path# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:14 unmodified lines)gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)answers_state = gr.State([])jsonl_file = gr.File(label="submission.jsonl", interactive=False)save_btn = gr.Button("Build JSONL for Leaderboard")
app.py+17-14