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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -49
app.py CHANGED
@@ -20,21 +20,25 @@ 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")),
@@ -49,7 +53,10 @@ SUBJECTS = {
49
  "index": faiss.read_index(faiss_phy_path)
50
  }
51
  }
52
- print("βœ“ All subject data loaded")
 
 
 
53
 
54
  # ------------------------------
55
  # Load LLM model (CPU)
@@ -69,7 +76,7 @@ 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:
@@ -80,43 +87,51 @@ def rag_search(query, subject, k=5):
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:
94
- - Use ONLY the information from the given context.
95
- - Do NOT hallucinate outside the context.
96
- - Each MCQ must include:
97
- β€’ 1 question
98
- β€’ 4 options (A, B, C, D)
99
- β€’ Correct answer at the end exactly like: Answer: B
100
- - No explanations.
 
 
101
 
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
 
@@ -160,6 +175,7 @@ HTML_TEMPLATE = """
160
  font-weight: 600;
161
  margin-bottom: 10px;
162
  color: #333;
 
163
  }
164
  select, input {
165
  width: 100%;
@@ -168,6 +184,7 @@ HTML_TEMPLATE = """
168
  border-radius: 10px;
169
  font-size: 16px;
170
  font-family: inherit;
 
171
  }
172
  select:focus, input:focus {
173
  outline: none;
@@ -175,7 +192,7 @@ HTML_TEMPLATE = """
175
  }
176
  button {
177
  width: 100%;
178
- padding: 15px;
179
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
180
  color: white;
181
  border: none;
@@ -206,14 +223,15 @@ HTML_TEMPLATE = """
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;
@@ -222,8 +240,8 @@ HTML_TEMPLATE = """
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;
@@ -234,18 +252,34 @@ HTML_TEMPLATE = """
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>
@@ -254,19 +288,19 @@ HTML_TEMPLATE = """
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>
@@ -278,7 +312,7 @@ HTML_TEMPLATE = """
278
  const topic = document.getElementById('topic').value.trim();
279
 
280
  if (!topic) {
281
- alert('Please enter a topic!');
282
  return;
283
  }
284
 
@@ -289,6 +323,7 @@ HTML_TEMPLATE = """
289
  loading.classList.add('show');
290
  result.classList.remove('show');
291
  btn.disabled = true;
 
292
 
293
  try {
294
  const response = await fetch('/generate', {
@@ -300,19 +335,27 @@ HTML_TEMPLATE = """
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>
@@ -338,28 +381,45 @@ def generate():
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)
 
20
  print("βœ“ Embedding model loaded")
21
 
22
  # ------------------------------
23
+ # Download files from Hugging Face
24
  # ------------------------------
25
+ REPO_ID = "Redfire-1234/pcb_tutor"
26
 
27
+ print("Downloading subject files from Hugging Face...")
 
 
 
 
28
 
29
+ # Download Biology files
30
+ bio_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="bio_chunks.pkl", repo_type="model")
31
  faiss_bio_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_bio.bin", repo_type="model")
32
+
33
+ # Download Chemistry files
34
+ chem_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="chem_chunks.pkl", repo_type="model")
35
  faiss_chem_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_chem.bin", repo_type="model")
36
+
37
+ # Download Physics files
38
+ phy_chunks_path = hf_hub_download(repo_id=REPO_ID, filename="phy_chunks.pkl", repo_type="model")
39
  faiss_phy_path = hf_hub_download(repo_id=REPO_ID, filename="faiss_phy.bin", repo_type="model")
40
 
41
+ # Load all subjects into memory
42
  SUBJECTS = {
43
  "biology": {
44
  "chunks": pickle.load(open(bio_chunks_path, "rb")),
 
53
  "index": faiss.read_index(faiss_phy_path)
54
  }
55
  }
56
+
57
+ print(f"βœ“ Biology: {len(SUBJECTS['biology']['chunks'])} chunks loaded")
58
+ print(f"βœ“ Chemistry: {len(SUBJECTS['chemistry']['chunks'])} chunks loaded")
59
+ print(f"βœ“ Physics: {len(SUBJECTS['physics']['chunks'])} chunks loaded")
60
 
61
  # ------------------------------
62
  # Load LLM model (CPU)
 
76
  print("=" * 50)
77
 
78
  # ------------------------------
79
+ # RAG Search in specific subject
80
  # ------------------------------
81
  def rag_search(query, subject, k=5):
82
  if subject not in SUBJECTS:
 
87
 
88
  q_emb = embed_model.encode([query]).astype("float32")
89
  D, I = index.search(q_emb, k)
90
+
91
+ # Get the actual chunks
92
+ results = []
93
+ for idx in I[0]:
94
+ if idx < len(chunks):
95
+ results.append(chunks[idx])
96
+
97
+ return "\n\n".join(results)
98
 
99
  # ------------------------------
100
  # MCQ Generation
101
  # ------------------------------
102
+ def generate_mcqs(context, topic, subject):
103
+ prompt = f"""You are a Class-12 {subject.title()} teacher.
104
+ Generate exactly 5 high-quality MCQs on the topic: "{topic}".
105
 
106
+ STRICT RULES:
107
+ - Use ONLY information from the context below
108
+ - Do NOT add information not present in the context
109
+ - Format each MCQ as:
110
+ Q1. [Question]
111
+ A) [Option]
112
+ B) [Option]
113
+ C) [Option]
114
+ D) [Option]
115
+ Answer: [Letter]
116
 
117
  Context:
118
  {context}
119
 
120
+ Generate 5 MCQs now:"""
121
 
122
  inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(device)
123
  outputs = model.generate(
124
  **inputs,
125
+ max_new_tokens=700,
126
  temperature=0.3,
127
  top_p=0.9,
128
  do_sample=True
129
  )
130
  result = tokenizer.decode(outputs[0], skip_special_tokens=True)
131
 
132
+ # Extract only the generated MCQs (after "Generate 5 MCQs now:")
133
+ if "Generate 5 MCQs now:" in result:
134
+ result = result.split("Generate 5 MCQs now:")[-1].strip()
135
 
136
  return result
137
 
 
175
  font-weight: 600;
176
  margin-bottom: 10px;
177
  color: #333;
178
+ font-size: 16px;
179
  }
180
  select, input {
181
  width: 100%;
 
184
  border-radius: 10px;
185
  font-size: 16px;
186
  font-family: inherit;
187
+ transition: border-color 0.3s;
188
  }
189
  select:focus, input:focus {
190
  outline: none;
 
192
  }
193
  button {
194
  width: 100%;
195
+ padding: 18px;
196
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
197
  color: white;
198
  border: none;
 
223
  .result h3 {
224
  color: #667eea;
225
  margin-bottom: 20px;
226
+ font-size: 1.4em;
227
  }
228
  .mcq-content {
229
  background: white;
230
+ padding: 25px;
231
  border-radius: 8px;
232
  white-space: pre-wrap;
233
+ line-height: 1.9;
234
+ font-size: 15px;
235
  }
236
  .loading {
237
  text-align: center;
 
240
  }
241
  .loading.show { display: block; }
242
  .spinner {
243
+ border: 4px solid #f3f3f3;
244
+ border-top: 4px solid #667eea;
245
  border-radius: 50%;
246
  width: 50px;
247
  height: 50px;
 
252
  0% { transform: rotate(0deg); }
253
  100% { transform: rotate(360deg); }
254
  }
255
+ .subject-tag {
256
+ display: inline-block;
257
+ padding: 5px 15px;
258
+ border-radius: 20px;
259
+ font-size: 13px;
260
+ font-weight: 600;
261
+ margin-right: 10px;
262
+ }
263
+ .bio { background: #d4edda; color: #155724; }
264
+ .chem { background: #d1ecf1; color: #0c5460; }
265
+ .phy { background: #f8d7da; color: #721c24; }
266
  </style>
267
  </head>
268
  <body>
269
  <div class="container">
270
  <div class="header">
271
  <h1>πŸŽ“ Class 12 PCB MCQ Generator</h1>
272
+ <p style="font-size: 1.1em; margin-bottom: 15px;">Generate practice MCQs from your textbooks</p>
273
+ <div>
274
+ <span class="subject-tag bio">Biology</span>
275
+ <span class="subject-tag chem">Chemistry</span>
276
+ <span class="subject-tag phy">Physics</span>
277
+ </div>
278
  </div>
279
 
280
  <div class="content">
281
  <div class="form-group">
282
+ <label for="subject">πŸ“š Select Subject</label>
283
  <select id="subject">
284
  <option value="biology">Biology</option>
285
  <option value="chemistry">Chemistry</option>
 
288
  </div>
289
 
290
  <div class="form-group">
291
+ <label for="topic">✏️ Enter Topic</label>
292
  <input type="text" id="topic" placeholder="e.g., Mitochondria, Chemical Bonding, Newton's Laws">
293
  </div>
294
 
295
+ <button onclick="generateMCQs()">πŸš€ Generate 5 MCQs</button>
296
 
297
  <div class="loading" id="loading">
298
  <div class="spinner"></div>
299
+ <p style="color: #666; font-size: 16px;">Generating MCQs... This may take 30-60 seconds</p>
300
  </div>
301
 
302
  <div class="result" id="result">
303
+ <h3>πŸ“ Generated MCQs:</h3>
304
  <div class="mcq-content" id="mcqContent"></div>
305
  </div>
306
  </div>
 
312
  const topic = document.getElementById('topic').value.trim();
313
 
314
  if (!topic) {
315
+ alert('⚠️ Please enter a topic!');
316
  return;
317
  }
318
 
 
323
  loading.classList.add('show');
324
  result.classList.remove('show');
325
  btn.disabled = true;
326
+ btn.textContent = '⏳ Generating...';
327
 
328
  try {
329
  const response = await fetch('/generate', {
 
335
  const data = await response.json();
336
 
337
  if (data.error) {
338
+ alert('❌ Error: ' + data.error);
339
  return;
340
  }
341
 
342
  document.getElementById('mcqContent').textContent = data.mcqs;
343
  result.classList.add('show');
344
  } catch (error) {
345
+ alert('❌ Error: ' + error.message);
346
  } finally {
347
  loading.classList.remove('show');
348
  btn.disabled = false;
349
+ btn.textContent = 'πŸš€ Generate 5 MCQs';
350
  }
351
  }
352
+
353
+ // Allow Enter key to submit
354
+ document.getElementById('topic').addEventListener('keypress', function(e) {
355
+ if (e.key === 'Enter') {
356
+ generateMCQs();
357
+ }
358
+ });
359
  </script>
360
  </body>
361
  </html>
 
381
  if subject not in SUBJECTS:
382
  return jsonify({"error": "Invalid subject. Choose biology, chemistry, or physics."}), 400
383
 
384
+ print(f"\nπŸ” Searching {subject} for topic: {topic}")
385
+
386
  # Retrieve context from RAG
387
  context = rag_search(topic, subject, k=5)
388
 
389
+ if not context or len(context.strip()) < 50:
390
+ return jsonify({"error": f"No relevant content found in {subject} for topic: {topic}"}), 404
391
+
392
+ print(f"βœ“ Found context ({len(context)} chars)")
393
 
394
  # Generate MCQs
395
+ print("πŸ€– Generating MCQs...")
396
+ mcqs = generate_mcqs(context, topic, subject)
397
+
398
+ print("βœ“ MCQs generated successfully")
399
 
400
+ return jsonify({"mcqs": mcqs, "subject": subject})
401
 
402
  except Exception as e:
403
+ print(f"❌ Error in /generate: {e}")
404
+ import traceback
405
+ traceback.print_exc()
406
  return jsonify({"error": str(e)}), 500
407
 
408
  @app.route("/health")
409
  def health():
410
+ return jsonify({
411
+ "status": "healthy",
412
+ "subjects": {
413
+ "biology": len(SUBJECTS["biology"]["chunks"]),
414
+ "chemistry": len(SUBJECTS["chemistry"]["chunks"]),
415
+ "physics": len(SUBJECTS["physics"]["chunks"])
416
+ }
417
+ })
418
 
419
  # ------------------------------
420
  # Run the App
421
  # ------------------------------
422
  if __name__ == "__main__":
423
  port = int(os.environ.get("PORT", 7860))
424
+ print(f"\nπŸš€ Starting Flask on 0.0.0.0:{port}\n")
425
  app.run(host="0.0.0.0", port=port, debug=False)