roshcheeku commited on
Commit
9512ec4
·
verified ·
1 Parent(s): f596536

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------- app.py ----------------
2
+ from flask import Flask, request, jsonify
3
+ import os
4
+ import uuid
5
+ import pdfplumber
6
+ from docx import Document
7
+ import openpyxl
8
+ from werkzeug.utils import secure_filename
9
+ from model_utils import extract_mcqs_with_model
10
+
11
+ app = Flask(__name__)
12
+ app.config['UPLOAD_FOLDER'] = 'uploads'
13
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
14
+
15
+ quiz_data_store = {}
16
+
17
+ def extract_text_from_pdf(filepath):
18
+ with pdfplumber.open(filepath) as pdf:
19
+ return "\n".join([p.extract_text() for p in pdf.pages if p.extract_text()])
20
+
21
+ def extract_text_from_docx(filepath):
22
+ doc = Document(filepath)
23
+ return "\n".join([para.text for para in doc.paragraphs])
24
+
25
+ def extract_text_from_excel(filepath):
26
+ wb = openpyxl.load_workbook(filepath)
27
+ sheet = wb.active
28
+ text = ""
29
+ for row in sheet.iter_rows(min_row=2, values_only=True):
30
+ if any(row):
31
+ text += " ".join([str(cell) for cell in row if cell is not None]) + "\n"
32
+ return text
33
+
34
+ @app.route('/upload', methods=['POST'])
35
+ def upload_file():
36
+ if 'file' not in request.files:
37
+ return jsonify({'error': 'No file provided'}), 400
38
+
39
+ file = request.files['file']
40
+ filename = secure_filename(file.filename)
41
+ ext = filename.split('.')[-1].lower()
42
+
43
+ uid = str(uuid.uuid4())
44
+ save_path = os.path.join(app.config['UPLOAD_FOLDER'], uid + '_' + filename)
45
+ file.save(save_path)
46
+
47
+ if ext == 'pdf':
48
+ text = extract_text_from_pdf(save_path)
49
+ elif ext == 'docx':
50
+ text = extract_text_from_docx(save_path)
51
+ elif ext in ['xls', 'xlsx']:
52
+ text = extract_text_from_excel(save_path)
53
+ else:
54
+ return jsonify({'error': 'Unsupported file type'}), 400
55
+
56
+ mcqs = extract_mcqs_with_model(text)
57
+ quiz_id = str(uuid.uuid4())
58
+ quiz_data_store[quiz_id] = mcqs
59
+
60
+ return jsonify({'quiz_id': quiz_id, 'mcqs': mcqs})
61
+
62
+ @app.route('/submit', methods=['POST'])
63
+ def submit_quiz():
64
+ data = request.json
65
+ quiz_id = data.get('quiz_id')
66
+ user_answers = data.get('answers')
67
+
68
+ if quiz_id not in quiz_data_store:
69
+ return jsonify({'error': 'Invalid quiz ID'}), 404
70
+
71
+ mcqs = quiz_data_store[quiz_id]
72
+ correct = 0
73
+ for i, ans in enumerate(user_answers):
74
+ if i < len(mcqs) and ans.upper() == mcqs[i]['answer'].upper():
75
+ correct += 1
76
+
77
+ total = len(mcqs)
78
+ accuracy = round((correct / total) * 100, 2) if total else 0
79
+
80
+ return jsonify({'score': correct, 'total': total, 'accuracy': accuracy})
81
+
82
+ if __name__ == '__main__':
83
+ app.run(host='0.0.0.0', port=7860)
84
+
85
+ # ---------------- model_utils.py ----------------
86
+ from transformers import pipeline
87
+
88
+ classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
89
+ labels = ["question", "option", "answer", "other"]
90
+
91
+ def classify_chunk(text):
92
+ result = classifier(text, labels)
93
+ return result['labels'][0]
94
+
95
+ def extract_mcqs_with_model(text):
96
+ chunks = [chunk.strip() for chunk in text.split("\n\n") if chunk.strip()]
97
+ mcqs = []
98
+ current = {"question": "", "options": [], "answer": ""}
99
+
100
+ for chunk in chunks:
101
+ label = classify_chunk(chunk)
102
+ if label == "question":
103
+ if current["question"]:
104
+ mcqs.append(current)
105
+ current = {"question": "", "options": [], "answer": ""}
106
+ current["question"] = chunk
107
+ elif label == "option":
108
+ current["options"].append(chunk)
109
+ elif label == "answer":
110
+ current["answer"] = chunk
111
+
112
+ if current["question"]:
113
+ mcqs.append(current)
114
+ return mcqs
115
+