Thanmay Mohandas Das commited on
Commit
31a8cef
·
unverified ·
2 Parent(s): 2407d8334d2be5

Merge pull request #12 from tAnboyy/artifact/quiz

Browse files
Files changed (2) hide show
  1. app.py +132 -15
  2. backend/quiz_service.py +30 -13
app.py CHANGED
@@ -488,19 +488,19 @@ def _safe_generate_podcast_audio(notebook_id, script, profile: gr.OAuthProfile |
488
  return f"Error generating podcast audio: {error}", None
489
 
490
  # Quiz Handlers
491
- def _get_notebook_pdfs(notebook_id):
492
- if not notebook_id:
 
493
  return gr.update(choices=[], value=None, visible=False)
494
- from backend.db import supabase
495
- result = (
496
- supabase.table("chunks")
497
- .select("source_id")
498
- .eq("notebook_id", notebook_id)
499
- .execute()
500
- )
501
- pdfs = list({r["source_id"] for r in (result.data or []) if r["source_id"].endswith(".pdf")})
502
  return gr.update(choices=pdfs, value=pdfs[0] if pdfs else None, visible=True)
503
 
 
504
  def _generate_quiz(notebook_id, source_type, pdf_source_id, profile: gr.OAuthProfile | None):
505
  from backend.quiz_service import generate_quiz
506
 
@@ -513,6 +513,9 @@ def _generate_quiz(notebook_id, source_type, pdf_source_id, profile: gr.OAuthPro
513
  type_map = {"Text": "txt", "PDF": "pdf", "URL": "url", "All": "all"}
514
  source_type_key = type_map.get(source_type, "all")
515
 
 
 
 
516
  try:
517
  result = generate_quiz(notebook_id, source_type=source_type_key, source_id=pdf_source_id)
518
  questions = result["questions"]
@@ -526,6 +529,7 @@ def _generate_quiz(notebook_id, source_type, pdf_source_id, profile: gr.OAuthPro
526
  elif q["type"] == "true_false":
527
  updates += [gr.update(visible=True), gr.update(value=q_label), gr.update(choices=["True", "False"], value=None, visible=True), gr.update(value="", visible=False)]
528
  else:
 
529
  updates += [gr.update(visible=True), gr.update(value=q_label), gr.update(choices=[], value=None, visible=False), gr.update(value="", visible=True)]
530
  else:
531
  updates += [gr.update(visible=False), gr.update(value=""), gr.update(choices=[], value=None, visible=False), gr.update(value="", visible=False)]
@@ -605,6 +609,60 @@ def _on_chat_submit(query, notebook_id, chat_history, profile: gr.OAuthProfile |
605
  except Exception as e:
606
  return "", chat_history, f"Error: {e}"
607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
  with gr.Blocks(
609
  title="NotebookLM Clone - Notebooks",
610
  theme=theme,
@@ -858,23 +916,35 @@ with gr.Blocks(
858
  # Quiz Section
859
  gr.Markdown("---")
860
  gr.Markdown("## Generate Quiz")
861
- gr.Markdown("Select a source type then generate a quiz.")
862
 
863
  quiz_source_type = gr.Radio(
864
  choices=["Text", "PDF", "URL", "All"],
865
  value="All",
866
  label="Source type",
867
  )
 
 
868
  quiz_pdf_dd = gr.Dropdown(
869
- label="Select PDF",
870
  choices=[],
871
  value=None,
872
  visible=False,
873
  )
 
 
 
 
 
 
 
 
 
 
874
  generate_quiz_btn = gr.Button("Generate Quiz", variant="primary")
875
- quiz_status = gr.Markdown("")
876
- quiz_state = gr.State([])
877
 
 
 
 
878
  quiz_components = []
879
  for i in range(5):
880
  with gr.Group(visible=False) as q_group:
@@ -886,6 +956,33 @@ with gr.Blocks(
886
  submit_quiz_btn = gr.Button("Submit Answers", variant="secondary", visible=False)
887
  quiz_results = gr.Markdown("")
888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889
  submit_btn.click(
890
  _do_upload,
891
  inputs=[txt_input, txt_title, selected_notebook_id],
@@ -921,17 +1018,37 @@ with gr.Blocks(
921
  )
922
 
923
  quiz_source_type.change(
924
- lambda t, nb: _get_notebook_pdfs(nb) if t == "PDF" else gr.update(visible=False, choices=[], value=None),
925
  inputs=[quiz_source_type, selected_notebook_id],
926
  outputs=[quiz_pdf_dd],
 
 
 
 
 
 
927
  )
928
 
 
 
 
 
 
 
 
 
 
929
  quiz_all_outputs = [quiz_status, quiz_state]
930
  for c in quiz_components:
931
  quiz_all_outputs += [c["group"], c["text"], c["radio"], c["textbox"]]
932
  quiz_all_outputs += [submit_quiz_btn, quiz_results]
933
 
934
  generate_quiz_btn.click(
 
 
 
 
 
935
  _generate_quiz,
936
  inputs=[selected_notebook_id, quiz_source_type, quiz_pdf_dd],
937
  outputs=quiz_all_outputs,
 
488
  return f"Error generating podcast audio: {error}", None
489
 
490
  # Quiz Handlers
491
+ def _get_notebook_pdfs(notebook_id, profile: gr.OAuthProfile | None):
492
+ user_id = _user_id(profile)
493
+ if not user_id or not notebook_id:
494
  return gr.update(choices=[], value=None, visible=False)
495
+
496
+ target_dir = Path("data") / "uploads" / user_id / str(notebook_id)
497
+ if not target_dir.exists():
498
+ return gr.update(choices=[], value=None, visible=False)
499
+
500
+ pdfs = sorted([p.name for p in target_dir.glob("*.pdf")])
 
 
501
  return gr.update(choices=pdfs, value=pdfs[0] if pdfs else None, visible=True)
502
 
503
+
504
  def _generate_quiz(notebook_id, source_type, pdf_source_id, profile: gr.OAuthProfile | None):
505
  from backend.quiz_service import generate_quiz
506
 
 
513
  type_map = {"Text": "txt", "PDF": "pdf", "URL": "url", "All": "all"}
514
  source_type_key = type_map.get(source_type, "all")
515
 
516
+ if source_type_key == "pdf" and not pdf_source_id:
517
+ return "Pick a PDF first.", [], *([gr.update(visible=False)] * 5 * 4), gr.update(visible=False), ""
518
+
519
  try:
520
  result = generate_quiz(notebook_id, source_type=source_type_key, source_id=pdf_source_id)
521
  questions = result["questions"]
 
529
  elif q["type"] == "true_false":
530
  updates += [gr.update(visible=True), gr.update(value=q_label), gr.update(choices=["True", "False"], value=None, visible=True), gr.update(value="", visible=False)]
531
  else:
532
+ # change this line for short_answer:
533
  updates += [gr.update(visible=True), gr.update(value=q_label), gr.update(choices=[], value=None, visible=False), gr.update(value="", visible=True)]
534
  else:
535
  updates += [gr.update(visible=False), gr.update(value=""), gr.update(choices=[], value=None, visible=False), gr.update(value="", visible=False)]
 
609
  except Exception as e:
610
  return "", chat_history, f"Error: {e}"
611
 
612
+ def _get_quiz_pdfs(source_type, notebook_id):
613
+ if source_type != "PDF":
614
+ return gr.update(visible=False, choices=[], value=None)
615
+ if not notebook_id:
616
+ return gr.update(visible=False, choices=[], value=None)
617
+
618
+ # Search across all users for this notebook_id
619
+ base = Path("data") / "uploads"
620
+ pdfs = []
621
+ if base.exists():
622
+ for user_dir in base.iterdir():
623
+ nb_dir = user_dir / str(notebook_id)
624
+ if nb_dir.exists():
625
+ pdfs = sorted([p.name for p in nb_dir.glob("*.pdf")])
626
+ break
627
+
628
+ print(f"DEBUG quiz pdfs found: {pdfs}")
629
+ return gr.update(visible=True, choices=pdfs, value=pdfs[0] if pdfs else None)
630
+
631
+ def _quiz_pdf_dropdown_update(source_type, notebook_id, profile: gr.OAuthProfile | None):
632
+ if source_type != "PDF":
633
+ return gr.update(visible=False, choices=[], value=None)
634
+
635
+ if not notebook_id:
636
+ return gr.update(visible=True, choices=[], value=None)
637
+
638
+ user_id = _user_id(profile)
639
+
640
+ # Try with user_id first (production)
641
+ if user_id:
642
+ target_dir = Path("data") / "uploads" / user_id / str(notebook_id)
643
+ if target_dir.exists():
644
+ pdfs = sorted([p.name for p in target_dir.glob("*.pdf")])
645
+ return gr.update(visible=True, choices=pdfs, value=pdfs[0] if pdfs else None)
646
+
647
+ # Fallback for local dev (no OAuth): scan all user folders
648
+ base = Path("data") / "uploads"
649
+ if base.exists():
650
+ for user_dir in base.iterdir():
651
+ if not user_dir.is_dir():
652
+ continue
653
+ nb_dir = user_dir / str(notebook_id)
654
+ if nb_dir.exists():
655
+ pdfs = sorted([p.name for p in nb_dir.glob("*.pdf")])
656
+ print(f"DEBUG (local fallback): notebook_id={notebook_id}, pdfs={pdfs}")
657
+ return gr.update(visible=True, choices=pdfs, value=pdfs[0] if pdfs else None)
658
+
659
+ return gr.update(visible=True, choices=[], value=None)
660
+
661
+ def _generate_btn_update(source_type, pdf_name):
662
+ if source_type == "PDF":
663
+ return gr.update(interactive=bool(pdf_name))
664
+ return gr.update(interactive=True)
665
+
666
  with gr.Blocks(
667
  title="NotebookLM Clone - Notebooks",
668
  theme=theme,
 
916
  # Quiz Section
917
  gr.Markdown("---")
918
  gr.Markdown("## Generate Quiz")
 
919
 
920
  quiz_source_type = gr.Radio(
921
  choices=["Text", "PDF", "URL", "All"],
922
  value="All",
923
  label="Source type",
924
  )
925
+
926
+
927
  quiz_pdf_dd = gr.Dropdown(
928
+ label="Select PDF (select a notebook first if empty)",
929
  choices=[],
930
  value=None,
931
  visible=False,
932
  )
933
+
934
+ demo.load(_initial_load, inputs=None, outputs=[nb_state, selected_notebook_id, status] + row_outputs, api_name=False)
935
+ demo.load(_list_uploaded_pdfs, inputs=[selected_notebook_id], outputs=[uploaded_pdf_dd], api_name=False)
936
+ demo.load(
937
+ _quiz_pdf_dropdown_update,
938
+ inputs=[quiz_source_type, selected_notebook_id],
939
+ outputs=[quiz_pdf_dd],
940
+ api_name=False,
941
+ )
942
+
943
  generate_quiz_btn = gr.Button("Generate Quiz", variant="primary")
 
 
944
 
945
+ quiz_status = gr.Markdown("")
946
+ quiz_state = gr.State([])
947
+
948
  quiz_components = []
949
  for i in range(5):
950
  with gr.Group(visible=False) as q_group:
 
956
  submit_quiz_btn = gr.Button("Submit Answers", variant="secondary", visible=False)
957
  quiz_results = gr.Markdown("")
958
 
959
+ for i in range(MAX_NOTEBOOKS):
960
+ select_btn = row_components[i]["select"]
961
+ def _on_select(i=i):
962
+ return "Selected notebook updated. Use this for chat/ingestion."
963
+
964
+ select_btn.click(
965
+ _select_notebook,
966
+ inputs=[gr.State(i), nb_state],
967
+ outputs=[selected_notebook_id],
968
+ api_name=False,
969
+ ).then(
970
+ _on_select, None, [status]
971
+ ).then(
972
+ _list_uploaded_pdfs, inputs=[selected_notebook_id], outputs=[uploaded_pdf_dd]
973
+ ).then(
974
+ _quiz_pdf_dropdown_update,
975
+ inputs=[quiz_source_type, selected_notebook_id],
976
+ outputs=[quiz_pdf_dd],
977
+ api_name=False,
978
+ ).then(
979
+ _generate_btn_update,
980
+ inputs=[quiz_source_type, quiz_pdf_dd],
981
+ outputs=[generate_quiz_btn],
982
+ api_name=False,
983
+ )
984
+
985
+
986
  submit_btn.click(
987
  _do_upload,
988
  inputs=[txt_input, txt_title, selected_notebook_id],
 
1018
  )
1019
 
1020
  quiz_source_type.change(
1021
+ _quiz_pdf_dropdown_update,
1022
  inputs=[quiz_source_type, selected_notebook_id],
1023
  outputs=[quiz_pdf_dd],
1024
+ api_name=False,
1025
+ ).then(
1026
+ _generate_btn_update,
1027
+ inputs=[quiz_source_type, quiz_pdf_dd],
1028
+ outputs=[generate_quiz_btn],
1029
+ api_name=False,
1030
  )
1031
 
1032
+ quiz_pdf_dd.change(
1033
+ _generate_btn_update,
1034
+ inputs=[quiz_source_type, quiz_pdf_dd],
1035
+ outputs=[generate_quiz_btn],
1036
+ api_name=False,
1037
+ )
1038
+
1039
+
1040
+
1041
  quiz_all_outputs = [quiz_status, quiz_state]
1042
  for c in quiz_components:
1043
  quiz_all_outputs += [c["group"], c["text"], c["radio"], c["textbox"]]
1044
  quiz_all_outputs += [submit_quiz_btn, quiz_results]
1045
 
1046
  generate_quiz_btn.click(
1047
+ lambda: gr.update(value="Generating quiz..."),
1048
+ inputs=[],
1049
+ outputs=[quiz_status],
1050
+ api_name=False,
1051
+ ).then(
1052
  _generate_quiz,
1053
  inputs=[selected_notebook_id, quiz_source_type, quiz_pdf_dd],
1054
  outputs=quiz_all_outputs,
backend/quiz_service.py CHANGED
@@ -88,9 +88,12 @@ def generate_quiz(notebook_id: str, source_type: str = "all", source_id: str = N
88
  chunks = _get_chunks_by_source_id(notebook_id, source_id)
89
  elif source_type in ("txt", "url"):
90
  chunks = _get_chunks_by_type(notebook_id, source_type)
 
 
 
91
  else:
92
  chunks = _get_chunks_for_notebook(notebook_id)
93
-
94
  print(f"Found {len(chunks)} chunks for source_type={source_type}")
95
  if not chunks:
96
  raise ValueError("No chunks found for this source. Please add sources first.")
@@ -137,33 +140,47 @@ def _get_chunks_by_source_id(notebook_id: str, source_id: str, limit: int = 10)
137
 
138
 
139
  def _get_chunks_by_type(notebook_id: str, source_type: str, limit: int = 10) -> list[str]:
140
- """Fetch chunks filtered by source type (txt = UUID source_ids, url = url_ prefix)."""
141
  result = (
142
  supabase.table("chunks")
143
- .select("content, source_id")
144
  .eq("notebook_id", notebook_id)
 
145
  .execute()
146
  )
147
  rows = result.data or []
148
  if source_type == "url":
149
- filtered = [r["content"] for r in rows if r["source_id"].startswith("url_")]
150
- else: # txt — UUID source_ids
151
- filtered = [r["content"] for r in rows if not r["source_id"].startswith("url_") and not r["source_id"].endswith(".pdf")]
152
- return filtered[:limit]
 
 
 
 
 
 
153
 
154
 
155
  def _parse_quiz(raw: str) -> list[dict]:
156
  print(f"RAW OUTPUT:\n{raw}\n")
157
- # Find the start of the JSON array
158
  start = raw.find('[')
159
  if start == -1:
160
  raise ValueError("No JSON array found in model output.")
161
 
162
  json_str = raw[start:].strip()
163
 
164
- # If closing bracket is missing, add it
165
- if not json_str.endswith(']'):
166
- # Remove trailing comma if present
167
- json_str = json_str.rstrip().rstrip(',') + '\n]'
 
 
 
 
 
 
 
 
 
168
 
169
- return json.loads(json_str)
 
88
  chunks = _get_chunks_by_source_id(notebook_id, source_id)
89
  elif source_type in ("txt", "url"):
90
  chunks = _get_chunks_by_type(notebook_id, source_type)
91
+ if not chunks:
92
+ source_label = "text" if source_type == "txt" else "URL"
93
+ raise ValueError(f"No {source_label} sources found. Please add a {source_label} source first.")
94
  else:
95
  chunks = _get_chunks_for_notebook(notebook_id)
96
+
97
  print(f"Found {len(chunks)} chunks for source_type={source_type}")
98
  if not chunks:
99
  raise ValueError("No chunks found for this source. Please add sources first.")
 
140
 
141
 
142
  def _get_chunks_by_type(notebook_id: str, source_type: str, limit: int = 10) -> list[str]:
 
143
  result = (
144
  supabase.table("chunks")
145
+ .select("content, source_id, created_at")
146
  .eq("notebook_id", notebook_id)
147
+ .order("created_at", desc=True)
148
  .execute()
149
  )
150
  rows = result.data or []
151
  if source_type == "url":
152
+ filtered = [r for r in rows if r["source_id"].startswith("url_")]
153
+ else: # txt
154
+ filtered = [r for r in rows if not r["source_id"].startswith("url_") and not r["source_id"].endswith(".pdf")]
155
+
156
+ if not filtered:
157
+ return []
158
+
159
+ # Use only the most recent source_id
160
+ latest_source_id = filtered[0]["source_id"]
161
+ return [r["content"] for r in filtered if r["source_id"] == latest_source_id][:limit]
162
 
163
 
164
  def _parse_quiz(raw: str) -> list[dict]:
165
  print(f"RAW OUTPUT:\n{raw}\n")
 
166
  start = raw.find('[')
167
  if start == -1:
168
  raise ValueError("No JSON array found in model output.")
169
 
170
  json_str = raw[start:].strip()
171
 
172
+ # Try parsing as-is first
173
+ try:
174
+ return json.loads(json_str)
175
+ except json.JSONDecodeError:
176
+ pass
177
+
178
+ # Try fixing truncated JSON by extracting complete objects only
179
+ objects = re.findall(r'\{[^{}]+\}', json_str, re.DOTALL)
180
+ if objects:
181
+ try:
182
+ return json.loads('[' + ','.join(objects) + ']')
183
+ except json.JSONDecodeError:
184
+ pass
185
 
186
+ raise ValueError("Could not parse quiz JSON from model output.")