Redfire-1234 commited on
Commit
3e8a626
·
verified ·
1 Parent(s): 03c0299

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +306 -50
app.py CHANGED
@@ -1,60 +1,93 @@
1
  import pickle
2
  import faiss
3
- from flask import Flask, request, jsonify
4
  from sentence_transformers import SentenceTransformer
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
 
6
  import torch
 
7
 
8
  app = Flask(__name__)
9
 
 
 
 
 
10
  # ------------------------------
11
  # Load embedding model (CPU)
12
  # ------------------------------
13
  embed_model = SentenceTransformer("all-MiniLM-L6-v2")
 
14
 
15
  # ------------------------------
16
- # Load subject-wise chunks + FAISS indexes
17
  # ------------------------------
18
- def load_subject(subject):
19
- if subject == "biology":
20
- chunks = pickle.load(open("bio_chunks.pkl", "rb"))
21
- index = faiss.read_index("faiss_bio.bin")
22
- elif subject == "chemistry":
23
- chunks = pickle.load(open("chem_chunks.pkl", "rb"))
24
- index = faiss.read_index("faiss_chem.bin")
25
- elif subject == "physics":
26
- chunks = pickle.load(open("phy_chunks.pkl", "rb"))
27
- index = faiss.read_index("faiss_phy.bin")
28
- else:
29
- return None, None
30
- return chunks, index
31
 
32
- # ------------------------------
33
- # Search inside the selected subject
34
- # ------------------------------
35
- def rag_search(query, chunks, index, k=5):
36
- q_emb = embed_model.encode([query]).astype("float32")
37
- D, I = index.search(q_emb, k)
38
- results = [chunks[i] for i in I[0]]
39
- return "\n".join(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  # ------------------------------
42
- # Load your fine-tuned model (CPU only)
43
  # ------------------------------
44
  model_name = "Qwen/Qwen2.5-1.5B-Instruct"
 
45
  tokenizer = AutoTokenizer.from_pretrained(model_name)
46
  device = "cpu"
47
  model = AutoModelForCausalLM.from_pretrained(
48
  model_name,
49
  torch_dtype=torch.float32
50
  ).to(device)
 
 
 
 
 
51
 
52
  # ------------------------------
53
- # MCQ Generation (strict, no hallucination)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  # ------------------------------
55
  def generate_mcqs(context, topic):
56
- prompt = f"""
57
- You are a Class-12 PCB teacher.
58
  Generate exactly 5 high-quality MCQs from the topic: "{topic}".
59
 
60
  Rules:
@@ -69,41 +102,264 @@ Rules:
69
  Context:
70
  {context}
71
 
72
- Generate now:
73
- """
74
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
75
  outputs = model.generate(
76
  **inputs,
77
- max_new_tokens=400,
78
- temperature=0.1, # low temperature to reduce hallucination
79
- top_p=0.9
 
80
  )
81
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
82
 
83
  # ------------------------------
84
- # API Route
85
  # ------------------------------
86
- @app.route("/generate", methods=["POST"])
87
- def generate():
88
- data = request.json
89
- subject = data.get("subject", "").lower()
90
- topic = data.get("topic", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- # Load subject files
93
- chunks, index = load_subject(subject)
94
- if chunks is None:
95
- return jsonify({"error": "Invalid subject. Choose biology, chemistry, physics."}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # Retrieve context from RAG
98
- context = rag_search(topic, chunks, index)
 
 
 
 
99
 
100
- # Generate MCQs
101
- mcqs = generate_mcqs(context, topic)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- return jsonify({"mcqs": mcqs})
 
 
104
 
105
  # ------------------------------
106
  # Run the App
107
  # ------------------------------
108
  if __name__ == "__main__":
109
- app.run(host="0.0.0.0", port=7860)
 
 
1
  import pickle
2
  import faiss
3
+ from flask import Flask, request, jsonify, render_template_string
4
  from sentence_transformers import SentenceTransformer
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ from huggingface_hub import hf_hub_download
7
  import torch
8
+ import os
9
 
10
  app = Flask(__name__)
11
 
12
+ print("=" * 50)
13
+ print("Loading models and data...")
14
+ print("=" * 50)
15
+
16
  # ------------------------------
17
  # Load embedding model (CPU)
18
  # ------------------------------
19
  embed_model = SentenceTransformer("all-MiniLM-L6-v2")
20
+ print("✓ Embedding model loaded")
21
 
22
  # ------------------------------
23
+ # Download and load subject-wise files from Hugging Face
24
  # ------------------------------
25
+ REPO_ID = "Redfire-1234/pcb_tutor" # Your model repo
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # Download all files
28
+ print("Downloading files from Hugging Face...")
29
+ bio_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="bio_chunks.pkl", repo_type="model")
30
+ chem_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="chem_chunks.pkl", repo_type="model")
31
+ phy_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="phy_chunks.pkl", repo_type="model")
32
+
33
+ faiss_bio_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_bio.bin", repo_type="model")
34
+ faiss_chem_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_chem.bin", repo_type="model")
35
+ faiss_phy_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_phy.bin", repo_type="model")
36
+
37
+ # Load into memory
38
+ SUBJECTS = {
39
+ "biology": {
40
+ "chunks": pickle.load(open(bio_chunks_path, "rb")),
41
+ "index": faiss.read_index(faiss_bio_path)
42
+ },
43
+ "chemistry": {
44
+ "chunks": pickle.load(open(chem_chunks_path, "rb")),
45
+ "index": faiss.read_index(faiss_chem_path)
46
+ },
47
+ "physics": {
48
+ "chunks": pickle.load(open(phy_chunks_path, "rb")),
49
+ "index": faiss.read_index(faiss_phy_path)
50
+ }
51
+ }
52
+ print("✓ All subject data loaded")
53
 
54
  # ------------------------------
55
+ # Load LLM model (CPU)
56
  # ------------------------------
57
  model_name = "Qwen/Qwen2.5-1.5B-Instruct"
58
+ print(f"Loading LLM: {model_name}")
59
  tokenizer = AutoTokenizer.from_pretrained(model_name)
60
  device = "cpu"
61
  model = AutoModelForCausalLM.from_pretrained(
62
  model_name,
63
  torch_dtype=torch.float32
64
  ).to(device)
65
+ print(f"✓ LLM loaded on {device}")
66
+
67
+ print("=" * 50)
68
+ print("All models loaded successfully!")
69
+ print("=" * 50)
70
 
71
  # ------------------------------
72
+ # Search inside the selected subject
73
+ # ------------------------------
74
+ def rag_search(query, subject, k=5):
75
+ if subject not in SUBJECTS:
76
+ return None
77
+
78
+ chunks = SUBJECTS[subject]["chunks"]
79
+ index = SUBJECTS[subject]["index"]
80
+
81
+ q_emb = embed_model.encode([query]).astype("float32")
82
+ D, I = index.search(q_emb, k)
83
+ results = [chunks[i] for i in I[0]]
84
+ return "\n".join(results)
85
+
86
+ # ------------------------------
87
+ # MCQ Generation
88
  # ------------------------------
89
  def generate_mcqs(context, topic):
90
+ prompt = f"""You are a Class-12 PCB teacher.
 
91
  Generate exactly 5 high-quality MCQs from the topic: "{topic}".
92
 
93
  Rules:
 
102
  Context:
103
  {context}
104
 
105
+ Generate now:"""
106
+
107
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(device)
108
  outputs = model.generate(
109
  **inputs,
110
+ max_new_tokens=600,
111
+ temperature=0.3,
112
+ top_p=0.9,
113
+ do_sample=True
114
  )
115
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
116
+
117
+ # Extract only the generated part (after the prompt)
118
+ if "Generate now:" in result:
119
+ result = result.split("Generate now:")[-1].strip()
120
+
121
+ return result
122
 
123
  # ------------------------------
124
+ # HTML UI
125
  # ------------------------------
126
+ HTML_TEMPLATE = """
127
+ <!DOCTYPE html>
128
+ <html>
129
+ <head>
130
+ <title>Class 12 PCB MCQ Generator</title>
131
+ <style>
132
+ * { margin: 0; padding: 0; box-sizing: border-box; }
133
+ body {
134
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
135
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
136
+ min-height: 100vh;
137
+ padding: 20px;
138
+ }
139
+ .container {
140
+ max-width: 900px;
141
+ margin: 0 auto;
142
+ background: white;
143
+ border-radius: 20px;
144
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
145
+ overflow: hidden;
146
+ }
147
+ .header {
148
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
149
+ color: white;
150
+ padding: 30px;
151
+ text-align: center;
152
+ }
153
+ .header h1 { font-size: 2.5em; margin-bottom: 10px; }
154
+ .content { padding: 40px; }
155
+ .form-group {
156
+ margin-bottom: 25px;
157
+ }
158
+ label {
159
+ display: block;
160
+ font-weight: 600;
161
+ margin-bottom: 10px;
162
+ color: #333;
163
+ }
164
+ select, input {
165
+ width: 100%;
166
+ padding: 15px;
167
+ border: 2px solid #e0e0e0;
168
+ border-radius: 10px;
169
+ font-size: 16px;
170
+ font-family: inherit;
171
+ }
172
+ select:focus, input:focus {
173
+ outline: none;
174
+ border-color: #667eea;
175
+ }
176
+ button {
177
+ width: 100%;
178
+ padding: 15px;
179
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
180
+ color: white;
181
+ border: none;
182
+ border-radius: 10px;
183
+ font-size: 18px;
184
+ font-weight: 600;
185
+ cursor: pointer;
186
+ transition: all 0.3s;
187
+ }
188
+ button:hover {
189
+ transform: translateY(-2px);
190
+ box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
191
+ }
192
+ button:disabled {
193
+ background: #ccc;
194
+ cursor: not-allowed;
195
+ transform: none;
196
+ }
197
+ .result {
198
+ margin-top: 30px;
199
+ padding: 25px;
200
+ background: #f8f9fa;
201
+ border-radius: 10px;
202
+ border-left: 4px solid #667eea;
203
+ display: none;
204
+ }
205
+ .result.show { display: block; }
206
+ .result h3 {
207
+ color: #667eea;
208
+ margin-bottom: 20px;
209
+ }
210
+ .mcq-content {
211
+ background: white;
212
+ padding: 20px;
213
+ border-radius: 8px;
214
+ white-space: pre-wrap;
215
+ line-height: 1.8;
216
+ font-family: monospace;
217
+ }
218
+ .loading {
219
+ text-align: center;
220
+ padding: 30px;
221
+ display: none;
222
+ }
223
+ .loading.show { display: block; }
224
+ .spinner {
225
+ border: 3px solid #f3f3f3;
226
+ border-top: 3px solid #667eea;
227
+ border-radius: 50%;
228
+ width: 50px;
229
+ height: 50px;
230
+ animation: spin 1s linear infinite;
231
+ margin: 0 auto 15px;
232
+ }
233
+ @keyframes spin {
234
+ 0% { transform: rotate(0deg); }
235
+ 100% { transform: rotate(360deg); }
236
+ }
237
+ </style>
238
+ </head>
239
+ <body>
240
+ <div class="container">
241
+ <div class="header">
242
+ <h1>🎓 Class 12 PCB MCQ Generator</h1>
243
+ <p>Generate practice MCQs from Physics, Chemistry & Biology</p>
244
+ </div>
245
+
246
+ <div class="content">
247
+ <div class="form-group">
248
+ <label for="subject">Select Subject</label>
249
+ <select id="subject">
250
+ <option value="biology">Biology</option>
251
+ <option value="chemistry">Chemistry</option>
252
+ <option value="physics">Physics</option>
253
+ </select>
254
+ </div>
255
+
256
+ <div class="form-group">
257
+ <label for="topic">Enter Topic</label>
258
+ <input type="text" id="topic" placeholder="e.g., Mitochondria, Chemical Bonding, Newton's Laws">
259
+ </div>
260
+
261
+ <button onclick="generateMCQs()">Generate MCQs</button>
262
+
263
+ <div class="loading" id="loading">
264
+ <div class="spinner"></div>
265
+ <p style="color: #666;">Generating MCQs... This may take 30-60 seconds</p>
266
+ </div>
267
+
268
+ <div class="result" id="result">
269
+ <h3>Generated MCQs:</h3>
270
+ <div class="mcq-content" id="mcqContent"></div>
271
+ </div>
272
+ </div>
273
+ </div>
274
 
275
+ <script>
276
+ async function generateMCQs() {
277
+ const subject = document.getElementById('subject').value;
278
+ const topic = document.getElementById('topic').value.trim();
279
+
280
+ if (!topic) {
281
+ alert('Please enter a topic!');
282
+ return;
283
+ }
284
+
285
+ const loading = document.getElementById('loading');
286
+ const result = document.getElementById('result');
287
+ const btn = document.querySelector('button');
288
+
289
+ loading.classList.add('show');
290
+ result.classList.remove('show');
291
+ btn.disabled = true;
292
+
293
+ try {
294
+ const response = await fetch('/generate', {
295
+ method: 'POST',
296
+ headers: {'Content-Type': 'application/json'},
297
+ body: JSON.stringify({subject, topic})
298
+ });
299
+
300
+ const data = await response.json();
301
+
302
+ if (data.error) {
303
+ alert('Error: ' + data.error);
304
+ return;
305
+ }
306
+
307
+ document.getElementById('mcqContent').textContent = data.mcqs;
308
+ result.classList.add('show');
309
+ } catch (error) {
310
+ alert('Error: ' + error.message);
311
+ } finally {
312
+ loading.classList.remove('show');
313
+ btn.disabled = false;
314
+ }
315
+ }
316
+ </script>
317
+ </body>
318
+ </html>
319
+ """
320
 
321
+ # ------------------------------
322
+ # Routes
323
+ # ------------------------------
324
+ @app.route("/")
325
+ def home():
326
+ return render_template_string(HTML_TEMPLATE)
327
 
328
+ @app.route("/generate", methods=["POST"])
329
+ def generate():
330
+ try:
331
+ data = request.json
332
+ subject = data.get("subject", "").lower()
333
+ topic = data.get("topic", "")
334
+
335
+ if not topic:
336
+ return jsonify({"error": "Topic is required"}), 400
337
+
338
+ if subject not in SUBJECTS:
339
+ return jsonify({"error": "Invalid subject. Choose biology, chemistry, or physics."}), 400
340
+
341
+ # Retrieve context from RAG
342
+ context = rag_search(topic, subject, k=5)
343
+
344
+ if not context:
345
+ return jsonify({"error": "No relevant content found for this topic"}), 404
346
+
347
+ # Generate MCQs
348
+ mcqs = generate_mcqs(context, topic)
349
+
350
+ return jsonify({"mcqs": mcqs})
351
+
352
+ except Exception as e:
353
+ print(f"Error in /generate: {e}")
354
+ return jsonify({"error": str(e)}), 500
355
 
356
+ @app.route("/health")
357
+ def health():
358
+ return jsonify({"status": "healthy"})
359
 
360
  # ------------------------------
361
  # Run the App
362
  # ------------------------------
363
  if __name__ == "__main__":
364
+ port = int(os.environ.get("PORT", 7860))
365
+ app.run(host="0.0.0.0", port=port, debug=False)