File size: 2,098 Bytes
679703e
afd816f
bf40495
755902a
679703e
 
 
 
 
 
bf40495
ca359f4
bf40495
 
755902a
 
 
 
 
 
 
6a8da1e
 
 
f51cd75
ffe198d
652cec3
6a8da1e
 
755902a
 
 
6a8da1e
 
755902a
 
 
 
bf40495
 
 
4a9190b
 
 
 
 
 
b19c493
 
bf40495
4a9190b
679703e
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
49
50
51
52
53
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})