Spaces:
Sleeping
Sleeping
Download utils.py from juancitro/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 3.61 kB
-
https://huggingface.co/spaces/juancitro/Final_Assignment_Template/resolve/main/utils.py
- Command line
-
hf download hf://spaces/juancitro/Final_Assignment_Template/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/juancitro/Final_Assignment_Template/resolve/main/utils.py
3.61 kB
| from pydantic import BaseModel | |
| import requests | |
| import json | |
| USERNAME = "juancitro" | |
| SPACE_ID = "juancitro/Final_Assignment_Template" | |
| AGENT_CODE = f"https://huggingface.co/spaces/{SPACE_ID}/tree/main" | |
| API_URL = "https://agents-course-unit4-scoring.hf.space" # Replace with actual API URL | |
| def extract_json(response: str) -> dict | None: | |
| """ | |
| Extract the JSON part of the LLM response, and remove some invalid caracters. | |
| """ | |
| try: | |
| json_start = response.index("{") | |
| json_end = response.rfind("}") | |
| json_str_response = response[json_start:json_end + 1] | |
| json_str_response = json_str_response.replace('\n', ' ') | |
| json_response = json.loads(json_str_response) | |
| except (ValueError, json.JSONDecodeError) as e: | |
| print(f"JSON can't be parsed: {e}. Original response: {response}") | |
| return None | |
| return json_response | |
| class GAIAQuestions(BaseModel): | |
| task_id: str | |
| question: str | |
| Level: str | |
| answer: str | None = None | |
| file_name: str | None = None | |
| def load_qa_data(file_path: str) -> list[GAIAQuestions]: | |
| import json | |
| with open(file_path, 'r') as f: | |
| questions = json.load(f) | |
| return [GAIAQuestions(**question) for question in questions] | |
| def submit(questions: list[GAIAQuestions], username=USERNAME, agent_code=AGENT_CODE, submit_url = f"{API_URL}/submit") -> str: | |
| answers_payload = [] | |
| results_log = [] | |
| for item in questions: | |
| answers_payload.append({"task_id": item.task_id, "submitted_answer": item.answer}) | |
| results_log.append({"Task ID": item.task_id, "Question": item.question, "Submitted Answer": item.answer}) | |
| submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} | |
| status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." | |
| print(status_update) | |
| # 5. Submit | |
| print(f"Submitting {len(answers_payload)} answers to: {submit_url}") | |
| try: | |
| response = requests.post(submit_url, json=submission_data, 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("Submission successful.") | |
| return final_status | |
| 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) | |
| return status_message | |
| except requests.exceptions.Timeout: | |
| status_message = "Submission Failed: The request timed out." | |
| print(status_message) | |
| return status_message | |
| except requests.exceptions.RequestException as e: | |
| status_message = f"Submission Failed: Network error - {e}" | |
| print(status_message) | |
| return status_message | |
| except Exception as e: | |
| status_message = f"An unexpected error occurred during submission: {e}" | |
| print(status_message) | |
| return status_message | |