Spaces:
Sleeping
Sleeping
import requests | |
import os | |
from typing import List, Dict, Any | |
class ApiClient: | |
def __init__(self, api_url="https://agents-course-unit4-scoring.hf.space"): | |
self.api_url = api_url | |
self.questions_url = f"{api_url}/questions" | |
self.submit_url = f"{api_url}/submit" | |
self.files_url = f"{api_url}/files" | |
def get_questions(self, limit=20) -> List[Dict[str, Any]]: | |
limit = min(limit, 20) | |
limit = max(limit, 1) | |
response = requests.get(self.questions_url) | |
response.raise_for_status() | |
return response.json()[:limit] | |
def get_random_question(self) -> Dict[str, Any]: | |
response = requests.get(f"{self.api_url}/random-question") | |
response.raise_for_status() | |
return response.json() | |
def get_file(self, task_id, file_name: str) -> bytes: | |
# check if file already exists | |
file_path = os.path.join("src/temp/files", file_name) | |
if os.path.exists(file_path): | |
return file_path | |
# Download the file | |
os.makedirs(os.path.dirname(file_path), exist_ok=True) | |
response = requests.get(f"{self.files_url}/{task_id}", stream=True) | |
response.raise_for_status() | |
# Save the file | |
with open(file_path, "wb") as f: | |
for chunk in response.iter_content(chunk_size=8192): | |
f.write(chunk) | |
print(f"File saved to {file_path}") | |
return file_path | |
def submit_answers( | |
self, | |
username: str, | |
agent_code: str, | |
answers_payload: List[Dict[str, Any]], | |
) -> Dict[str, Any]: | |
data = { | |
"username": username, | |
"agent_code": agent_code, | |
"answers": answers_payload, | |
} | |
response = requests.post(self.submit_url, json=data, timeout=60) | |
response.raise_for_status() | |
return response.json() | |