Redfire-1234 commited on
Commit
998d25f
·
verified ·
1 Parent(s): 241bc53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -24
app.py CHANGED
@@ -24,6 +24,65 @@
24
  # print("STARTING MCQ GENERATOR APP")
25
  # print("=" * 50)
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # # ------------------------------
28
  # # Initialize Groq API Client
29
  # # ------------------------------
@@ -153,6 +212,107 @@
153
 
154
  # return "\n\n".join(results)
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  # # ------------------------------
157
  # # MCQ Generation
158
  # # ------------------------------
@@ -160,14 +320,12 @@
160
  # # Check if Groq is available
161
  # if not groq_client:
162
  # error_msg = """ERROR: Groq API not initialized!
163
-
164
  # Please check:
165
  # 1. GROQ_API_KEY is set in Space Settings → Repository secrets
166
  # 2. API key is valid (get one from https://console.groq.com/keys)
167
  # 3. Space has been restarted after adding the key
168
-
169
  # Current status: API key not found or invalid."""
170
- # return error_msg
171
 
172
  # # Check cache
173
  # context_hash = hashlib.md5(context.encode()).hexdigest()[:8]
@@ -175,14 +333,16 @@
175
 
176
  # if cache_key in MCQ_CACHE:
177
  # print("✓ Using cached MCQs")
178
- # return MCQ_CACHE[cache_key]
179
 
180
  # print(f"🤖 Generating MCQs for {subject} - {topic}")
181
 
 
 
 
182
  # prompt = f"""You are a Class-12 {subject.title()} teacher creating MCQs.
183
-
184
  # Topic: "{topic}"
185
-
186
  # Reference material from textbook:
187
  # {context[:1500]}
188
 
@@ -234,22 +394,21 @@
234
  # result = chat_completion.choices[0].message.content.strip()
235
  # result = clean_mcq_output(result)
236
 
237
- # cache_mcq(cache_key, result)
 
238
 
239
  # print("✓ MCQs generated successfully")
240
- # return result
241
 
242
  # except Exception as e:
243
  # error_msg = f"""Error calling Groq API: {str(e)}
244
-
245
  # Possible causes:
246
  # 1. Rate limit exceeded (wait a moment)
247
  # 2. Invalid API key
248
  # 3. Network issue
249
-
250
  # Please try again in a few seconds."""
251
  # print(f"❌ Groq API Error: {e}")
252
- # return error_msg
253
 
254
  # def clean_mcq_output(text):
255
  # lines = text.split('\n')
@@ -357,6 +516,27 @@
357
  # margin-bottom: 20px;
358
  # font-size: 1.4em;
359
  # }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  # .mcq-content {
361
  # background: white;
362
  # padding: 25px;
@@ -440,11 +620,20 @@
440
  # <div class="loading" id="loading">
441
  # <div class="spinner"></div>
442
  # <p style="color: #666; font-size: 16px;">Generating MCQs with AI...</p>
443
- # <p style="color: #999; font-size: 13px; margin-top: 10px;">⚡ Usually takes 5-10 seconds</p>
444
  # </div>
445
 
446
  # <div class="result" id="result">
447
  # <h3>📝 Generated MCQs:</h3>
 
 
 
 
 
 
 
 
 
448
  # <div style="background: #d4edda; padding: 12px; border-radius: 6px; margin-bottom: 15px; color: #155724; font-size: 14px;">
449
  # ✓ <strong>High Quality:</strong> Generated by Llama 3.3 70B via Groq API
450
  # </div>
@@ -465,9 +654,11 @@
465
  # const loading = document.getElementById('loading');
466
  # const result = document.getElementById('result');
467
  # const btn = document.querySelector('button');
 
468
 
469
  # loading.classList.add('show');
470
  # result.classList.remove('show');
 
471
  # btn.disabled = true;
472
  # btn.textContent = '⏳ Generating...';
473
 
@@ -485,6 +676,12 @@
485
  # return;
486
  # }
487
 
 
 
 
 
 
 
488
  # document.getElementById('mcqContent').textContent = data.mcqs;
489
  # result.classList.add('show');
490
  # } catch (error) {
@@ -535,9 +732,13 @@
535
 
536
  # print(f"✓ Context found ({len(context)} chars)")
537
 
538
- # mcqs = generate_mcqs(context, topic, subject)
539
 
540
- # return jsonify({"mcqs": mcqs, "subject": subject})
 
 
 
 
541
 
542
  # except Exception as e:
543
  # print(f"❌ Error: {e}")
@@ -560,6 +761,7 @@
560
  # port = int(os.environ.get("PORT", 7860))
561
  # print(f"\n🚀 Starting server on port {port}...\n")
562
  # app.run(host="0.0.0.0", port=port, debug=False)
 
563
  import pickle
564
  import faiss
565
  from flask import Flask, request, jsonify, render_template_string
@@ -780,9 +982,10 @@ def rag_search(query, subject, k=5):
780
  def detect_chapter_from_list(context, topic, subject):
781
  """
782
  Detect chapter using the actual chapter list by matching keywords
 
783
  """
784
  if subject not in CHAPTER_NAMES:
785
- return "Unknown Chapter"
786
 
787
  chapters = CHAPTER_NAMES[subject]
788
  combined_text = (topic + " " + context[:1000]).lower()
@@ -820,32 +1023,35 @@ def detect_chapter_from_list(context, topic, subject):
820
  def detect_chapter_with_llm(context, topic, subject, chapters):
821
  """
822
  Use LLM to pick the correct chapter from the provided list
 
823
  """
824
  if not groq_client:
825
- return "Unknown Chapter"
826
 
827
  chapter_list = "\n".join([f"{i+1}. {ch}" for i, ch in enumerate(chapters)])
828
 
829
- detection_prompt = f"""Based on the following textbook content and topic, identify which chapter from the list below this content belongs to.
830
 
831
  Topic: {topic}
832
 
833
  Content snippet:
834
  {context[:600]}
835
 
836
- Available chapters:
837
  {chapter_list}
838
 
839
- Respond with ONLY the chapter number and name exactly as listed (e.g., "5. Origin and Evolution of Life"). Choose the most relevant chapter.
840
 
841
- Chapter:"""
 
 
842
 
843
  try:
844
  response = groq_client.chat.completions.create(
845
  messages=[
846
  {
847
  "role": "system",
848
- "content": "You are an expert at identifying which chapter textbook content belongs to. Respond with only the chapter number and name from the provided list."
849
  },
850
  {
851
  "role": "user",
@@ -859,6 +1065,11 @@ Chapter:"""
859
 
860
  result = response.choices[0].message.content.strip()
861
 
 
 
 
 
 
862
  # Extract chapter name from response (remove number prefix if present)
863
  chapter = re.sub(r'^\d+\.\s*', '', result).strip()
864
 
@@ -869,11 +1080,11 @@ Chapter:"""
869
  return ch
870
 
871
  print(f"⚠️ LLM response not in list: {result}")
872
- return chapters[0] # Default to first chapter
873
 
874
  except Exception as e:
875
  print(f"⚠️ Chapter detection failed: {e}")
876
- return "Unknown Chapter"
877
 
878
  # ------------------------------
879
  # MCQ Generation
@@ -887,7 +1098,7 @@ Please check:
887
  2. API key is valid (get one from https://console.groq.com/keys)
888
  3. Space has been restarted after adding the key
889
  Current status: API key not found or invalid."""
890
- return error_msg, "Unknown"
891
 
892
  # Check cache
893
  context_hash = hashlib.md5(context.encode()).hexdigest()[:8]
@@ -902,6 +1113,12 @@ Current status: API key not found or invalid."""
902
  # Detect the chapter from our actual chapter list
903
  chapter = detect_chapter_from_list(context, topic, subject)
904
 
 
 
 
 
 
 
905
  prompt = f"""You are a Class-12 {subject.title()} teacher creating MCQs.
906
  Topic: "{topic}"
907
  Chapter: "{chapter}"
@@ -1296,6 +1513,10 @@ def generate():
1296
 
1297
  mcqs, chapter = generate_mcqs(context, topic, subject)
1298
 
 
 
 
 
1299
  return jsonify({
1300
  "mcqs": mcqs,
1301
  "subject": subject,
 
24
  # print("STARTING MCQ GENERATOR APP")
25
  # print("=" * 50)
26
 
27
+ # # ------------------------------
28
+ # # Chapter Names (Actual Textbook Chapters)
29
+ # # ------------------------------
30
+ # CHAPTER_NAMES = {
31
+ # "biology": [
32
+ # "Reproduction in Lower and Higher Plants",
33
+ # "Reproduction in Lower and Higher Animals",
34
+ # "Inheritance and Variation",
35
+ # "Molecular Basis of Inheritance",
36
+ # "Origin and Evolution of Life",
37
+ # "Plant Water Relation",
38
+ # "Plant Growth and Mineral Nutrition",
39
+ # "Respiration and Circulation",
40
+ # "Control and Co-ordination",
41
+ # "Human Health and Diseases",
42
+ # "Enhancement of Food Production",
43
+ # "Biotechnology",
44
+ # "Organisms and Populations",
45
+ # "Ecosystems and Energy Flow",
46
+ # "Biodiversity, Conservation and Environmental Issues"
47
+ # ],
48
+ # "chemistry": [
49
+ # "Solid State",
50
+ # "Solutions",
51
+ # "Ionic Equilibria",
52
+ # "Chemical Thermodynamics",
53
+ # "Electrochemistry",
54
+ # "Chemical Kinetics",
55
+ # "Elements of Groups 16, 17 and 18",
56
+ # "Transition and Inner transition Elements",
57
+ # "Coordination Compounds",
58
+ # "Halogen Derivatives",
59
+ # "Alcohols, Phenols and Ethers",
60
+ # "Aldehydes, Ketones and Carboxylic acids",
61
+ # "Amines",
62
+ # "Biomolecules",
63
+ # "Introduction to Polymer Chemistry",
64
+ # "Green Chemistry and Nanochemistry"
65
+ # ],
66
+ # "physics": [
67
+ # "Rotational Dynamics",
68
+ # "Mechanical Properties of Fluids",
69
+ # "Kinetic Theory of Gases and Radiation",
70
+ # "Thermodynamics",
71
+ # "Oscillations",
72
+ # "Superposition of Waves",
73
+ # "Wave Optics",
74
+ # "Electrostatics",
75
+ # "Current Electricity",
76
+ # "Magnetic Fields due to Electric Current",
77
+ # "Magnetic Materials",
78
+ # "Electromagnetic induction",
79
+ # "AC Circuits",
80
+ # "Dual Nature of Radiation and Matter",
81
+ # "Structure of Atoms and Nuclei",
82
+ # "Semiconductor Devices"
83
+ # ]
84
+ # }
85
+
86
  # # ------------------------------
87
  # # Initialize Groq API Client
88
  # # ------------------------------
 
212
 
213
  # return "\n\n".join(results)
214
 
215
+ # # ------------------------------
216
+ # # Chapter Detection (Using Actual Chapter Names)
217
+ # # ------------------------------
218
+ # def detect_chapter_from_list(context, topic, subject):
219
+ # """
220
+ # Detect chapter using the actual chapter list by matching keywords
221
+ # """
222
+ # if subject not in CHAPTER_NAMES:
223
+ # return "Unknown Chapter"
224
+
225
+ # chapters = CHAPTER_NAMES[subject]
226
+ # combined_text = (topic + " " + context[:1000]).lower()
227
+
228
+ # # Score each chapter based on keyword matching
229
+ # scores = {}
230
+ # for chapter in chapters:
231
+ # score = 0
232
+ # chapter_words = chapter.lower().split()
233
+
234
+ # # Check if chapter words appear in the content
235
+ # for word in chapter_words:
236
+ # if len(word) > 3: # Ignore small words like "and", "the"
237
+ # if word in combined_text:
238
+ # score += 1
239
+
240
+ # # Bonus if topic is similar to chapter name
241
+ # topic_words = topic.lower().split()
242
+ # for t_word in topic_words:
243
+ # if len(t_word) > 3 and t_word in chapter.lower():
244
+ # score += 2
245
+
246
+ # if score > 0:
247
+ # scores[chapter] = score
248
+
249
+ # # Return chapter with highest score
250
+ # if scores:
251
+ # best_chapter = max(scores.items(), key=lambda x: x[1])[0]
252
+ # print(f"✓ Matched chapter: {best_chapter} (score: {scores[best_chapter]})")
253
+ # return best_chapter
254
+
255
+ # # Fallback: Use LLM to choose from the list
256
+ # return detect_chapter_with_llm(context, topic, subject, chapters)
257
+
258
+ # def detect_chapter_with_llm(context, topic, subject, chapters):
259
+ # """
260
+ # Use LLM to pick the correct chapter from the provided list
261
+ # """
262
+ # if not groq_client:
263
+ # return "Unknown Chapter"
264
+
265
+ # chapter_list = "\n".join([f"{i+1}. {ch}" for i, ch in enumerate(chapters)])
266
+
267
+ # detection_prompt = f"""Based on the following textbook content and topic, identify which chapter from the list below this content belongs to.
268
+
269
+ # Topic: {topic}
270
+
271
+ # Content snippet:
272
+ # {context[:600]}
273
+
274
+ # Available chapters:
275
+ # {chapter_list}
276
+
277
+ # Respond with ONLY the chapter number and name exactly as listed (e.g., "5. Origin and Evolution of Life"). Choose the most relevant chapter.
278
+
279
+ # Chapter:"""
280
+
281
+ # try:
282
+ # response = groq_client.chat.completions.create(
283
+ # messages=[
284
+ # {
285
+ # "role": "system",
286
+ # "content": "You are an expert at identifying which chapter textbook content belongs to. Respond with only the chapter number and name from the provided list."
287
+ # },
288
+ # {
289
+ # "role": "user",
290
+ # "content": detection_prompt
291
+ # }
292
+ # ],
293
+ # model="llama-3.3-70b-versatile",
294
+ # temperature=0.1,
295
+ # max_tokens=50
296
+ # )
297
+
298
+ # result = response.choices[0].message.content.strip()
299
+
300
+ # # Extract chapter name from response (remove number prefix if present)
301
+ # chapter = re.sub(r'^\d+\.\s*', '', result).strip()
302
+
303
+ # # Verify it's in our list
304
+ # for ch in chapters:
305
+ # if ch.lower() in chapter.lower() or chapter.lower() in ch.lower():
306
+ # print(f"✓ LLM detected chapter: {ch}")
307
+ # return ch
308
+
309
+ # print(f"⚠️ LLM response not in list: {result}")
310
+ # return chapters[0] # Default to first chapter
311
+
312
+ # except Exception as e:
313
+ # print(f"⚠️ Chapter detection failed: {e}")
314
+ # return "Unknown Chapter"
315
+
316
  # # ------------------------------
317
  # # MCQ Generation
318
  # # ------------------------------
 
320
  # # Check if Groq is available
321
  # if not groq_client:
322
  # error_msg = """ERROR: Groq API not initialized!
 
323
  # Please check:
324
  # 1. GROQ_API_KEY is set in Space Settings → Repository secrets
325
  # 2. API key is valid (get one from https://console.groq.com/keys)
326
  # 3. Space has been restarted after adding the key
 
327
  # Current status: API key not found or invalid."""
328
+ # return error_msg, "Unknown"
329
 
330
  # # Check cache
331
  # context_hash = hashlib.md5(context.encode()).hexdigest()[:8]
 
333
 
334
  # if cache_key in MCQ_CACHE:
335
  # print("✓ Using cached MCQs")
336
+ # return MCQ_CACHE[cache_key]["mcqs"], MCQ_CACHE[cache_key]["chapter"]
337
 
338
  # print(f"🤖 Generating MCQs for {subject} - {topic}")
339
 
340
+ # # Detect the chapter from our actual chapter list
341
+ # chapter = detect_chapter_from_list(context, topic, subject)
342
+
343
  # prompt = f"""You are a Class-12 {subject.title()} teacher creating MCQs.
 
344
  # Topic: "{topic}"
345
+ # Chapter: "{chapter}"
346
  # Reference material from textbook:
347
  # {context[:1500]}
348
 
 
394
  # result = chat_completion.choices[0].message.content.strip()
395
  # result = clean_mcq_output(result)
396
 
397
+ # # Cache both MCQs and chapter
398
+ # cache_mcq(cache_key, {"mcqs": result, "chapter": chapter})
399
 
400
  # print("✓ MCQs generated successfully")
401
+ # return result, chapter
402
 
403
  # except Exception as e:
404
  # error_msg = f"""Error calling Groq API: {str(e)}
 
405
  # Possible causes:
406
  # 1. Rate limit exceeded (wait a moment)
407
  # 2. Invalid API key
408
  # 3. Network issue
 
409
  # Please try again in a few seconds."""
410
  # print(f"❌ Groq API Error: {e}")
411
+ # return error_msg, chapter
412
 
413
  # def clean_mcq_output(text):
414
  # lines = text.split('\n')
 
516
  # margin-bottom: 20px;
517
  # font-size: 1.4em;
518
  # }
519
+ # .chapter-info {
520
+ # background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
521
+ # color: white;
522
+ # padding: 15px 20px;
523
+ # border-radius: 8px;
524
+ # margin-bottom: 20px;
525
+ # display: flex;
526
+ # align-items: center;
527
+ # gap: 10px;
528
+ # font-size: 16px;
529
+ # }
530
+ # .chapter-icon {
531
+ # font-size: 24px;
532
+ # }
533
+ # .chapter-text {
534
+ # flex: 1;
535
+ # }
536
+ # .chapter-name {
537
+ # font-weight: 700;
538
+ # font-size: 18px;
539
+ # }
540
  # .mcq-content {
541
  # background: white;
542
  # padding: 25px;
 
620
  # <div class="loading" id="loading">
621
  # <div class="spinner"></div>
622
  # <p style="color: #666; font-size: 16px;">Generating MCQs with AI...</p>
623
+ # <p style="color: #999; font-size: 13px; margin-top: 10px;">⚡ Detecting chapter from textbook...</p>
624
  # </div>
625
 
626
  # <div class="result" id="result">
627
  # <h3>📝 Generated MCQs:</h3>
628
+
629
+ # <div class="chapter-info" id="chapterInfo" style="display: none;">
630
+ # <span class="chapter-icon">📖</span>
631
+ # <div class="chapter-text">
632
+ # <div style="font-size: 13px; opacity: 0.9;">Chapter:</div>
633
+ # <div class="chapter-name" id="chapterName"></div>
634
+ # </div>
635
+ # </div>
636
+
637
  # <div style="background: #d4edda; padding: 12px; border-radius: 6px; margin-bottom: 15px; color: #155724; font-size: 14px;">
638
  # ✓ <strong>High Quality:</strong> Generated by Llama 3.3 70B via Groq API
639
  # </div>
 
654
  # const loading = document.getElementById('loading');
655
  # const result = document.getElementById('result');
656
  # const btn = document.querySelector('button');
657
+ # const chapterInfo = document.getElementById('chapterInfo');
658
 
659
  # loading.classList.add('show');
660
  # result.classList.remove('show');
661
+ # chapterInfo.style.display = 'none';
662
  # btn.disabled = true;
663
  # btn.textContent = '⏳ Generating...';
664
 
 
676
  # return;
677
  # }
678
 
679
+ # // Display chapter info
680
+ # if (data.chapter && data.chapter !== 'Unknown Chapter') {
681
+ # document.getElementById('chapterName').textContent = data.chapter;
682
+ # chapterInfo.style.display = 'flex';
683
+ # }
684
+
685
  # document.getElementById('mcqContent').textContent = data.mcqs;
686
  # result.classList.add('show');
687
  # } catch (error) {
 
732
 
733
  # print(f"✓ Context found ({len(context)} chars)")
734
 
735
+ # mcqs, chapter = generate_mcqs(context, topic, subject)
736
 
737
+ # return jsonify({
738
+ # "mcqs": mcqs,
739
+ # "subject": subject,
740
+ # "chapter": chapter
741
+ # })
742
 
743
  # except Exception as e:
744
  # print(f"❌ Error: {e}")
 
761
  # port = int(os.environ.get("PORT", 7860))
762
  # print(f"\n🚀 Starting server on port {port}...\n")
763
  # app.run(host="0.0.0.0", port=port, debug=False)
764
+
765
  import pickle
766
  import faiss
767
  from flask import Flask, request, jsonify, render_template_string
 
982
  def detect_chapter_from_list(context, topic, subject):
983
  """
984
  Detect chapter using the actual chapter list by matching keywords
985
+ Returns None if topic doesn't match the subject
986
  """
987
  if subject not in CHAPTER_NAMES:
988
+ return None
989
 
990
  chapters = CHAPTER_NAMES[subject]
991
  combined_text = (topic + " " + context[:1000]).lower()
 
1023
  def detect_chapter_with_llm(context, topic, subject, chapters):
1024
  """
1025
  Use LLM to pick the correct chapter from the provided list
1026
+ Also verifies if the topic belongs to the subject
1027
  """
1028
  if not groq_client:
1029
+ return None
1030
 
1031
  chapter_list = "\n".join([f"{i+1}. {ch}" for i, ch in enumerate(chapters)])
1032
 
1033
+ detection_prompt = f"""Based on the following textbook content and topic, identify which chapter from the Class 12 {subject.title()} textbook this content belongs to.
1034
 
1035
  Topic: {topic}
1036
 
1037
  Content snippet:
1038
  {context[:600]}
1039
 
1040
+ Available {subject.title()} chapters:
1041
  {chapter_list}
1042
 
1043
+ IMPORTANT: If the topic and content do NOT belong to {subject.title()}, respond with "NOT_MATCHING".
1044
 
1045
+ If it matches, respond with ONLY the chapter number and name exactly as listed (e.g., "5. Origin and Evolution of Life").
1046
+
1047
+ Response:"""
1048
 
1049
  try:
1050
  response = groq_client.chat.completions.create(
1051
  messages=[
1052
  {
1053
  "role": "system",
1054
+ "content": f"You are an expert at identifying which chapter textbook content belongs to. You can recognize when content doesn't match the subject. If the topic is from a different subject than {subject.title()}, respond with 'NOT_MATCHING'."
1055
  },
1056
  {
1057
  "role": "user",
 
1065
 
1066
  result = response.choices[0].message.content.strip()
1067
 
1068
+ # Check if topic doesn't match the subject
1069
+ if "NOT_MATCHING" in result.upper() or "NOT MATCHING" in result.upper():
1070
+ print(f"⚠️ Topic '{topic}' doesn't belong to {subject}")
1071
+ return None
1072
+
1073
  # Extract chapter name from response (remove number prefix if present)
1074
  chapter = re.sub(r'^\d+\.\s*', '', result).strip()
1075
 
 
1080
  return ch
1081
 
1082
  print(f"⚠️ LLM response not in list: {result}")
1083
+ return None
1084
 
1085
  except Exception as e:
1086
  print(f"⚠️ Chapter detection failed: {e}")
1087
+ return None
1088
 
1089
  # ------------------------------
1090
  # MCQ Generation
 
1098
  2. API key is valid (get one from https://console.groq.com/keys)
1099
  3. Space has been restarted after adding the key
1100
  Current status: API key not found or invalid."""
1101
+ return error_msg, None
1102
 
1103
  # Check cache
1104
  context_hash = hashlib.md5(context.encode()).hexdigest()[:8]
 
1113
  # Detect the chapter from our actual chapter list
1114
  chapter = detect_chapter_from_list(context, topic, subject)
1115
 
1116
+ # If chapter is None, topic doesn't belong to this subject
1117
+ if chapter is None:
1118
+ error_msg = f"❌ The topic '{topic}' does not belong to {subject.title()}.\n\nPlease enter a topic related to {subject.title()} or select the correct subject."
1119
+ print(f"⚠️ Topic mismatch: '{topic}' not in {subject}")
1120
+ return error_msg, None
1121
+
1122
  prompt = f"""You are a Class-12 {subject.title()} teacher creating MCQs.
1123
  Topic: "{topic}"
1124
  Chapter: "{chapter}"
 
1513
 
1514
  mcqs, chapter = generate_mcqs(context, topic, subject)
1515
 
1516
+ # Check if there was a subject mismatch
1517
+ if chapter is None:
1518
+ return jsonify({"error": mcqs}), 400
1519
+
1520
  return jsonify({
1521
  "mcqs": mcqs,
1522
  "subject": subject,