ttttim3's picture
Update agent code
90d0b3d verified
Raw History Blame Contribute Delete
2.19 kB
"""Submit the answers in results/ to the Unit 4 scoring API.
usage: python submit.py --space <hf_username>/<space_name> [--dry-run]
The HF username is read from the token (env HF_TOKEN, or macOS Keychain item "huggingface").
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import time
from pathlib import Path
import requests
API = "https://agents-course-unit4-scoring.hf.space"
ROOT = Path(__file__).parent
def hf_token() -> str:
tok = os.getenv("HF_TOKEN")
if tok:
return tok
return subprocess.run(
["security", "find-generic-password", "-a", os.getenv("USER", ""), "-s", "huggingface", "-w"],
capture_output=True, text=True, check=True,
).stdout.strip()
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--space", required=True, help="e.g. myname/agents-course-final-assignment")
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
username = requests.get(
"https://huggingface.co/api/whoami-v2", headers={"Authorization": f"Bearer {hf_token()}"}, timeout=30
).json()["name"]
questions = json.loads((ROOT / "data" / "questions.json").read_text())
answers = []
for q in questions:
path = ROOT / "results" / f"{q['task_id']}.json"
ans = json.loads(path.read_text()).get("answer", "") if path.exists() else ""
answers.append({"task_id": q["task_id"], "submitted_answer": ans})
payload = {
"username": username,
"agent_code": f"https://huggingface.co/spaces/{args.space}/tree/main",
"answers": answers,
}
print(f"user={username} code={payload['agent_code']} answers={sum(1 for a in answers if a['submitted_answer'])}/{len(answers)} non-empty")
if args.dry_run:
return
r = requests.post(f"{API}/submit", json=payload, timeout=120)
print(r.status_code, r.text)
out = ROOT / "submissions"
out.mkdir(exist_ok=True)
(out / f"{time.strftime('%Y%m%d-%H%M%S')}.json").write_text(
json.dumps({"status": r.status_code, "response": r.text}, ensure_ascii=False, indent=2)
)
if __name__ == "__main__":
main()