mou3az commited on
Commit
4d33dac
1 Parent(s): b01d78d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -181
app.py CHANGED
@@ -1,181 +1,100 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Generated Quiz</title>
7
- <style>
8
- body {
9
- font-family: Arial, sans-serif;
10
- background-color: #f0f0f0;
11
- color: #333;
12
- margin: 20px;
13
- }
14
- h2 {
15
- background-color: #ffc107;
16
- padding: 10px;
17
- border-radius: 5px;
18
- }
19
- .quiz-container {
20
- background-color: #fff;
21
- padding: 20px;
22
- border-radius: 5px;
23
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
24
- margin-bottom: 20px;
25
- }
26
- .quiz-container pre {
27
- white-space: pre-wrap;
28
- }
29
- .generate-link {
30
- display: inline-block;
31
- margin-top: 10px;
32
- border: 2px solid transparent;
33
- padding: 5px 10px;
34
- text-decoration: none;
35
- color: #ffc107;
36
- font-weight: bold;
37
- border-radius: 4px;
38
- background-color: #333;
39
- }
40
- .generate-link:hover {
41
- text-decoration: none;
42
- background-color: #555;
43
- }
44
- a {
45
- color: #ffc107;
46
- text-decoration: none;
47
- }
48
- a:hover {
49
- text-decoration: underline;
50
- }
51
- </style>
52
- </head>
53
- <body>
54
- <div class="quiz-container">
55
- <h2>Generated Quiz</h2>
56
- <pre>{{ filtered_text }}</pre>
57
- <a href="/" class="generate-link">Back to generate another quiz</a>
58
- </div>
59
- <div id="quizSection"></div>
60
- <button id="submitQuiz" style="display: none;" onclick="submitQuiz()">Submit Quiz</button>
61
-
62
- <script>
63
- document.addEventListener('DOMContentLoaded', function() {
64
- generateQuiz("{{ filtered_text }}", {{ answers_and_explanations | tojson }});
65
- });
66
-
67
- function generateQuiz(filteredText, answersAndExplanations) {
68
- let quizSection = document.getElementById('quizSection');
69
- quizSection.innerHTML = '';
70
-
71
- let questions = filteredText.split(/\d+\.\s+/).filter(q => q.trim() !== '');
72
-
73
- questions.forEach((question, index) => {
74
- let parts = question.split('Choices:');
75
- let questionText = parts[0].replace('Question:', '').trim();
76
- let choicesText = parts[1].trim();
77
-
78
- let div = document.createElement('div');
79
- div.className = 'quiz-question';
80
- div.innerHTML = `<strong>${index + 1}: ${questionText}</strong>`;
81
-
82
- let choices = choicesText.split(/\s*[A-D]\)\s*/).filter(choice => choice.trim() !== '');
83
- let labels = choicesText.match(/\s*[A-D]\)\s*/g);
84
- choices.forEach((choice, i) => {
85
- let label = labels[i].trim().charAt(0);
86
-
87
- let choiceDiv = document.createElement('div');
88
-
89
- let input = document.createElement('input');
90
- input.type = 'radio';
91
- input.name = `question_${index + 1}`;
92
- input.value = label;
93
- input.id = `q${index + 1}_${label}`;
94
-
95
- let choiceLabel = document.createElement('label');
96
- choiceLabel.setAttribute('for', `q${index + 1}_${label}`);
97
- choiceLabel.textContent = `${label}) ${choice}`;
98
-
99
- choiceDiv.appendChild(input);
100
- choiceDiv.appendChild(choiceLabel);
101
-
102
- div.appendChild(choiceDiv);
103
- });
104
-
105
- let answerDiv = document.createElement('div');
106
- answerDiv.className = 'quiz-answer';
107
- answerDiv.style.display = 'none';
108
- div.appendChild(answerDiv);
109
-
110
- let explanationDiv = document.createElement('div');
111
- explanationDiv.className = 'quiz-explanation';
112
- explanationDiv.style.display = 'none';
113
- div.appendChild(explanationDiv);
114
-
115
- quizSection.appendChild(div);
116
- });
117
-
118
- document.getElementById('submitQuiz').style.display = 'block';
119
- }
120
-
121
- function validateQuiz() {
122
- let quizSection = document.getElementById('quizSection');
123
- let questions = quizSection.getElementsByClassName('quiz-question');
124
-
125
- for (let i = 0; i < questions.length; i++) {
126
- let inputs = questions[i].querySelectorAll('input[type="radio"]');
127
- let answered = false;
128
-
129
- for (let j = 0; j < inputs.length; j++) {
130
- if (inputs[j].checked) {
131
- answered = true;
132
- break;
133
- }
134
- }
135
-
136
- if (!answered) {
137
- return false;
138
- }
139
- }
140
-
141
- return true;
142
- }
143
-
144
- function submitQuiz() {
145
- if (!validateQuiz()) {
146
- alert('Please answer all questions before submitting.');
147
- return;
148
- }
149
-
150
- let quizSection = document.getElementById('quizSection');
151
- let questions = quizSection.getElementsByClassName('quiz-question');
152
-
153
- fetch('/process_text', {
154
- method: 'POST',
155
- headers: {
156
- 'Content-Type': 'application/json'
157
- },
158
- body: JSON.stringify({ text: "{{ filtered_text }}" })
159
- })
160
- .then(response => response.json())
161
- .then(data => {
162
- let answersAndExplanations = data.answers_and_explanations;
163
- for (let i = 0; i < questions.length; i++) {
164
- let answerDiv = questions[i].querySelector('.quiz-answer');
165
- let explanationDiv = questions[i].querySelector('.quiz-explanation');
166
- let answer = answersAndExplanations[i]?.Answer || '';
167
- let explanation = answersAndExplanations[i]?.Explanation || '';
168
-
169
- answerDiv.style.display = 'block';
170
- answerDiv.innerHTML = `Answer: ${answer}`;
171
-
172
- explanationDiv.style.display = 'block';
173
- explanationDiv.innerHTML = `Explanation: ${explanation}`;
174
- }
175
-
176
- document.getElementById('submitQuiz').style.display = 'none';
177
- });
178
- }
179
- </script>
180
- </body>
181
- </html>
 
1
+ from flask import Flask, request, jsonify, render_template
2
+ from huggingface_hub import InferenceClient
3
+ from requests.exceptions import RequestException
4
+
5
+ app = Flask(__name__)
6
+
7
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
8
+
9
+ def system_instructions(context):
10
+ return f"""<s> [INST] Your are a great teacher and your task is to create 6 questions with answer and 4 choices based on the following context:\n\n{context}\n\n. Each example should be like this
11
+ Question: ""
12
+ Choices:
13
+ A): ""
14
+ B): ""
15
+ C): ""
16
+ D): ""
17
+ Answer: "Choose either A, B, C, or D as the correct answer"
18
+ Explanation: ""
19
+ \n
20
+ [/INST]
21
+ """
22
+
23
+ def generate_quiz(context):
24
+ formatted_prompt = system_instructions(context)
25
+
26
+ generate_kwargs = dict(
27
+ temperature=0.1,
28
+ max_new_tokens=2048,
29
+ top_p=0.95,
30
+ repetition_penalty=1.0,
31
+ do_sample=True,
32
+ seed=42,)
33
+
34
+ try:
35
+ response = client.text_generation(
36
+ formatted_prompt,
37
+ **generate_kwargs,
38
+ stream=False,
39
+ details=False,
40
+ return_full_text=False,
41
+ )
42
+ return response
43
+
44
+ except (RequestException, SystemExit) as e:
45
+ return {"error": str(e)}
46
+
47
+ @app.route("/", methods=["GET", "POST"])
48
+ def generate_quiz_page():
49
+ if request.method == "POST":
50
+ if request.content_type == 'application/json':
51
+ data = request.get_json()
52
+ context = data.get("context")
53
+ if context is None or context.strip() == "":
54
+ return jsonify({"error": "Missing or empty 'context' parameter"}), 400
55
+ else:
56
+ context = request.form.get("context")
57
+ if context is None or context.strip() == "":
58
+ return jsonify({"error": "Missing or empty 'context' parameter"}), 400
59
+
60
+ response = generate_quiz(context)
61
+
62
+ if request.content_type == 'application/json':
63
+ return jsonify(response)
64
+
65
+ # Handle text processing for quiz generation
66
+ filtered_text, answers_and_explanations = handle_text(response)
67
+
68
+ return render_template('quiz.html', filtered_text=filtered_text, answers_and_explanations=answers_and_explanations)
69
+
70
+ # Default GET request handling
71
+ return render_template('index.html')
72
+
73
+ def handle_text(text):
74
+ lines = text.splitlines()
75
+ filtered_lines = []
76
+ answers_and_explanations = []
77
+
78
+ for line in lines:
79
+ line = line.strip()
80
+
81
+ if line.startswith("Question:"):
82
+ filtered_lines.append(line)
83
+ elif line.startswith("Choices:"):
84
+ filtered_lines.append(line)
85
+ elif line.startswith("Answer:"):
86
+ answer = line.split(":")[1].strip()
87
+ answers_and_explanations.append({"Answer": answer})
88
+ elif line.startswith("Explanation:"):
89
+ explanation = line.split(":")[1].strip()
90
+ answers_and_explanations[-1]["Explanation"] = explanation
91
+ elif line.startswith(("A)", "B)", "C)", "D)")):
92
+ filtered_lines.append(line)
93
+ else:
94
+ filtered_lines.append(line)
95
+
96
+ filtered_text = "\n".join(filtered_lines)
97
+ return filtered_text, answers_and_explanations
98
+
99
+ if __name__ == "__main__":
100
+ app.run(debug=True)