smart-quiz-api / app.py
NZLouislu's picture
Update app.py
679703e verified
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 """
<html>
<head><title>Smart Quiz API</title></head>
<body style="font-family: Arial; padding: 2em;">
<h1>🧠 Smart Quiz API</h1>
<p>This is the <strong>FastAPI backend</strong> for the Smart Quiz system. It provides an API endpoint to generate AI-powered multiple-choice quiz questions based on a given topic.</p>
<p>
👉 To try the full interactive quiz experience, please visit the Gradio UI:
<a href="https://huggingface.co/spaces/NZLouislu/smart-quiz-ui" target="_blank" rel="noopener noreferrer">
NZLouislu/smart-quiz-ui</a></p>
<p>POST</code> request to <code>/generate_quiz</code> with the following JSON body:</p>
<pre>
{
"topic": "New Zealand",
"n_questions": 3,
"difficulty": "medium"
}
</pre>
</body>
</html>
"""
@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})