File size: 2,500 Bytes
3d9164d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
"""Run the agent locally on all questions, cache answers, and optionally submit.

  python run_local.py                 # answer every question not yet cached
  python run_local.py --only 3 11     # (re)answer specific question indexes
  python run_local.py --submit        # submit cached answers

Submitting through the API needs no Gradio login: the scoring server only takes
the username, the public Space code link, and the answers.
"""

import argparse
import json
import os

import requests

from agent import API_URL, GaiaAgent, download_task_file

USERNAME = os.getenv("HF_USERNAME", "2tyoon")
SPACE_ID = os.getenv("SPACE_ID", f"{USERNAME}/Final_Assignment_Agent")
CACHE = "answers.json"


def load_cache() -> dict:
    if os.path.exists(CACHE):
        with open(CACHE, encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_cache(cache: dict) -> None:
    with open(CACHE, "w", encoding="utf-8") as f:
        json.dump(cache, f, ensure_ascii=False, indent=2)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--only", type=int, nargs="*")
    parser.add_argument("--submit", action="store_true")
    args = parser.parse_args()

    questions = requests.get(f"{API_URL}/questions", timeout=30).json()
    cache = load_cache()

    if args.submit:
        payload = {
            "username": USERNAME,
            "agent_code": f"https://huggingface.co/spaces/{SPACE_ID}/tree/main",
            "answers": [
                {"task_id": q["task_id"], "submitted_answer": cache[q["task_id"]]}
                for q in questions
                if q["task_id"] in cache
            ],
        }
        resp = requests.post(f"{API_URL}/submit", json=payload, timeout=120)
        print(resp.status_code, json.dumps(resp.json(), ensure_ascii=False, indent=2))
        return

    agent = GaiaAgent()
    for i, q in enumerate(questions):
        if args.only is not None and i not in args.only:
            continue
        if args.only is None and q["task_id"] in cache:
            continue
        print(f"\n===== [{i}] {q['question'][:120]}")
        try:
            file_path = download_task_file(q["task_id"], q.get("file_name", ""))
            answer = agent(q["question"], file_path)
        except Exception as e:
            print(f"!! error: {e}")
            continue
        print(f"===== [{i}] ANSWER: {answer}")
        cache[q["task_id"]] = answer
        save_cache(cache)


if __name__ == "__main__":
    main()