File size: 2,187 Bytes
90d0b3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""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()