import os import traceback from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, HTMLResponse cache_dir = os.environ.get("HF_HOME", os.path.join(os.getcwd(), "hf_cache")) os.makedirs(cache_dir, exist_ok=True) os.environ["HF_HOME"] = cache_dir os.environ["HF_DATASETS_CACHE"] = cache_dir from quiz_logic import generator app = FastAPI() @app.get("/", response_class=HTMLResponse) async def home(): return """
This is the FastAPI backend for the Smart Quiz system. It provides an API endpoint to generate AI-powered multiple-choice quiz questions based on a given topic.
👉 To try the full interactive quiz experience, please visit the Gradio UI: NZLouislu/smart-quiz-ui
POST request to /generate_quiz
with the following JSON body:
{ "topic": "New Zealand", "n_questions": 3, "difficulty": "medium" }""" @app.post("/generate_quiz") async def generate_quiz(request: Request): try: data = await request.json() topic = (data.get("topic") or "").strip() n_questions = int(data.get("n_questions", 3)) difficulty = data.get("difficulty", "medium") if not topic: return JSONResponse(status_code=400, content={"error": "Topic is required."}) questions = generator.generate_questions(topic, n_questions, difficulty) return {"questions": [{"question": q["question"], "options": q["options"], "answer": q["answer"]} for q in questions]} except Exception as e: tb = traceback.format_exc() return JSONResponse(status_code=500, content={"error": str(e), "traceback": tb})