File size: 3,798 Bytes
c7d7299
 
a0307db
b5ca933
 
 
c7d7299
 
 
 
b5ca933
 
c7d7299
b5ca933
c7d7299
b5ca933
 
 
 
 
 
 
c7d7299
b5ca933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d7299
 
b5ca933
 
 
 
 
 
c7d7299
 
b5ca933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d7299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
from flask import Flask, request, jsonify
from flask_cors import CORS
import fitz 
import requests
import os

app = Flask(__name__)
CORS(app)  # Enable CORS

HF_API_KEY = os.getenv("HF_API_KEY")  # <-- From Hugging Face secret
MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.1"

def extract_text_from_pdf(file_stream):
    try:
        doc = fitz.open(stream=file_stream.read(), filetype="pdf")
        text = ""
        for page in doc:
            text += page.get_text()
            if len(text) > 1500:
                break
        return text.strip()
    except Exception as e:
        print("❌ Error extracting PDF:", e)
        return None

def generate_mcqs(text):
    prompt = f"""
    You are an expert teacher. Given the following content, generate 30 well-structured multiple-choice questions. Each question must have:
    1. A clear question
    2. 4 options (A, B, C, D)
    3. The correct answer letter

    Format the output as:
    Q1: <question>
    A. <option>
    B. <option>
    C. <option>
    D. <option>
    Answer: <letter>

    Text: {text}
    """

    headers = {"Authorization": f"Bearer {HF_API_KEY}"}
    payload = {"inputs": prompt, "parameters": {"max_new_tokens": 1024}}

    response = requests.post(MODEL_ENDPOINT, headers=headers, json=payload)
    print(" HF API Status:", response.status_code)
    print(" HF API Response:", response.text[:300])  # limit preview

    try:
        if response.status_code == 200:
            raw_output = response.json()[0]["generated_text"]
            return parse_mcqs(raw_output)
    except Exception as e:
        print("Parsing Error:", e)

    return []

def parse_mcqs(raw):
    questions = []
    blocks = raw.strip().split("Q")
    for blk in blocks[1:]:
        try:
            lines = blk.strip().split("\n")
            qtext = lines[0].split(":", 1)[1].strip()
            options = [l.split(". ", 1)[1].strip() for l in lines[1:5]]
            answer_line = next((l for l in lines if "Answer" in l), None)
            answer_letter = answer_line.split(":")[1].strip()
            correct = options[["A", "B", "C", "D"].index(answer_letter)]
            questions.append({
                "question": qtext,
                "options": options,
                "correct": correct
            })
        except:
            continue
        if len(questions) == 10:
            break
    return questions

# --- Flask Routes ---
@app.route('/generate-quiz', methods=['POST'])
def generate_quiz():
    try:
        if 'pdf_file' not in request.files:
            return jsonify({"error": "PDF file not provided"}), 400

        text = extract_text_from_pdf(request.files['pdf_file'])
        if not text:
            return jsonify({"error": "Unable to extract text from PDF"}), 500

        questions = generate_mcqs(text)
        if not questions:
            return jsonify({"error": "Failed to generate questions"}), 500

        return jsonify({"questions": questions}), 200

    except Exception as e:
        print(" Exception in /generate-quiz:", e)
        return jsonify({"error": str(e)}), 500

@app.route('/submit-quiz', methods=['POST'])
def submit_quiz():
    try:
        data = request.get_json()
        answers = data.get("answers", [])
        score = 0
        total = len(answers)

        for ans in answers:
            selected = ans.get("selected", "").strip().lower()
            correct = ans.get("correct", "").strip().lower()
            if selected == correct:
                score += 1

        return jsonify({"score": score, "total": total}), 200
    except Exception as e:
        return jsonify({"error": "Invalid data format"}), 400

# --- Main ---
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860, debug=True)