Quiz_Generator / app.py
starkbyte45896's picture
Update app.py
a0307db verified
Raw History Blame Contribute Delete
3.8 kB
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)