File size: 5,362 Bytes
cbe419f
383d2d3
cbe419f
 
 
383d2d3
 
cbe419f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383d2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae85a53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
824f6d2
ae85a53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbe419f
 
383d2d3
 
ae85a53
 
 
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import json
import os

import requests

from model import AssistantModel

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

def _get_response(url: str):
    try:
        response = requests.get(url, timeout=15)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred fetching questions: {e}")
        return None
    return response

def _get_response_json(url: str):
    try:
        response = _get_response(url)
        questions_data = response.json()
        if not questions_data:
            print("Fetched questions list is empty.")
            return {}, None
        print(f"Fetched {len(questions_data)} questions.")
    except requests.exceptions.JSONDecodeError as e:
         print(f"Error decoding JSON response from questions endpoint: {e}")
         print(f"Response text: {response.text[:500]}")
         return {}, None

    return questions_data


def load_questions() -> None:
    questions_url = f"{DEFAULT_API_URL}/questions"

    questions_data = _get_response_json(questions_url)

    with open(r'./dataset/questions.json', 'w') as f:
        json.dump(questions_data, f, indent=2)


def load_files() -> None:
    with open(r'./dataset/questions.json', 'r') as f:
        questions_data = json.load(f)

    for q in questions_data:
        if q["file_name"] != '':
            files_url = f'{DEFAULT_API_URL}/files/{q["task_id"]}'

            print(f"Fetching file from: {files_url}")

            file_data = _get_response(files_url)

            with open(f'./dataset/{q["file_name"]}', 'wb') as f:
                f.write(file_data.content)
                print(f"File {q['file_name']} downloaded successfully.")


def run_validation() -> None:
    with open(r'./dataset/questions.json', 'r') as f:
        questions_data = json.load(f)

    results_file = r'./dataset/results.json'
    if os.path.exists(results_file):
        with open(results_file, 'r') as f:
            results = json.load(f)
    else:
        results = {}

    model = AssistantModel()

    for question in questions_data:
        print('Task ID:', question['task_id'])
        try:
            if 'youtube.com' in question['question']:
                raise Exception('Youtube is not supported')

            if question['file_name'].endswith('.mp3'):
                raise Exception('MP3 file is not supported')

            answer = model.ask_question(question['question'], question['file_name'])
        except Exception as e:
            print(f"Error processing question {question['task_id']}: {e}")
            answer = "N/A"
        results[question['task_id']]=answer
        print('Answer:', answer)

        with open(r'./dataset/results.json', 'w') as f:
            json.dump(results, f, indent=2)


def prepare_submission() -> None:
    with open(r'./dataset/results.json', 'r') as f:
        results = json.load(f)

    lines = [f'{{"task_id": "{id}", "model_answer":"{a}"}}' for id, a in results.items()]

    with open(r'./dataset/submission.jsonl', 'w') as f:
        f.write('\n'.join(lines))


def post_submission() -> None:
    with open(r'./dataset/results.json', 'r') as f:
        results = json.load(f)

    space_id = os.environ['SPACE_ID']

    submission_json = {
        "username": os.environ['HF_USERNAME'],
        "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
        "answers": [{"task_id": id, "submitted_answer": a} for id, a in results.items()]
    }

    print(json.dumps(submission_json, indent=2))

    submit_url = f"{DEFAULT_API_URL}/submit"

    try:
        response = requests.post(submit_url, json=submission_json, timeout=60)
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        print(final_status)
        print("Submission successful.")
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {e.response.status_code}."
        try:
            error_json = e.response.json()
            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
        except requests.exceptions.JSONDecodeError:
            error_detail += f" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)


if __name__ == '__main__':
    # load_questions()
    # load_files()

    # run_validation()

    # prepare_submission()

    post_submission()