File size: 1,666 Bytes
6f31603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
import json

# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
QUESTIONS_FILE = "questions.json"

def fetch_and_save_questions():
    """
    Fetches questions from the API and saves them to a JSON file.
    """
    questions_url = f"{DEFAULT_API_URL}/questions"

    print(f"Fetching questions from: {questions_url}")
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
        questions_data = response.json()

        if not questions_data:
            print("Fetched questions list is empty or invalid format.")
            return

        print(f"Fetched {len(questions_data)} questions.")


        # Save the questions to a JSON file
        with open(QUESTIONS_FILE, 'w', encoding='utf-8') as f:
            json.dump(questions_data, f, indent=4)
        print(f"Successfully saved questions to {QUESTIONS_FILE}")

    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
    except requests.exceptions.JSONDecodeError as e:
        print(f"Error decoding JSON response from questions endpoint: {e}")
        if 'response' in locals() and response is not None:
            print(f"Response text (first 500 chars): {response.text[:500]}")
    except IOError as e:
        print(f"Error saving questions to file: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    print("--- Starting Question Fetcher ---")
    fetch_and_save_questions()
    print("--- Question Fetcher Finished ---")