Spaces:
Sleeping

File size: 3,159 Bytes
086367b
 
 
 
 
 
ed3b377
086367b
 
 
 
 
 
 
 
ed3b377
 
 
086367b
ed3b377
 
086367b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed3b377
086367b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed3b377
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import gradio as gr
import fitz  # PyMuPDF
from transformers import pipeline
import json

# Load Hugging Face model pipeline
qa_model = pipeline("text2text-generation", model="google/flan-t5-xl", device=0)

# Extract text from PDF
def extract_text_from_pdf(filepath):
    doc = fitz.open(filepath)
    return "".join([page.get_text() for page in doc])

# Generate MCQs from text using HF model
def generate_mcqs_with_hf_model(text):
    # Truncate input to ~2000 characters for token safety
    text = text[:2000]

    prompt = f"Generate 3 multiple choice questions with 4 options each from the following lecture notes:\n\n{text}\n\nOutput format: JSON list with question, options, and answer."

    result = qa_model(prompt, max_new_tokens=512)[0]["generated_text"]

    try:
        json_start = result.find("[")
        mcqs = json.loads(result[json_start:])
    except Exception:
        mcqs = [
            {
                "question": "What is the capital of France?",
                "options": ["Berlin", "Madrid", "Paris", "Rome"],
                "answer": "Paris"
            }
        ]
    return mcqs

with gr.Blocks() as demo:
    gr.Markdown("# 🧠 PDF to MCQ Quiz Generator (Powered by flan-t5-xl)")

    pdf_file = gr.File(label="Upload PDF Slides", file_types=[".pdf"])
    generate_btn = gr.Button("Generate Quiz")

    quiz_area = gr.Column(visible=False)
    question_radios = []
    answer_store = gr.State([])

    for i in range(5):
        radio = gr.Radio(choices=[], label=f"Question {i+1}", visible=False, type="value")
        question_radios.append(radio)

    submit_btn = gr.Button("Submit Answers", visible=False)
    result_box = gr.Textbox(label="Result", visible=False)

    def handle_generate(file):
        text = extract_text_from_pdf(file.name)
        mcqs = generate_mcqs_with_hf_model(text)
        correct_answers = []
        updates = []

        for i in range(5):
            if i < len(mcqs):
                q = mcqs[i]
                updates.append(gr.update(choices=q["options"], label=q["question"], visible=True))
                correct_answers.append(q["answer"])
            else:
                updates.append(gr.update(visible=False))

        return updates + [gr.update(visible=True), gr.update(visible=True), correct_answers]

    generate_btn.click(
        fn=handle_generate,
        inputs=pdf_file,
        outputs=question_radios + [submit_btn, quiz_area, answer_store]
    )

    def handle_submit(*user_answers_and_state):
        *user_answers, correct_answers = user_answers_and_state
        score = 0
        feedback = []

        for i, (user_ans, correct_ans) in enumerate(zip(user_answers, correct_answers)):
            if user_ans == correct_ans:
                score += 1
                feedback.append(f"{i+1}. ✅ Correct")
            else:
                feedback.append(f"{i+1}. ❌ Your answer: {user_ans} | Correct: {correct_ans}")

        return f"Score: {score}/{len(correct_answers)}\n\n" + "\n".join(feedback)

    submit_btn.click(
        fn=handle_submit,
        inputs=question_radios + [answer_store],
        outputs=result_box
    )

demo.launch()