Dipti Dhawade commited on
Commit
b2c44ca
Β·
1 Parent(s): 6548616

smart notes-grounded prompt pipeline

Browse files
backend/api.py CHANGED
@@ -1082,7 +1082,7 @@ def study_generate(
1082
 
1083
 
1084
  @app.post("/study/mindmap")
1085
- def study_mindmap(
1086
  courses: str = Form(""),
1087
  focus_query: str = Form("main concepts"),
1088
  opened_file_path: str = Form(""),
@@ -1103,12 +1103,12 @@ def study_mindmap(
1103
  )
1104
  if cerr:
1105
  return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
1106
- data, err = llm_pipeline.mind_map_json(ctx)
1107
  if err:
1108
  return JSONResponse({"error": err}, status_code=503)
1109
  return JSONResponse(
1110
  {
1111
- "graph": data,
1112
  "grounded_on_path": _strip_storage_path(opened_file_path or ""),
1113
  "context_chars": len(ctx or ""),
1114
  }
 
1082
 
1083
 
1084
  @app.post("/study/mindmap")
1085
+ def study_summary(
1086
  courses: str = Form(""),
1087
  focus_query: str = Form("main concepts"),
1088
  opened_file_path: str = Form(""),
 
1103
  )
1104
  if cerr:
1105
  return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
1106
+ summary_text, err = llm_pipeline.topic_summary(ctx)
1107
  if err:
1108
  return JSONResponse({"error": err}, status_code=503)
1109
  return JSONResponse(
1110
  {
1111
+ "summary": summary_text,
1112
  "grounded_on_path": _strip_storage_path(opened_file_path or ""),
1113
  "context_chars": len(ctx or ""),
1114
  }
backend/llm_pipeline.py CHANGED
@@ -3,7 +3,6 @@ import json
3
  import os
4
  import re
5
  import tempfile
6
- import unicodedata
7
  import zipfile
8
  from typing import Any
9
 
@@ -253,7 +252,7 @@ def sarvam_general_answer(question: str) -> tuple[str | None, str | None]:
253
 
254
 
255
  def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | None]:
256
- """Answer strictly from provided notes context."""
257
  ctx = (context or "").strip()[:60000]
258
  q = (question or "").strip()
259
  if not q:
@@ -262,17 +261,30 @@ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | No
262
  {
263
  "role": "system",
264
  "content": (
265
- "You are a teaching assistant answering ONLY from the provided notes excerpts. "
266
- "Do not claim inability to access files. "
267
- "If answer is not present in the excerpts, say that clearly and suggest what to open/upload."
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  ),
269
  },
270
  {
271
  "role": "user",
272
  "content": (
273
- f"Question:\n{q}\n\n"
274
- f"Notes excerpts:\n{ctx}\n\n"
275
- "Answer using only these excerpts."
276
  ),
277
  },
278
  ]
@@ -280,7 +292,7 @@ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | No
280
  messages,
281
  model=_model_rag(),
282
  max_tokens=4096,
283
- temperature=0.2,
284
  )
285
 
286
 
@@ -319,129 +331,10 @@ def _context_keywords(context: str) -> set[str]:
319
  return {k for k, _v in ranked[:250]}
320
 
321
 
322
- def _grounded_enough(text: str, keywords: set[str], *, min_hits: int = 2) -> bool:
323
- if not keywords:
324
- return False
325
- hits = len(set(_tokens(text)) & keywords)
326
- return hits >= min_hits
327
-
328
-
329
- def _normalize_study_match(s: str) -> str:
330
- t = unicodedata.normalize("NFKC", s or "")
331
- for u, a in (
332
- ("\u2013", "-"),
333
- ("\u2014", "-"),
334
- ("\u2212", "-"),
335
- ("\u00a0", " "),
336
- ("\u200b", ""),
337
- ):
338
- t = t.replace(u, a)
339
- return re.sub(r"\s+", " ", t.strip().lower())
340
-
341
-
342
- def _contains_context_quote(context: str, quote: str) -> bool:
343
- q = (quote or "").strip()
344
- if len(q) < 12:
345
- return False
346
- ctx_raw = context or ""
347
- # Fast path: exact / case-insensitive substring of raw notes (handles OCR spacing).
348
- if q in ctx_raw:
349
- return True
350
- if q.lower() in ctx_raw.lower():
351
- return True
352
- ctx_n = _normalize_study_match(context)
353
- qq = _normalize_study_match(q)
354
- if len(qq) < 12:
355
- return False
356
- if qq in ctx_n:
357
- return True
358
- # Model may drop punctuation around matrices / LaTeX; alnum fold still ties to notes.
359
- def fold(t: str) -> str:
360
- return re.sub(r"[^a-z0-9]+", "", t)
361
-
362
- qf, cf = fold(qq), fold(ctx_n)
363
- return len(qf) >= 10 and qf in cf
364
-
365
-
366
- def _pick_evidence_span(body: str, text_for_match: str, *, min_len: int = 12, max_len: int = 240) -> str:
367
- """Choose a substring of body that best overlaps tokens from text_for_match (server-side evidence)."""
368
- b = body or ""
369
- if len(b) < min_len:
370
- return ""
371
- toks = [t for t in _tokens(text_for_match) if len(t) >= 3][:50]
372
- win = min(max_len, len(b))
373
- win = max(min_len, win)
374
- step = max(40, win // 4)
375
- best_i, best_score = 0, -1
376
- upper = max(1, len(b) - win + 1)
377
- for i in range(0, upper, step):
378
- chunk = b[i : i + win]
379
- cl = chunk.lower()
380
- score = sum(1 for t in toks if t in cl) if toks else len(chunk)
381
- if score > best_score:
382
- best_score = score
383
- best_i = i
384
- span = b[best_i : best_i + win].strip()
385
- if len(span) < min_len:
386
- span = b[: min(max_len, len(b))].strip()
387
- out = span[:max_len] if span else ""
388
- if out and not _contains_context_quote(b, out):
389
- out = b[: min(max_len, len(b))].strip()[:max_len]
390
- return out
391
-
392
-
393
- def _best_line_snippet(body: str, anchor_text: str, max_len: int = 220) -> str:
394
- """Return a note line (or start of body) that best overlaps anchor tokens."""
395
- b = body or ""
396
- if len(b) < 12:
397
- return ""
398
- want = set(_tokens(anchor_text))
399
- best_s, best_score = "", -1
400
- for line in b.splitlines():
401
- s = line.strip()
402
- if len(s) < 12:
403
- continue
404
- got = set(_tokens(s))
405
- score = len(want & got) if want else len(s)
406
- if score > best_score:
407
- best_score, best_s = score, s
408
- if best_s and _contains_context_quote(b, best_s[:max_len]):
409
- return best_s[:max_len].strip()
410
- head = b[:max_len].strip()
411
- return head if len(head) >= 12 else ""
412
-
413
-
414
- def _token_overlap(a: str, b: str) -> int:
415
- return len(set(_tokens(a)) & set(_tokens(b)))
416
-
417
-
418
- def _finalize_evidence(primary_body: str, evidence: str, anchor_text: str, keywords: set[str]) -> str | None:
419
- """Return evidence substring of primary_body: model quote, picked span, best line, or note head."""
420
- body = (primary_body or "").strip()
421
- if len(body) < 12:
422
- return None
423
- ev = (evidence or "").strip()
424
- if ev and _contains_context_quote(body, ev):
425
- return ev[:500]
426
- picked = _pick_evidence_span(body, anchor_text)
427
- if picked and _contains_context_quote(body, picked):
428
- return picked[:500]
429
- line_snip = _best_line_snippet(body, anchor_text)
430
- if line_snip and _contains_context_quote(body, line_snip):
431
- return line_snip[:500]
432
- if _grounded_enough(anchor_text, keywords, min_hits=1):
433
- head = body[: min(220, len(body))].strip()
434
- if len(head) >= 12 and _contains_context_quote(body, head):
435
- return head
436
- return None
437
-
438
-
439
- def _validate_flashcards(
440
- items: Any, n: int, keywords: set[str], ctx: str, primary_body: str
441
- ) -> list[dict[str, str]] | None:
442
  if not isinstance(items, list):
443
  return None
444
- body = (primary_body or _primary_body_from_study_ctx(ctx) or ctx).strip()
445
  cleaned: list[dict[str, str]] = []
446
  for it in items:
447
  if len(cleaned) >= n:
@@ -450,20 +343,17 @@ def _validate_flashcards(
450
  continue
451
  front = str(it.get("front") or "").strip()
452
  back = str(it.get("back") or "").strip()
453
- if not front or not back:
454
- continue
455
- ev_raw = str(it.get("evidence") or "").strip()
456
- evidence = _finalize_evidence(body, ev_raw, front + " " + back, keywords)
457
- if not evidence:
458
  continue
459
- cleaned.append({"front": front, "back": back, "evidence": evidence})
 
460
  return cleaned if len(cleaned) >= 1 else None
461
 
462
 
463
- def _validate_mcq(items: Any, n: int, keywords: set[str], ctx: str, primary_body: str) -> list[dict[str, Any]] | None:
 
464
  if not isinstance(items, list):
465
  return None
466
- body = (primary_body or _primary_body_from_study_ctx(ctx) or ctx).strip()
467
  cleaned: list[dict[str, Any]] = []
468
  for it in items:
469
  if len(cleaned) >= n:
@@ -484,19 +374,13 @@ def _validate_mcq(items: Any, n: int, keywords: set[str], ctx: str, primary_body
484
  norm_opts = [str(x or "").strip() for x in opts]
485
  if any(not o for o in norm_opts):
486
  continue
487
- anchor = " ".join([q] + norm_opts)
488
- ev_raw = str(it.get("evidence") or "").strip()
489
- evidence = _finalize_evidence(body, ev_raw, anchor, keywords)
490
- if not evidence:
491
- continue
492
- cleaned.append(
493
- {
494
- "question": q,
495
- "options": norm_opts,
496
- "answer_index": ai_i,
497
- "evidence": evidence,
498
- }
499
- )
500
  return cleaned if len(cleaned) >= 1 else None
501
 
502
 
@@ -559,64 +443,54 @@ def _synthetic_mcq_from_body(body: str, n: int) -> list[dict[str, Any]]:
559
  return out
560
 
561
 
562
- def _synthetic_mind_map(body: str) -> dict[str, Any]:
563
- b = (body or "").strip()
564
- lines = [ln.strip() for ln in b.splitlines() if 18 <= len(ln.strip()) <= 220][:14]
565
- if len(lines) < 2:
566
- step = 60
567
- lines = [b[i : i + step].strip() for i in range(0, min(len(b), 480), step) if len(b[i : i + step].strip()) >= 12][
568
- :10
569
- ]
570
- if len(lines) < 2:
571
- return {"nodes": [], "edges": []}
572
- nodes = [{"id": str(i + 1), "label": lines[i][:90], "source_quote": lines[i][:220]} for i in range(len(lines))]
573
- edges = [{"source": str(i), "target": str(i + 1), "label": ""} for i in range(1, len(nodes))]
574
- return {"nodes": nodes, "edges": edges}
575
-
576
 
577
  def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
578
  ctx = context[:60000]
579
  body = _primary_body_from_study_ctx(ctx)
580
  keywords = _context_keywords(body or ctx)
581
- if len(keywords) < 6:
582
- return None, "Not enough usable note content for grounded study generation."
 
583
  if task == "flashcards":
584
- prompt = f"""You are generating study material ONLY from the provided notes context.
585
- STRICT RULES:
586
- - Use only facts/concepts that appear in the context.
587
- - Do NOT use outside knowledge, generic filler, or random topics.
588
- - If context is insufficient, still stay within context and produce shorter/simpler cards.
589
- - Return EXACTLY {n} items.
590
- - Output ONLY a JSON array of objects with keys "front", "back", "evidence". No markdown fence.
591
- - "evidence" must be a contiguous quote copied from the PRIMARY FILE CONTENT section (>= 12 chars). Copy punctuation and wording literally when possible.
592
- - Include exact terminology/phrases from the notes where possible.
593
-
594
- Notes context:
595
- {ctx}
596
- """
 
 
597
  else:
598
- prompt = f"""You are generating study material ONLY from the provided notes context.
599
- STRICT RULES:
600
- - Use only facts/concepts that appear in the context.
601
- - Do NOT use outside knowledge, generic filler, or random topics.
602
- - Keep questions grounded in the notes wording/ideas.
603
- - Return EXACTLY {n} items.
604
- - Output ONLY a JSON array of objects with keys "question", "options" (array of 4 strings), "answer_index" (0-3), "evidence". No markdown fence.
605
- - "evidence" must be a contiguous quote copied from the PRIMARY FILE CONTENT section (>= 12 chars). Copy punctuation and wording literally when possible.
606
- - Include exact terminology/phrases from the notes where possible.
607
-
608
- Notes context:
609
- {ctx}
610
- """
611
- attempts = 3
 
612
  last_err = "generation failed"
613
- for k in range(attempts):
614
- msg = prompt if k == 0 else (prompt + "\n\nPrevious output was not grounded in notes. Regenerate with stricter note-anchored content.")
615
  raw, err = _sarvam_chat_complete(
616
  [{"role": "user", "content": msg}],
617
  model=_model_study(),
618
  max_tokens=8192,
619
- temperature=0.05,
620
  )
621
  if err:
622
  last_err = err
@@ -631,14 +505,15 @@ Notes context:
631
  last_err = "Model returned JSON but not a list of study items."
632
  continue
633
  if task == "flashcards":
634
- valid = _validate_flashcards(coerced, n, keywords, ctx, body)
635
  else:
636
- valid = _validate_mcq(coerced, n, keywords, ctx, body)
637
  if valid is not None and len(valid) >= 1:
638
  return valid, None
639
- last_err = "Model output was not grounded in selected notes."
640
  except json.JSONDecodeError as e:
641
  last_err = f"invalid JSON: {e}"
 
642
  primary = (body or _primary_body_from_study_ctx(ctx) or "").strip()
643
  if len(primary) >= 12:
644
  if task == "flashcards":
@@ -650,79 +525,35 @@ Notes context:
650
  return None, last_err
651
 
652
 
653
- def _prune_mind_map(data: dict, primary_body: str, keywords: set[str]) -> dict | None:
654
- """Keep nodes grounded in notes; repair or drop bad source_quote; filter edges to kept ids."""
655
- body = (primary_body or "").strip()
656
- if len(body) < 12:
657
- return None
658
- nodes_raw = data.get("nodes") or []
659
- edges_raw = data.get("edges") or []
660
- if not isinstance(nodes_raw, list):
661
- return None
662
- kept: list[dict[str, str]] = []
663
- for n in nodes_raw:
664
- if not isinstance(n, dict):
665
- continue
666
- nid = str(n.get("id") or "").strip()
667
- label = str(n.get("label") or "").strip()
668
- quote = str(n.get("source_quote") or "").strip()
669
- if not nid or not label:
670
- continue
671
- final_quote = quote if quote and _contains_context_quote(body, quote) else ""
672
- if not final_quote:
673
- final_quote = _pick_evidence_span(body, label + " " + quote)
674
- if not final_quote or not _contains_context_quote(body, final_quote):
675
- continue
676
- kept.append({"id": nid, "label": label, "source_quote": final_quote})
677
- if len(kept) < 2:
678
- return None
679
- kept_ids = {n["id"] for n in kept}
680
- kept_edges: list[dict[str, str]] = []
681
- if isinstance(edges_raw, list):
682
- for e in edges_raw:
683
- if not isinstance(e, dict):
684
- continue
685
- s, t = str(e.get("source") or ""), str(e.get("target") or "")
686
- if s in kept_ids and t in kept_ids:
687
- kept_edges.append(
688
- {
689
- "source": s,
690
- "target": t,
691
- "label": str(e.get("label") or ""),
692
- }
693
- )
694
- return {"nodes": kept, "edges": kept_edges}
695
-
696
-
697
- def mind_map_json(context: str) -> tuple[dict | None, str | None]:
698
- ctx = context[:60000]
699
  body = _primary_body_from_study_ctx(ctx)
700
  keywords = _context_keywords(body or ctx)
701
- if len(keywords) < 6:
702
- return None, "Not enough usable note content for grounded mind map generation."
703
- prompt = f"""Build a mind map ONLY from the provided notes context.
704
- STRICT RULES:
705
- - Use only concepts present in the context.
706
- - Do NOT add outside topics or generic unrelated nodes.
707
- - Reuse notes terminology in node labels.
708
-
709
- Output a single JSON object with:
710
- "nodes": [ {{"id": string, "label": string, "source_quote": string}} ],
711
- "edges": [ {{"source": string, "target": string, "label": string}} ]
712
- Use 8-25 nodes max. IDs must match between edges and nodes. No markdown fence.
713
- "source_quote" must be a contiguous quote from PRIMARY FILE CONTENT (>= 12 chars).
714
-
715
- Notes context:
716
- {ctx}
717
- """
718
  last_err = "generation failed"
719
- for k in range(3):
720
- msg = prompt if k == 0 else (prompt + "\n\nPrevious output used unrelated topics. Regenerate strictly from notes context.")
721
  raw, err = _sarvam_chat_complete(
722
  [{"role": "user", "content": msg}],
723
  model=_model_study(),
724
- max_tokens=4096,
725
- temperature=0.05,
726
  )
727
  if err:
728
  last_err = err
@@ -730,27 +561,18 @@ Notes context:
730
  if not raw:
731
  last_err = "empty model output"
732
  continue
733
- try:
734
- data = _parse_json_loose(raw)
735
- if not isinstance(data, dict):
736
- last_err = "invalid shape"
737
- continue
738
- nodes = data.get("nodes")
739
- if not isinstance(nodes, list) or not nodes:
740
- last_err = "invalid shape"
741
- continue
742
- pruned = _prune_mind_map(data, body, keywords)
743
- if pruned is None:
744
- last_err = "Mind map was not grounded in selected notes."
745
- continue
746
- return pruned, None
747
- except json.JSONDecodeError as e:
748
- last_err = f"invalid JSON: {e}"
749
- primary = (body or _primary_body_from_study_ctx(ctx) or "").strip()
750
- if len(primary) >= 40:
751
- syn = _synthetic_mind_map(primary)
752
- if syn.get("nodes") and len(syn["nodes"]) >= 2:
753
- return syn, None
754
  return None, last_err
755
 
756
 
 
3
  import os
4
  import re
5
  import tempfile
 
6
  import zipfile
7
  from typing import Any
8
 
 
252
 
253
 
254
  def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | None]:
255
+ """Answer from notes-first context with constrained subject verification."""
256
  ctx = (context or "").strip()[:60000]
257
  q = (question or "").strip()
258
  if not q:
 
261
  {
262
  "role": "system",
263
  "content": (
264
+ "You are a brilliant subject-matter tutor helping a student prepare for exams.\n\n"
265
+ "GROUNDING RULES:\n"
266
+ "- The student's notes are your PRIMARY source of truth.\n"
267
+ "- Identify the subject/topic from the notes (e.g. Machine Learning, Linear Algebra, Operating Systems).\n"
268
+ "- ALWAYS answer the student's question β€” never refuse or say 'not in notes'.\n"
269
+ "- When the notes contain the answer, cite specific details from them.\n"
270
+ "- When the notes are incomplete, supplement with correct, textbook-level knowledge for THAT subject.\n"
271
+ " Mark such additions with 'πŸ“– Beyond notes:' so the student knows.\n"
272
+ "- NEVER drift to unrelated subjects. If asked about something outside the course scope, "
273
+ " briefly redirect: 'That's outside [subject]. Here's what your notes cover instead…'\n\n"
274
+ "TEACHING STYLE:\n"
275
+ "- Explain like a great tutor: clear, concise, with examples.\n"
276
+ "- For problem-solving: show step-by-step working.\n"
277
+ "- For tricky exam practice: generate 5-8 challenging questions with concise answer keys.\n"
278
+ "- Use bullet points and short paragraphs for readability.\n"
279
+ "- Do not claim inability to access files or notes."
280
  ),
281
  },
282
  {
283
  "role": "user",
284
  "content": (
285
+ f"**Student's question:** {q}\n\n"
286
+ f"**Notes excerpts:**\n{ctx}\n\n"
287
+ "Answer the question fully. Use notes evidence first, then subject knowledge if needed."
288
  ),
289
  },
290
  ]
 
292
  messages,
293
  model=_model_rag(),
294
  max_tokens=4096,
295
+ temperature=0.3,
296
  )
297
 
298
 
 
331
  return {k for k, _v in ranked[:250]}
332
 
333
 
334
+ def _validate_flashcards_smart(items: Any, n: int) -> list[dict[str, str]] | None:
335
+ """Accept flashcards with valid front/back; no verbatim evidence requirement."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  if not isinstance(items, list):
337
  return None
 
338
  cleaned: list[dict[str, str]] = []
339
  for it in items:
340
  if len(cleaned) >= n:
 
343
  continue
344
  front = str(it.get("front") or "").strip()
345
  back = str(it.get("back") or "").strip()
346
+ if len(front) < 5 or len(back) < 5:
 
 
 
 
347
  continue
348
+ source = str(it.get("source") or "notes").strip()
349
+ cleaned.append({"front": front, "back": back, "source": source})
350
  return cleaned if len(cleaned) >= 1 else None
351
 
352
 
353
+ def _validate_mcq_smart(items: Any, n: int) -> list[dict[str, Any]] | None:
354
+ """Accept MCQs with valid structure; no verbatim evidence requirement."""
355
  if not isinstance(items, list):
356
  return None
 
357
  cleaned: list[dict[str, Any]] = []
358
  for it in items:
359
  if len(cleaned) >= n:
 
374
  norm_opts = [str(x or "").strip() for x in opts]
375
  if any(not o for o in norm_opts):
376
  continue
377
+ source = str(it.get("source") or "notes").strip()
378
+ cleaned.append({
379
+ "question": q,
380
+ "options": norm_opts,
381
+ "answer_index": ai_i,
382
+ "source": source,
383
+ })
 
 
 
 
 
 
384
  return cleaned if len(cleaned) >= 1 else None
385
 
386
 
 
443
  return out
444
 
445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
 
447
  def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
448
  ctx = context[:60000]
449
  body = _primary_body_from_study_ctx(ctx)
450
  keywords = _context_keywords(body or ctx)
451
+ if len(keywords) < 4:
452
+ return None, "Not enough usable note content for study generation."
453
+
454
  if task == "flashcards":
455
+ prompt = (
456
+ f"You are generating exam-preparation flashcards for a student.\n\n"
457
+ f"RULES:\n"
458
+ f"1. Generate EXACTLY {n} flashcards.\n"
459
+ f"2. PRIMARY SOURCE: the notes below. Most cards (~70%) should test concepts directly from the notes.\n"
460
+ f"3. EXTENDED SOURCE: for the remaining ~30%, create cards on closely related concepts from the SAME subject "
461
+ f" that a student should know for exam preparation β€” but NEVER drift to unrelated subjects.\n"
462
+ f"4. Mix difficulty: include definitions, conceptual 'why' questions, tricky edge-case cards, "
463
+ f" and application/problem-solving cards.\n"
464
+ f"5. 'front' = question or prompt. 'back' = concise, correct answer.\n"
465
+ f"6. 'source' = 'notes' if from the notes, 'subject_knowledge' if extended.\n"
466
+ f"7. Output ONLY a JSON array. No markdown fence, no extra text.\n"
467
+ f" Each object: {{\"front\": str, \"back\": str, \"source\": str}}\n\n"
468
+ f"Notes:\n{ctx}"
469
+ )
470
  else:
471
+ prompt = (
472
+ f"You are generating challenging exam-style MCQs for a student.\n\n"
473
+ f"RULES:\n"
474
+ f"1. Generate EXACTLY {n} MCQs.\n"
475
+ f"2. PRIMARY SOURCE: the notes below. Most questions (~70%) should test concepts directly from the notes.\n"
476
+ f"3. EXTENDED SOURCE: for the remaining ~30%, create questions on closely related concepts from the SAME subject "
477
+ f" that commonly appear in exams β€” but NEVER drift to unrelated subjects.\n"
478
+ f"4. Mix difficulty: include recall, application, analysis, and tricky 'gotcha' questions.\n"
479
+ f"5. Each question must have exactly 4 plausible options. Distractors should be realistic, not obviously wrong.\n"
480
+ f"6. 'source' = 'notes' if from the notes, 'subject_knowledge' if extended.\n"
481
+ f"7. Output ONLY a JSON array. No markdown fence, no extra text.\n"
482
+ f" Each object: {{\"question\": str, \"options\": [str,str,str,str], \"answer_index\": 0-3, \"source\": str}}\n\n"
483
+ f"Notes:\n{ctx}"
484
+ )
485
+
486
  last_err = "generation failed"
487
+ for k in range(3):
488
+ msg = prompt if k == 0 else (prompt + "\n\nPrevious output had formatting issues. Regenerate valid JSON strictly following the schema.")
489
  raw, err = _sarvam_chat_complete(
490
  [{"role": "user", "content": msg}],
491
  model=_model_study(),
492
  max_tokens=8192,
493
+ temperature=0.4,
494
  )
495
  if err:
496
  last_err = err
 
505
  last_err = "Model returned JSON but not a list of study items."
506
  continue
507
  if task == "flashcards":
508
+ valid = _validate_flashcards_smart(coerced, n)
509
  else:
510
+ valid = _validate_mcq_smart(coerced, n)
511
  if valid is not None and len(valid) >= 1:
512
  return valid, None
513
+ last_err = "Model output did not match expected schema."
514
  except json.JSONDecodeError as e:
515
  last_err = f"invalid JSON: {e}"
516
+
517
  primary = (body or _primary_body_from_study_ctx(ctx) or "").strip()
518
  if len(primary) >= 12:
519
  if task == "flashcards":
 
525
  return None, last_err
526
 
527
 
528
+ def topic_summary(context: str) -> tuple[str | None, str | None]:
529
+ """Generate a concise 100-150 word summary covering all key topics from the notes."""
530
+ ctx = (context or "").strip()[:60000]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  body = _primary_body_from_study_ctx(ctx)
532
  keywords = _context_keywords(body or ctx)
533
+ if len(keywords) < 4:
534
+ return None, "Not enough usable note content for summary generation."
535
+
536
+ prompt = (
537
+ "You are a study assistant. Read the student's notes below and write a SINGLE, "
538
+ "concise summary of 100-150 words.\n\n"
539
+ "RULES:\n"
540
+ "1. Cover ALL major topics, definitions, formulas, and key takeaways from the notes.\n"
541
+ "2. Use the same terminology as the notes.\n"
542
+ "3. Structure: start with the overarching topic, then list key concepts in logical order.\n"
543
+ "4. Do NOT add content from outside the notes β€” summarize only what is provided.\n"
544
+ "5. Write in plain text paragraphs (no bullet points, no JSON, no markdown headers).\n"
545
+ "6. Aim for exactly 100-150 words. Be dense and information-rich.\n\n"
546
+ f"Notes:\n{ctx}"
547
+ )
548
+
 
549
  last_err = "generation failed"
550
+ for k in range(2):
551
+ msg = prompt if k == 0 else (prompt + "\n\nPrevious output was too long or formatted incorrectly. Write 100-150 words of plain text only.")
552
  raw, err = _sarvam_chat_complete(
553
  [{"role": "user", "content": msg}],
554
  model=_model_study(),
555
+ max_tokens=1024,
556
+ temperature=0.2,
557
  )
558
  if err:
559
  last_err = err
 
561
  if not raw:
562
  last_err = "empty model output"
563
  continue
564
+ text = raw.strip()
565
+ text = re.sub(r"^```(?:text)?\s*", "", text)
566
+ text = re.sub(r"\s*```\s*$", "", text)
567
+ if len(text) >= 40:
568
+ return text, None
569
+ last_err = "summary too short"
570
+
571
+ if body and len(body) >= 60:
572
+ sentences = [s.strip() for s in re.split(r"[.!?\n]+", body) if len(s.strip()) > 20]
573
+ fallback = ". ".join(sentences[:8])
574
+ if len(fallback) >= 40:
575
+ return fallback[:600] + ".", None
 
 
 
 
 
 
 
 
 
576
  return None, last_err
577
 
578
 
frontend/my-app/src/components/StudyPanel.jsx CHANGED
@@ -1,32 +1,7 @@
1
  import { useState, useCallback } from "react";
2
- import {
3
- ReactFlow,
4
- Background,
5
- Controls,
6
- useNodesState,
7
- useEdgesState,
8
- ReactFlowProvider,
9
- } from "@xyflow/react";
10
- import "@xyflow/react/dist/style.css";
11
  import { API_BASE } from "../config";
12
  import { authFetch } from "../auth";
13
 
14
- function graphToFlow(graph) {
15
- const rawNodes = graph?.nodes || [];
16
- const nodes = rawNodes.map((n, i) => ({
17
- id: String(n.id),
18
- position: { x: (i % 6) * 140, y: Math.floor(i / 6) * 100 },
19
- data: { label: n.label || n.id },
20
- }));
21
- const edges = (graph?.edges || []).map((e, i) => ({
22
- id: `e${i}`,
23
- source: String(e.source),
24
- target: String(e.target),
25
- label: e.label || "",
26
- }));
27
- return { initialNodes: nodes, initialEdges: edges };
28
- }
29
-
30
  export default function StudyPanel({
31
  coursesCsv = "",
32
  activeFilePath = "",
@@ -41,8 +16,7 @@ export default function StudyPanel({
41
  const [mcq, setMcq] = useState([]);
42
  const [mcqIdx, setMcqIdx] = useState(0);
43
  const [picked, setPicked] = useState(null);
44
- const [nodes, setNodes, onNodesChange] = useNodesState([]);
45
- const [edges, setEdges, onEdgesChange] = useEdgesState([]);
46
  const hasActiveFile = !!(activeFilePath || "").trim();
47
 
48
  const runFlashcards = useCallback(async () => {
@@ -117,49 +91,31 @@ export default function StudyPanel({
117
  }
118
  }, [coursesCsv, activeFilePath, activeCourseFolder]);
119
 
120
- const runMindmap = useCallback(async () => {
121
  setLoading(true);
122
  setError("");
123
- setNodes([]);
124
- setEdges([]);
125
  try {
126
  const fd = new FormData();
127
  fd.append("courses", coursesCsv);
128
  fd.append("opened_file_path", activeFilePath || "");
129
  fd.append("course_path", activeCourseFolder || "");
130
  fd.append("include_course_context", "true");
131
- fd.append("focus_query", "concept relationships");
132
  const res = await authFetch(`${API_BASE}/study/mindmap`, { method: "POST", body: fd });
133
  const data = await res.json().catch(() => ({}));
134
  if (!res.ok) throw new Error(data.error || "Failed");
135
- const nodesRaw = Array.isArray(data?.graph?.nodes) ? data.graph.nodes : [];
136
- if (!nodesRaw.length) throw new Error("No mind map returned for this file.");
137
- const graph = {
138
- ...data.graph,
139
- nodes: nodesRaw.map((n) => {
140
- if (!n || typeof n.label !== "string") return n;
141
- const sq = typeof n.source_quote === "string" ? n.source_quote.trim() : "";
142
- const label = n.label.trim();
143
- return {
144
- ...n,
145
- source_quote: sq.length >= 8 ? sq : label.slice(0, 220),
146
- };
147
- }),
148
- };
149
- const { initialNodes, initialEdges } = graphToFlow(graph);
150
- setNodes(initialNodes);
151
- setEdges(initialEdges);
152
  } catch (e) {
153
  setError(e.message || "Failed");
154
- setNodes([]);
155
- setEdges([]);
156
  } finally {
157
  setLoading(false);
158
  }
159
- }, [coursesCsv, activeFilePath, activeCourseFolder, setNodes, setEdges]);
160
 
161
  return (
162
- <ReactFlowProvider>
163
  <div className="study-panel">
164
  <div className="study-tabs">
165
  <button type="button" className={tab === "flashcards" ? "active" : ""} onClick={() => setTab("flashcards")}>
@@ -168,11 +124,12 @@ export default function StudyPanel({
168
  <button type="button" className={tab === "mcq" ? "active" : ""} onClick={() => setTab("mcq")}>
169
  Mock MCQ
170
  </button>
171
- <button type="button" className={tab === "map" ? "active" : ""} onClick={() => setTab("map")}>
172
- Mind map
173
  </button>
174
  </div>
175
  {error && <div className="study-error">{error}</div>}
 
176
  {tab === "flashcards" && (
177
  <div className="study-section">
178
  <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runFlashcards}>
@@ -182,6 +139,9 @@ export default function StudyPanel({
182
  <div className="flashcard">
183
  <div className="flashcard-index">
184
  {cardIdx + 1} / {cards.length}
 
 
 
185
  </div>
186
  <button type="button" className="flashcard-face" onClick={() => setShowBack((s) => !s)}>
187
  {showBack ? cards[cardIdx]?.back : cards[cardIdx]?.front}
@@ -198,6 +158,7 @@ export default function StudyPanel({
198
  )}
199
  </div>
200
  )}
 
201
  {tab === "mcq" && (
202
  <div className="study-section">
203
  <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runMcq}>
@@ -205,7 +166,12 @@ export default function StudyPanel({
205
  </button>
206
  {mcq.length > 0 && (
207
  <div className="mcq-block">
208
- <p className="mcq-q">{mcq[mcqIdx]?.question}</p>
 
 
 
 
 
209
  <ul className="mcq-options">
210
  {(mcq[mcqIdx]?.options || []).map((opt, i) => (
211
  <li key={i}>
@@ -217,7 +183,7 @@ export default function StudyPanel({
217
  </ul>
218
  {picked != null && (
219
  <p className="mcq-ans">
220
- {picked === mcq[mcqIdx]?.answer_index ? "Correct." : `Answer: option ${(mcq[mcqIdx]?.answer_index ?? 0) + 1}`}
221
  </p>
222
  )}
223
  <div className="flashcard-nav">
@@ -232,20 +198,19 @@ export default function StudyPanel({
232
  )}
233
  </div>
234
  )}
235
- {tab === "map" && (
236
- <div className="study-section study-map-wrap">
237
- <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runMindmap}>
238
- {loading ? "…" : "Build mind map"}
 
239
  </button>
240
- <div className="react-flow-wrap">
241
- <ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} fitView>
242
- <Background />
243
- <Controls />
244
- </ReactFlow>
245
- </div>
246
  </div>
247
  )}
248
  </div>
249
- </ReactFlowProvider>
250
  );
251
  }
 
1
  import { useState, useCallback } from "react";
 
 
 
 
 
 
 
 
 
2
  import { API_BASE } from "../config";
3
  import { authFetch } from "../auth";
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  export default function StudyPanel({
6
  coursesCsv = "",
7
  activeFilePath = "",
 
16
  const [mcq, setMcq] = useState([]);
17
  const [mcqIdx, setMcqIdx] = useState(0);
18
  const [picked, setPicked] = useState(null);
19
+ const [summary, setSummary] = useState("");
 
20
  const hasActiveFile = !!(activeFilePath || "").trim();
21
 
22
  const runFlashcards = useCallback(async () => {
 
91
  }
92
  }, [coursesCsv, activeFilePath, activeCourseFolder]);
93
 
94
+ const runSummary = useCallback(async () => {
95
  setLoading(true);
96
  setError("");
97
+ setSummary("");
 
98
  try {
99
  const fd = new FormData();
100
  fd.append("courses", coursesCsv);
101
  fd.append("opened_file_path", activeFilePath || "");
102
  fd.append("course_path", activeCourseFolder || "");
103
  fd.append("include_course_context", "true");
104
+ fd.append("focus_query", "comprehensive topic summary");
105
  const res = await authFetch(`${API_BASE}/study/mindmap`, { method: "POST", body: fd });
106
  const data = await res.json().catch(() => ({}));
107
  if (!res.ok) throw new Error(data.error || "Failed");
108
+ if (!data.summary) throw new Error("No summary returned for this file.");
109
+ setSummary(data.summary);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  } catch (e) {
111
  setError(e.message || "Failed");
112
+ setSummary("");
 
113
  } finally {
114
  setLoading(false);
115
  }
116
+ }, [coursesCsv, activeFilePath, activeCourseFolder]);
117
 
118
  return (
 
119
  <div className="study-panel">
120
  <div className="study-tabs">
121
  <button type="button" className={tab === "flashcards" ? "active" : ""} onClick={() => setTab("flashcards")}>
 
124
  <button type="button" className={tab === "mcq" ? "active" : ""} onClick={() => setTab("mcq")}>
125
  Mock MCQ
126
  </button>
127
+ <button type="button" className={tab === "summary" ? "active" : ""} onClick={() => setTab("summary")}>
128
+ Summary
129
  </button>
130
  </div>
131
  {error && <div className="study-error">{error}</div>}
132
+
133
  {tab === "flashcards" && (
134
  <div className="study-section">
135
  <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runFlashcards}>
 
139
  <div className="flashcard">
140
  <div className="flashcard-index">
141
  {cardIdx + 1} / {cards.length}
142
+ {cards[cardIdx]?.source === "subject_knowledge" && (
143
+ <span className="flashcard-badge">πŸ“– Beyond notes</span>
144
+ )}
145
  </div>
146
  <button type="button" className="flashcard-face" onClick={() => setShowBack((s) => !s)}>
147
  {showBack ? cards[cardIdx]?.back : cards[cardIdx]?.front}
 
158
  )}
159
  </div>
160
  )}
161
+
162
  {tab === "mcq" && (
163
  <div className="study-section">
164
  <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runMcq}>
 
166
  </button>
167
  {mcq.length > 0 && (
168
  <div className="mcq-block">
169
+ <p className="mcq-q">
170
+ {mcq[mcqIdx]?.question}
171
+ {mcq[mcqIdx]?.source === "subject_knowledge" && (
172
+ <span className="mcq-badge">πŸ“– Beyond notes</span>
173
+ )}
174
+ </p>
175
  <ul className="mcq-options">
176
  {(mcq[mcqIdx]?.options || []).map((opt, i) => (
177
  <li key={i}>
 
183
  </ul>
184
  {picked != null && (
185
  <p className="mcq-ans">
186
+ {picked === mcq[mcqIdx]?.answer_index ? "βœ“ Correct!" : `βœ— Answer: option ${(mcq[mcqIdx]?.answer_index ?? 0) + 1}`}
187
  </p>
188
  )}
189
  <div className="flashcard-nav">
 
198
  )}
199
  </div>
200
  )}
201
+
202
+ {tab === "summary" && (
203
+ <div className="study-section">
204
+ <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runSummary}>
205
+ {loading ? "…" : "Generate summary"}
206
  </button>
207
+ {summary && (
208
+ <div className="study-summary">
209
+ <p>{summary}</p>
210
+ </div>
211
+ )}
 
212
  </div>
213
  )}
214
  </div>
 
215
  );
216
  }
frontend/my-app/src/index.css CHANGED
@@ -498,11 +498,26 @@ html, body { height: 100%; overflow: hidden; }
498
  }
499
  .mcq-options button.picked { border-color: #007acc; }
500
  .mcq-ans { font-size: 12px; color: #89d185; }
501
- .react-flow-wrap {
502
- height: 320px;
 
 
503
  border: 1px solid #3c3c3c;
504
- border-radius: 6px;
505
- margin-top: 8px;
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  }
507
 
508
  /* ─── Left Sidebar ──────────────────────────────────────────────────────── */
 
498
  }
499
  .mcq-options button.picked { border-color: #007acc; }
500
  .mcq-ans { font-size: 12px; color: #89d185; }
501
+ .study-summary {
502
+ margin-top: 10px;
503
+ padding: 14px 16px;
504
+ background: #2d2d30;
505
  border: 1px solid #3c3c3c;
506
+ border-radius: 8px;
507
+ line-height: 1.6;
508
+ font-size: 13px;
509
+ color: #d4d4d4;
510
+ }
511
+ .study-summary p { margin: 0; }
512
+ .flashcard-badge, .mcq-badge {
513
+ display: inline-block;
514
+ margin-left: 8px;
515
+ font-size: 10px;
516
+ padding: 1px 6px;
517
+ border-radius: 4px;
518
+ background: #3c3c3c;
519
+ color: #89d185;
520
+ vertical-align: middle;
521
  }
522
 
523
  /* ─── Left Sidebar ──────────────────────────────────────────────────────── */