File size: 60,189 Bytes
157fe17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {"name": "ipython", "version": 3},
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "version": "3.10.0"
  }
 },
 "cells": [

  {
   "cell_type": "markdown",
   "id": "md-title",
   "metadata": {},
   "source": [
    "# RAGBench Knowledge Base Builder β€” v2\n",
    "\n",
    "Builds **FAISS + BM25 + chunk/doc artefacts** for every\n",
    "`(dataset Γ— embedding_model Γ— chunk_config)` combination and uploads each\n",
    "to a Hugging Face dataset repo so the Gradio app can download on demand.\n",
    "\n",
    "## Design decisions\n",
    "\n",
    "| Decision | Choice | Rationale |\n",
    "|---|---|---|\n",
    "| Corpus scope (v1) | `test` split only | 12 datasets Γ— models Γ— chunk configs is significant compute; test split is sufficient for comparative evaluation |\n",
    "| Evaluation setting | **Closed retrieval** | Every test question's relevant document is guaranteed in the index; metrics measure *relative quality* across configs, not open-corpus absolute recall |\n",
    "| Future expansion | `all_splits` rebuild | Change `corpus_scope` β†’ new `index_id` automatically; old indices untouched |\n",
    "| Existing indices | Deleted + rebuilt | Prior indices had an incomplete cache key and silent truncation (chunk_size > model max_seq_length) |\n",
    "\n",
    "## Key improvements over v1\n",
    "\n",
    "1. **Parameterised corpus scope** β€” `corpus_scope` field drives the loader; upgrading to `all_splits` later needs only one field change.\n",
    "2. **Pre-build validation** β€” chunk sizes are checked against every model's effective `max_seq_length` before any encoding starts.\n",
    "3. **Query / passage prefixes** β€” BGE and other asymmetric models require different text formats for passages vs queries; both are stored in every combo and in `meta.json`.\n",
    "4. **Chunking strategy dispatch** β€” `chunking_strategy` now selects a real implementation (`passthrough`, `recursive`); unknown strategies raise immediately.\n",
    "5. **Complete cache key** β€” includes schema version, corpus scope, model revision, prefixes, and strategy; two different indices can never share an `index_id`.\n",
    "6. **Improved BM25 tokenisation** β€” regex word splitting separates punctuation from legal terms (e.g. `clause,` β†’ `clause`).\n",
    "7. **Richer `meta.json`** β€” stores every field needed to reproduce or audit the index.\n",
    "\n",
    "## Colab workflow\n",
    "\n",
    "1. Set `HF_TOKEN` in the Colab secrets panel (πŸ”‘ left sidebar).\n",
    "2. Edit `HF_REPO` in **Cell 2**.\n",
    "3. Run **Cells 1–5** once per session (install + auth + helpers).\n",
    "4. Run **Cell 6** (validation) β€” confirms all combos are safe before any compute.\n",
    "5. Run **Cell 7** to see which combos are done vs pending.\n",
    "6. Set `COMBO_IDX` in **Cell 8** and run **Cells 8–12** to build and upload one combo.\n",
    "7. Repeat step 6 in a fresh session for the next pending combo.\n",
    "\n",
    "Or run **Cell 13** to build all pending combos automatically in one session."
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-install",
   "metadata": {},
   "source": [
    "## Cell 1 β€” Install dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-install",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -q datasets transformers sentence-transformers faiss-cpu rank_bm25 langchain-text-splitters huggingface_hub pyarrow pandas numpy"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-config",
   "metadata": {},
   "source": [
    "## Cell 2 β€” Configuration\n",
    "\n",
    "### Corpus scope\n",
    "\n",
    "RAGBench provides train / validation / test splits of *question–answer–context triples*,\n",
    "not of a separate document corpus. In a production RAG system all documents are indexed;\n",
    "queries are evaluated against that one index regardless of which split they came from.\n",
    "\n",
    "For this first build (`corpus_scope = \"test\"`) we index only the documents attached to\n",
    "test-split examples. This creates a **closed retrieval** setting: every test question's\n",
    "relevant document is guaranteed to be in the index. Retrieval metrics (Hit@k, nDCG@k)\n",
    "therefore measure *relative quality* across configurations, not open-corpus absolute recall.\n",
    "This is documented explicitly in every `meta.json` artifact.\n",
    "\n",
    "**Upgrade path:** change `corpus_scope` to `\"all_splits\"` in any combo. The updated\n",
    "`make_cache_key()` will produce a different `index_id`; old test-scope indices stay\n",
    "untouched in the HF repo and both are listed in `index_config.json`.\n",
    "\n",
    "### Combo schema\n",
    "\n",
    "| Field | Purpose |\n",
    "|---|---|\n",
    "| `corpus_scope` | Which splits to load for the document corpus (`test` / `train` / `all_splits`) |\n",
    "| `embedding_model` | HuggingFace model ID |\n",
    "| `model_revision` | Git ref β€” pins the model checkpoint for reproducibility |\n",
    "| `query_prefix` | Instruction prepended to queries **at runtime** by the retriever |\n",
    "| `passage_prefix` | Instruction prepended to passages **during indexing** |\n",
    "| `chunking_strategy` | `passthrough`, `recursive`, or `parent_child` |\n",
    "| `chunk_size` | Target chunk size in tokens (0 = not applicable for passthrough) |\n",
    "| `chunk_overlap` | Overlap between adjacent chunks in tokens |\n",
    "\n",
    "### Asymmetric model prefixes\n",
    "\n",
    "Some embedding models use asymmetric formatting:\n",
    "- **BGE v1.5** β€” short instruction on retrieval queries; no prefix on passages.\n",
    "- **E5** β€” `query: ` on queries, `passage: ` on passages.\n",
    "- **GTE-ModernBERT / MiniLM / MPNet** β€” symmetric raw-text embedding (empty prefixes).\n",
    "\n",
    "The `passage_prefix` is applied during index construction (this notebook).\n",
    "The `query_prefix` must be applied in the app's `HybridRetriever.dense_search()`\n",
    "and read from `meta.json` β€” **both must change together**.\n",
    "\n",
    "### Chunking strategies\n",
    "\n",
    "- **`passthrough`** β€” each source passage becomes one chunk. Best for short retrieved\n",
    "  passages (e.g. CovidQA ~100 words) that already fit within any model's limit.\n",
    "- **`recursive`** β€” tokenizer-aware `RecursiveCharacterTextSplitter`. `chunk_size` is in\n",
    "  the model's own token space and validated against `model.max_seq_length` before building.\n",
    "- **`parent_child`** β€” small retrieval children with a larger parent stored for generation.\n",
    "  Not yet implemented; requires retrieval + generation pipeline changes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-config",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ── Schema version ─────────────────────────────────────────────────────────────\n",
    "# Increment when any build-logic change would produce a different index from the\n",
    "# same combo settings. Forces all affected combos to a new index_id.\n",
    "SCHEMA_VERSION = 2\n",
    "\n",
    "HF_REPO = \"your-username/rag-capstone-indices\"  # <── change to your HF repo\n",
    "\n",
    "SPLIT_MAP = {\n",
    "    \"test\":       [\"test\"],\n",
    "    \"train\":      [\"train\"],\n",
    "    \"all_splits\": [\"train\", \"validation\", \"test\"],\n",
    "}\n",
    "\n",
    "ARTIFACT_FILES = [\n",
    "    \"faiss.index\", \"embeddings.npy\", \"bm25.pkl\",\n",
    "    \"chunks.parquet\", \"docs.parquet\", \"meta.json\",\n",
    "]\n",
    "\n",
    "# ── CovidQA combos β€” biomedical domain ────────────────────────────────────────\n",
    "# Source passages are already short (~100 words from CORD-19 retrieval).\n",
    "# Strategy: passthrough β€” each passage becomes exactly one chunk.\n",
    "# chunk_size=0 / chunk_overlap=0 are sentinels meaning \"not applicable\".\n",
    "COVIDQA_COMBOS = [\n",
    "    {\n",
    "        \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n",
    "        \"display_name\": \"CovidQA (Biomedical)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n",
    "        \"embedding_display_name\": \"MiniLM L6 v2\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"passthrough\",\n",
    "        \"chunk_size\": 0, \"chunk_overlap\": 0,\n",
    "    },\n",
    "    {\n",
    "        \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n",
    "        \"display_name\": \"CovidQA (Biomedical)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"BAAI/bge-base-en-v1.5\",\n",
    "        \"embedding_display_name\": \"BGE base en v1.5\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"Represent this sentence for searching relevant passages: \",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"passthrough\",\n",
    "        \"chunk_size\": 0, \"chunk_overlap\": 0,\n",
    "    },\n",
    "    {\n",
    "        \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n",
    "        \"display_name\": \"CovidQA (Biomedical)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n",
    "        \"embedding_display_name\": \"GTE ModernBERT base\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"passthrough\",\n",
    "        \"chunk_size\": 0, \"chunk_overlap\": 0,\n",
    "    },\n",
    "    {\n",
    "        \"dataset\": \"covidqa\", \"domain\": \"biomedical\",\n",
    "        \"display_name\": \"CovidQA (Biomedical)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"sentence-transformers/all-mpnet-base-v2\",\n",
    "        \"embedding_display_name\": \"MPNet base v2\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"passthrough\",\n",
    "        \"chunk_size\": 0, \"chunk_overlap\": 0,\n",
    "    },\n",
    "]\n",
    "\n",
    "# ── CUAD combos β€” legal domain ─────────────────────────────────────────────────\n",
    "# Full commercial contracts (1–100 pages). Recursive chunking required.\n",
    "# All chunk sizes stay within each model's max_seq_length (validated in Cell 6).\n",
    "CUAD_COMBOS = [\n",
    "    # Tier 1: fast baseline β€” MiniLM (max_seq_length=256)\n",
    "    {\n",
    "        \"dataset\": \"cuad\", \"domain\": \"legal\",\n",
    "        \"display_name\": \"CUAD (Legal Contracts)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n",
    "        \"embedding_display_name\": \"MiniLM L6 v2\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"recursive\",\n",
    "        \"chunk_size\": 256, \"chunk_overlap\": 32,\n",
    "    },\n",
    "    # Tier 2: cross-domain baseline β€” MPNet (max_seq_length=384)\n",
    "    {\n",
    "        \"dataset\": \"cuad\", \"domain\": \"legal\",\n",
    "        \"display_name\": \"CUAD (Legal Contracts)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"sentence-transformers/all-mpnet-base-v2\",\n",
    "        \"embedding_display_name\": \"MPNet base v2\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"recursive\",\n",
    "        \"chunk_size\": 384, \"chunk_overlap\": 64,\n",
    "    },\n",
    "    # Tier 3: strong dense retrieval β€” BGE-large (max_seq_length=512, asymmetric)\n",
    "    {\n",
    "        \"dataset\": \"cuad\", \"domain\": \"legal\",\n",
    "        \"display_name\": \"CUAD (Legal Contracts)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"BAAI/bge-large-en-v1.5\",\n",
    "        \"embedding_display_name\": \"BGE large en v1.5\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"Represent this sentence for searching relevant passages: \",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"recursive\",\n",
    "        \"chunk_size\": 512, \"chunk_overlap\": 96,\n",
    "    },\n",
    "    # Tier 4: modern long-context β€” GTE-ModernBERT (max_seq_length=8192), 512 tokens\n",
    "    {\n",
    "        \"dataset\": \"cuad\", \"domain\": \"legal\",\n",
    "        \"display_name\": \"CUAD (Legal Contracts)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n",
    "        \"embedding_display_name\": \"GTE ModernBERT base\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"recursive\",\n",
    "        \"chunk_size\": 512, \"chunk_overlap\": 96,\n",
    "    },\n",
    "    # Tier 4b: long-clause experiment β€” GTE-ModernBERT, 1024 tokens\n",
    "    {\n",
    "        \"dataset\": \"cuad\", \"domain\": \"legal\",\n",
    "        \"display_name\": \"CUAD (Legal Contracts)\",\n",
    "        \"corpus_scope\": \"test\",\n",
    "        \"embedding_model\": \"Alibaba-NLP/gte-modernbert-base\",\n",
    "        \"embedding_display_name\": \"GTE ModernBERT base (long clause)\",\n",
    "        \"model_revision\": \"main\",\n",
    "        \"query_prefix\": \"\",\n",
    "        \"passage_prefix\": \"\",\n",
    "        \"chunking_strategy\": \"recursive\",\n",
    "        \"chunk_size\": 1024, \"chunk_overlap\": 128,\n",
    "    },\n",
    "]\n",
    "\n",
    "# ── Other RAGBench datasets ────────────────────────────────────────────────────\n",
    "# Add combos here for the remaining RAGBench datasets.\n",
    "# First verify the HF config name:\n",
    "#   load_dataset(\"rungalileo/ragbench\", \"<name>\", split=\"test\")\n",
    "#\n",
    "# Most RAGBench datasets are short retrieved passages β†’ use passthrough.\n",
    "# Switch to recursive only if source passages exceed the model's max_seq_length.\n",
    "#\n",
    "# Minimum baseline per dataset: MiniLM (floor) + one stronger model.\n",
    "#\n",
    "# Example for FiQA:\n",
    "# {\n",
    "#     \"dataset\": \"fiqa\", \"domain\": \"financial\",\n",
    "#     \"display_name\": \"FiQA (Financial)\",\n",
    "#     \"corpus_scope\": \"test\",\n",
    "#     \"embedding_model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n",
    "#     \"embedding_display_name\": \"MiniLM L6 v2\",\n",
    "#     \"model_revision\": \"main\",\n",
    "#     \"query_prefix\": \"\", \"passage_prefix\": \"\",\n",
    "#     \"chunking_strategy\": \"passthrough\",\n",
    "#     \"chunk_size\": 0, \"chunk_overlap\": 0,\n",
    "# },\n",
    "OTHER_COMBOS = []  # <── extend with other RAGBench dataset combos\n",
    "\n",
    "COMBOS = COVIDQA_COMBOS + CUAD_COMBOS + OTHER_COMBOS\n",
    "\n",
    "print(f\"Repo     : {HF_REPO}\")\n",
    "print(f\"CovidQA  : {len(COVIDQA_COMBOS)} combos\")\n",
    "print(f\"CUAD     : {len(CUAD_COMBOS)} combos\")\n",
    "print(f\"Other    : {len(OTHER_COMBOS)} combos\")\n",
    "print(f\"Total    : {len(COMBOS)} combos\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-auth",
   "metadata": {},
   "source": [
    "## Cell 3 β€” Authenticate with Hugging Face\n",
    "\n",
    "Store your token via the πŸ”‘ Colab secrets panel (key name `HF_TOKEN`).\n",
    "Never paste a token directly in a cell you might share or commit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-auth",
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import HfApi, login\n",
    "\n",
    "try:\n",
    "    from google.colab import userdata\n",
    "    HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
    "except Exception:\n",
    "    HF_TOKEN = \"\"  # <── paste token here ONLY for quick local tests, never commit\n",
    "\n",
    "login(token=HF_TOKEN, add_to_git_credential=False)\n",
    "api = HfApi()\n",
    "\n",
    "api.create_repo(repo_id=HF_REPO, repo_type=\"dataset\", exist_ok=True)\n",
    "print(f\"Repo ready: https://huggingface.co/datasets/{HF_REPO}\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-helpers",
   "metadata": {},
   "source": [
    "## Cell 4 β€” Helper functions\n",
    "\n",
    "### Cache key design\n",
    "\n",
    "`make_cache_key()` hashes **every field that materially changes the index**:\n",
    "`schema_version`, `dataset`, `corpus_scope`, `embedding_model`, `model_revision`,\n",
    "`query_prefix`, `passage_prefix`, `chunking_strategy`, `chunk_size`, `chunk_overlap`.\n",
    "\n",
    "Any change to any of these fields produces a new `index_id`. This means:\n",
    "- Fixing a bug β†’ increment `SCHEMA_VERSION` β†’ all combos get new IDs automatically.\n",
    "- Expanding corpus β†’ change `corpus_scope` β†’ new ID, old index untouched.\n",
    "- Adding a prefix β†’ new ID, no silent overwrites.\n",
    "\n",
    "### Corpus loading\n",
    "\n",
    "`load_ragbench()` accepts a `corpus_scope` string and loads the appropriate splits\n",
    "from `SPLIT_MAP`. Multiple splits are concatenated before deduplication so the\n",
    "knowledge base contains only unique documents.\n",
    "\n",
    "### Chunking dispatch\n",
    "\n",
    "`chunk_documents()` is a dispatcher: it reads `combo['chunking_strategy']` and calls\n",
    "the matching private function. An unknown strategy raises `ValueError` immediately\n",
    "so no compute is wasted. Currently implemented:\n",
    "\n",
    "- `passthrough` β€” each source document becomes exactly one chunk (no splitting).\n",
    "- `recursive` β€” tokenizer-aware `RecursiveCharacterTextSplitter`. Uses the embedding\n",
    "  model's own tokenizer so `chunk_size` is in the same token space as `max_seq_length`.\n",
    "\n",
    "### Dense index with passage prefix\n",
    "\n",
    "`build_dense_index()` prepends `passage_prefix` to every chunk before encoding.\n",
    "Embeddings are L2-normalised so inner-product search is equivalent to cosine similarity.\n",
    "The matching `query_prefix` must be applied in the app's retriever at query time.\n",
    "\n",
    "### BM25 tokenisation\n",
    "\n",
    "`build_bm25()` uses `re.findall(r\"\\w+\", text.lower())` instead of `str.split()`.\n",
    "This separates punctuation from tokens β€” important for legal text where terms like\n",
    "`clause,` or `Β§3.1` would otherwise not match their clean forms.\n",
    "\n",
    "### Artifact schema (meta.json)\n",
    "\n",
    "Every uploaded artefact folder includes a `meta.json` with the full provenance:\n",
    "schema version, corpus scope, model revision, effective sequence limit, both prefixes,\n",
    "chunking parameters, normalisation, similarity metric, counts, and build timestamp."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-helpers",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "import io\n",
    "import json\n",
    "import pickle\n",
    "import re\n",
    "import shutil\n",
    "from datetime import datetime, timezone\n",
    "from pathlib import Path\n",
    "\n",
    "import faiss\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from datasets import load_dataset\n",
    "from rank_bm25 import BM25Okapi\n",
    "from sentence_transformers import SentenceTransformer\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "\n",
    "# ── Cache key ──────────────────────────────────────────────────────────────────\n",
    "def make_cache_key(combo: dict) -> str:\n",
    "    \"\"\"Deterministic 12-char hash covering every field that defines index content.\"\"\"\n",
    "    parts = [\n",
    "        str(SCHEMA_VERSION),\n",
    "        combo[\"dataset\"],\n",
    "        combo[\"corpus_scope\"],\n",
    "        combo[\"embedding_model\"],\n",
    "        combo.get(\"model_revision\", \"main\"),\n",
    "        combo.get(\"query_prefix\", \"\"),\n",
    "        combo.get(\"passage_prefix\", \"\"),\n",
    "        combo[\"chunking_strategy\"],\n",
    "        str(combo[\"chunk_size\"]),\n",
    "        str(combo[\"chunk_overlap\"]),\n",
    "    ]\n",
    "    raw = \"|\".join(parts)\n",
    "    return hashlib.md5(raw.encode(\"utf-8\")).hexdigest()[:12]\n",
    "\n",
    "\n",
    "# ── RAGBench loader ────────────────────────────────────────────────────────────\n",
    "def load_ragbench(dataset_name: str, corpus_scope: str) -> pd.DataFrame:\n",
    "    \"\"\"Load RAGBench rows from the splits specified by corpus_scope.\"\"\"\n",
    "    splits = SPLIT_MAP[corpus_scope]\n",
    "    frames = []\n",
    "    for s in splits:\n",
    "        print(f\"  Loading rungalileo/ragbench [{dataset_name}] split={s} ...\")\n",
    "        ds = load_dataset(\"rungalileo/ragbench\", dataset_name, split=s)\n",
    "        frames.append(ds.to_pandas())\n",
    "    df = pd.concat(frames, ignore_index=True)\n",
    "    print(f\"  {len(df):,} rows, columns: {list(df.columns)}\")\n",
    "    return df\n",
    "\n",
    "\n",
    "# ── Document deduplication ─────────────────────────────────────────────────────\n",
    "def build_knowledge_base(df: pd.DataFrame) -> pd.DataFrame:\n",
    "    \"\"\"Flatten list-of-contexts columns into one row per unique document.\"\"\"\n",
    "    ctx_col = next(\n",
    "        (c for c in [\"documents\", \"context\", \"contexts\"] if c in df.columns), None\n",
    "    )\n",
    "    if ctx_col is None:\n",
    "        raise ValueError(f\"No context column found. Available: {list(df.columns)}\")\n",
    "    seen, rows = set(), []\n",
    "    for cell in df[ctx_col]:\n",
    "        if isinstance(cell, (list, np.ndarray)):\n",
    "            docs = list(cell)\n",
    "        elif isinstance(cell, str):\n",
    "            docs = [cell]\n",
    "        else:\n",
    "            docs = list(cell) if hasattr(cell, \"__iter__\") else [cell]\n",
    "        for doc in docs:\n",
    "            text = doc.strip() if isinstance(doc, str) else str(doc).strip()\n",
    "            if not text:\n",
    "                continue\n",
    "            h = hashlib.md5(text.encode()).hexdigest()\n",
    "            if h not in seen:\n",
    "                seen.add(h)\n",
    "                rows.append({\"doc_id\": h[:12], \"text\": text})\n",
    "    docs_df = pd.DataFrame(rows)\n",
    "    print(f\"  {len(docs_df):,} unique documents\")\n",
    "    return docs_df\n",
    "\n",
    "\n",
    "# ── Chunking strategies ────────────────────────────────────────────────────────\n",
    "def _chunk_passthrough(docs_df: pd.DataFrame) -> pd.DataFrame:\n",
    "    \"\"\"Keep each source passage as exactly one chunk (no splitting).\"\"\"\n",
    "    rows = [\n",
    "        {\n",
    "            \"chunk_id\": f\"{row['doc_id']}_0\",\n",
    "            \"doc_id\": row[\"doc_id\"],\n",
    "            \"chunk_idx\": i,\n",
    "            \"text\": row[\"text\"],\n",
    "        }\n",
    "        for i, (_, row) in enumerate(docs_df.iterrows())\n",
    "    ]\n",
    "    return pd.DataFrame(rows).reset_index(drop=True)\n",
    "\n",
    "\n",
    "def _chunk_recursive(\n",
    "    docs_df: pd.DataFrame,\n",
    "    model: SentenceTransformer,\n",
    "    chunk_size: int,\n",
    "    chunk_overlap: int,\n",
    ") -> pd.DataFrame:\n",
    "    \"\"\"Tokenizer-aware recursive splitting. chunk_size is in model token space.\"\"\"\n",
    "    splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(\n",
    "        model.tokenizer,\n",
    "        chunk_size=chunk_size,\n",
    "        chunk_overlap=chunk_overlap,\n",
    "    )\n",
    "    rows = []\n",
    "    for _, row in docs_df.iterrows():\n",
    "        for i, chunk in enumerate(splitter.split_text(row[\"text\"])):\n",
    "            rows.append({\n",
    "                \"chunk_id\": f\"{row['doc_id']}_{i}\",\n",
    "                \"doc_id\": row[\"doc_id\"],\n",
    "                \"chunk_idx\": len(rows),\n",
    "                \"text\": chunk,\n",
    "            })\n",
    "    return pd.DataFrame(rows).reset_index(drop=True)\n",
    "\n",
    "\n",
    "def chunk_documents(\n",
    "    docs_df: pd.DataFrame,\n",
    "    model: SentenceTransformer,\n",
    "    combo: dict,\n",
    ") -> pd.DataFrame:\n",
    "    \"\"\"Dispatch to the chunking strategy named in combo['chunking_strategy'].\"\"\"\n",
    "    strategy = combo[\"chunking_strategy\"]\n",
    "    if strategy == \"passthrough\":\n",
    "        chunks_df = _chunk_passthrough(docs_df)\n",
    "    elif strategy == \"recursive\":\n",
    "        chunks_df = _chunk_recursive(\n",
    "            docs_df, model, combo[\"chunk_size\"], combo[\"chunk_overlap\"]\n",
    "        )\n",
    "    elif strategy == \"parent_child\":\n",
    "        raise NotImplementedError(\n",
    "            \"parent_child requires retrieval + generation pipeline changes. \"\n",
    "            \"Implement after the dense/BM25 baseline is stable.\"\n",
    "        )\n",
    "    else:\n",
    "        raise ValueError(\n",
    "            f\"Unknown chunking_strategy: {strategy!r}. \"\n",
    "            \"Valid options: passthrough, recursive, parent_child\"\n",
    "        )\n",
    "    print(\n",
    "        f\"  {len(chunks_df):,} chunks from {len(docs_df):,} docs \"\n",
    "        f\"(strategy={strategy}, chunk_size={combo['chunk_size']}, \"\n",
    "        f\"overlap={combo['chunk_overlap']})\"\n",
    "    )\n",
    "    return chunks_df\n",
    "\n",
    "\n",
    "# ── Pre-build validation ───────────────────────────────────────────────────────\n",
    "def validate_combo(combo: dict, model: SentenceTransformer) -> None:\n",
    "    \"\"\"Raise before encoding if chunk_size would cause silent text truncation.\n",
    "\n",
    "    SentenceTransformer.encode() silently drops tokens beyond max_seq_length.\n",
    "    This guard surfaces the problem before any compute is spent.\n",
    "    \"\"\"\n",
    "    if combo[\"chunking_strategy\"] == \"passthrough\":\n",
    "        return  # no fixed chunk size; individual long passages are a data concern\n",
    "    if combo[\"chunk_size\"] > model.max_seq_length:\n",
    "        raise ValueError(\n",
    "            f\"chunk_size={combo['chunk_size']} exceeds \"\n",
    "            f\"{combo['embedding_model']} max_seq_length={model.max_seq_length}. \"\n",
    "            \"Reduce chunk_size or use a model with a larger limit.\"\n",
    "        )\n",
    "\n",
    "\n",
    "# ── Dense index ────────────────────────────────────────────────────────────────\n",
    "def build_dense_index(\n",
    "    chunks_df: pd.DataFrame,\n",
    "    model: SentenceTransformer,\n",
    "    passage_prefix: str = \"\",\n",
    "):\n",
    "    \"\"\"Encode chunks with optional passage_prefix; build FAISS inner-product index.\n",
    "\n",
    "    Embeddings are L2-normalised: inner-product == cosine similarity.\n",
    "    The passage_prefix is required for asymmetric models (e.g. BGE v1.5).\n",
    "    The matching query_prefix must be applied in the app retriever at query time.\n",
    "    \"\"\"\n",
    "    texts = [passage_prefix + t for t in chunks_df[\"text\"].tolist()]\n",
    "    print(f\"  Encoding {len(texts):,} chunks ...\")\n",
    "    embeddings = model.encode(\n",
    "        texts,\n",
    "        batch_size=64,\n",
    "        show_progress_bar=True,\n",
    "        convert_to_numpy=True,\n",
    "        normalize_embeddings=True,\n",
    "    ).astype(\"float32\")\n",
    "    index = faiss.IndexFlatIP(embeddings.shape[1])\n",
    "    index.add(embeddings)\n",
    "    print(f\"  FAISS index: {index.ntotal:,} vectors, dim={embeddings.shape[1]}\")\n",
    "    return embeddings, index\n",
    "\n",
    "\n",
    "# ── BM25 index ─────────────────────────────────────────────────────────────────\n",
    "def build_bm25(chunks_df: pd.DataFrame) -> BM25Okapi:\n",
    "    \"\"\"Build BM25 index with regex word tokenisation.\n",
    "\n",
    "    re.findall(r'\\\\w+') separates punctuation from tokens β€” important for legal\n",
    "    text where terms like 'clause,' or 'Β§3.1' must match their clean forms.\n",
    "    \"\"\"\n",
    "    tokenized = [re.findall(r\"\\w+\", t.lower()) for t in chunks_df[\"text\"]]\n",
    "    return BM25Okapi(tokenized)\n",
    "\n",
    "\n",
    "# ── Artifact serialisation ─────────────────────────────────────────────────────\n",
    "def save_artifacts(\n",
    "    out_dir: Path,\n",
    "    chunks_df: pd.DataFrame,\n",
    "    docs_df: pd.DataFrame,\n",
    "    embeddings: np.ndarray,\n",
    "    faiss_index,\n",
    "    bm25: BM25Okapi,\n",
    "    combo: dict,\n",
    "    index_id: str,\n",
    "    model: SentenceTransformer,\n",
    ") -> dict:\n",
    "    \"\"\"Write all artefacts to out_dir and return the meta dict.\"\"\"\n",
    "    out_dir.mkdir(parents=True, exist_ok=True)\n",
    "    faiss.write_index(faiss_index, str(out_dir / \"faiss.index\"))\n",
    "    np.save(str(out_dir / \"embeddings.npy\"), embeddings)\n",
    "    with open(out_dir / \"bm25.pkl\", \"wb\") as f:\n",
    "        pickle.dump(bm25, f)\n",
    "    chunks_df.to_parquet(out_dir / \"chunks.parquet\", index=False)\n",
    "    docs_df.to_parquet(out_dir / \"docs.parquet\", index=False)\n",
    "\n",
    "    meta = {\n",
    "        \"schema_version\": SCHEMA_VERSION,\n",
    "        \"index_id\": index_id,\n",
    "        \"dataset_repo\": \"rungalileo/ragbench\",\n",
    "        \"dataset_config\": combo[\"dataset\"],\n",
    "        \"corpus_scope\": combo[\"corpus_scope\"],\n",
    "        \"evaluation_note\": (\n",
    "            \"Closed retrieval: documents from the selected corpus_scope only. \"\n",
    "            \"Metrics measure relative quality across configs, \"\n",
    "            \"not open-corpus absolute recall.\"\n",
    "        ),\n",
    "        \"model_name\": combo[\"embedding_model\"],\n",
    "        \"model_revision\": combo.get(\"model_revision\", \"main\"),\n",
    "        \"effective_max_seq_length\": model.max_seq_length,\n",
    "        \"query_prefix\": combo.get(\"query_prefix\", \"\"),\n",
    "        \"passage_prefix\": combo.get(\"passage_prefix\", \"\"),\n",
    "        \"chunking_strategy\": combo[\"chunking_strategy\"],\n",
    "        \"chunk_size\": combo[\"chunk_size\"],\n",
    "        \"chunk_overlap\": combo[\"chunk_overlap\"],\n",
    "        \"normalization\": \"l2\",\n",
    "        \"similarity\": \"inner_product\",\n",
    "        \"domain\": combo[\"domain\"],\n",
    "        \"n_chunks\": len(chunks_df),\n",
    "        \"n_docs\": len(docs_df),\n",
    "        \"build_date\": datetime.now(timezone.utc).isoformat(),\n",
    "    }\n",
    "    with open(out_dir / \"meta.json\", \"w\") as f:\n",
    "        json.dump(meta, f, indent=2)\n",
    "    print(f\"  Saved to {out_dir}/\")\n",
    "    return meta\n",
    "\n",
    "\n",
    "print(\"Helper functions loaded.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-index-config",
   "metadata": {},
   "source": [
    "## Cell 5 β€” `index_config.json` helpers\n",
    "\n",
    "`index_config.json` is the registry file in the HF dataset repo that the Gradio app\n",
    "reads to populate its dropdowns. It stores the full tree of\n",
    "`dataset β†’ embedding_model β†’ chunk_config β†’ index_id` mappings.\n",
    "\n",
    "After every successful build the notebook:\n",
    "1. Downloads the current config from HF.\n",
    "2. Upserts the new `chunk_config` entry (replacing any existing entry with the same\n",
    "   `chunk_size / chunk_overlap / chunking_strategy / corpus_scope` tuple).\n",
    "3. Re-uploads the updated config.\n",
    "\n",
    "The `register_combo()` function now includes `corpus_scope`, `query_prefix`,\n",
    "`passage_prefix`, and `build_date` in the registered entry so the app can\n",
    "read them from the config without loading `meta.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-index-config",
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy\n",
    "\n",
    "INDEX_CONFIG_FILENAME = \"index_config.json\"\n",
    "\n",
    "_EMPTY_CONFIG = {\n",
    "    \"schema_version\": 1,\n",
    "    \"hub_repo\": HF_REPO,\n",
    "    \"datasets\": {},\n",
    "    \"runtime_options\": {\n",
    "        \"retrieval_strategies\": [\n",
    "            {\"id\": \"dense\",  \"display_name\": \"Dense only\"},\n",
    "            {\"id\": \"bm25\",   \"display_name\": \"BM25 only\"},\n",
    "            {\"id\": \"hybrid\", \"display_name\": \"Hybrid (Dense + BM25, RRF)\"},\n",
    "        ],\n",
    "        \"query_rewrite_strategies\": [\n",
    "            {\"id\": \"none\",        \"display_name\": \"None (raw question)\"},\n",
    "            {\"id\": \"rewrite\",     \"display_name\": \"Query rewrite\"},\n",
    "            {\"id\": \"multiquery\",  \"display_name\": \"Multi-query expansion\"},\n",
    "            {\"id\": \"hyde\",        \"display_name\": \"HyDE (dense)\"},\n",
    "            {\"id\": \"hyde_hybrid\", \"display_name\": \"HyDE + BM25 (hybrid)\"},\n",
    "        ],\n",
    "        \"rerankers\": [\n",
    "            {\"id\": \"off\",                                   \"display_name\": \"Off\"},\n",
    "            {\"id\": \"cross-encoder/ms-marco-MiniLM-L-6-v2\", \"display_name\": \"MiniLM-L-6-v2 cross-encoder\"},\n",
    "        ],\n",
    "        \"llm_models\": [\n",
    "            {\"id\": \"llama-3.1-8b-instant\",    \"display_name\": \"Llama 3.1 8B Instant\"},\n",
    "            {\"id\": \"llama-3.3-70b-versatile\", \"display_name\": \"Llama 3.3 70B Versatile\"},\n",
    "        ],\n",
    "    },\n",
    "}\n",
    "\n",
    "\n",
    "def download_index_config() -> dict:\n",
    "    \"\"\"Download index_config.json from HF repo, or return a fresh empty config.\"\"\"\n",
    "    try:\n",
    "        from huggingface_hub import hf_hub_download\n",
    "        path = hf_hub_download(\n",
    "            repo_id=HF_REPO, repo_type=\"dataset\",\n",
    "            filename=INDEX_CONFIG_FILENAME, token=HF_TOKEN,\n",
    "        )\n",
    "        with open(path) as f:\n",
    "            cfg = json.load(f)\n",
    "        print(\"  Downloaded existing index_config.json\")\n",
    "        return cfg\n",
    "    except Exception:\n",
    "        print(\"  index_config.json not found β€” starting fresh.\")\n",
    "        cfg = copy.deepcopy(_EMPTY_CONFIG)\n",
    "        cfg[\"hub_repo\"] = HF_REPO\n",
    "        return cfg\n",
    "\n",
    "\n",
    "def register_combo(cfg: dict, combo: dict, meta: dict) -> dict:\n",
    "    \"\"\"Upsert a chunk_config entry into the in-memory config dict.\"\"\"\n",
    "    cfg = copy.deepcopy(cfg)\n",
    "    cfg[\"hub_repo\"] = HF_REPO\n",
    "\n",
    "    ds_key  = combo[\"dataset\"]\n",
    "    em_key  = combo[\"embedding_model\"]\n",
    "    index_id = meta[\"index_id\"]\n",
    "\n",
    "    ds_entry = cfg.setdefault(\"datasets\", {}).setdefault(ds_key, {\n",
    "        \"display_name\": combo[\"display_name\"],\n",
    "        \"domain\": combo[\"domain\"],\n",
    "        \"embedding_models\": {},\n",
    "    })\n",
    "    ds_entry[\"display_name\"] = combo[\"display_name\"]\n",
    "    ds_entry[\"domain\"]       = combo[\"domain\"]\n",
    "\n",
    "    em_entry = ds_entry.setdefault(\"embedding_models\", {}).setdefault(em_key, {\n",
    "        \"display_name\": combo[\"embedding_display_name\"],\n",
    "        \"chunk_configs\": [],\n",
    "    })\n",
    "    em_entry[\"display_name\"] = combo[\"embedding_display_name\"]\n",
    "\n",
    "    new_entry = {\n",
    "        \"chunk_size\":        combo[\"chunk_size\"],\n",
    "        \"chunk_overlap\":     combo[\"chunk_overlap\"],\n",
    "        \"chunking_strategy\": combo[\"chunking_strategy\"],\n",
    "        \"corpus_scope\":      combo[\"corpus_scope\"],\n",
    "        \"query_prefix\":      combo.get(\"query_prefix\", \"\"),\n",
    "        \"passage_prefix\":    combo.get(\"passage_prefix\", \"\"),\n",
    "        \"index_id\":          index_id,\n",
    "        \"subfolder\":         index_id,\n",
    "        \"files\":             ARTIFACT_FILES,\n",
    "        \"n_chunks\":          meta[\"n_chunks\"],\n",
    "        \"n_docs\":            meta[\"n_docs\"],\n",
    "        \"build_date\":        meta[\"build_date\"],\n",
    "    }\n",
    "\n",
    "    # Replace any existing entry with the same (size, overlap, strategy, scope).\n",
    "    cfgs = em_entry[\"chunk_configs\"]\n",
    "    cfgs[:] = [\n",
    "        c for c in cfgs\n",
    "        if not (\n",
    "            c[\"chunk_size\"]        == combo[\"chunk_size\"]\n",
    "            and c[\"chunk_overlap\"]     == combo[\"chunk_overlap\"]\n",
    "            and c[\"chunking_strategy\"] == combo[\"chunking_strategy\"]\n",
    "            and c.get(\"corpus_scope\", \"train\") == combo[\"corpus_scope\"]\n",
    "        )\n",
    "    ]\n",
    "    cfgs.append(new_entry)\n",
    "    return cfg\n",
    "\n",
    "\n",
    "def upload_index_config(cfg: dict) -> None:\n",
    "    buf = json.dumps(cfg, indent=2).encode(\"utf-8\")\n",
    "    api.upload_file(\n",
    "        path_or_fileobj=io.BytesIO(buf),\n",
    "        path_in_repo=INDEX_CONFIG_FILENAME,\n",
    "        repo_id=HF_REPO,\n",
    "        repo_type=\"dataset\",\n",
    "        token=HF_TOKEN,\n",
    "        commit_message=\"chore: update index_config.json\",\n",
    "    )\n",
    "    print(f\"  Uploaded {INDEX_CONFIG_FILENAME} to {HF_REPO}\")\n",
    "\n",
    "\n",
    "print(\"index_config.json helpers loaded.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-validate",
   "metadata": {},
   "source": [
    "## Cell 6 β€” Validation: check all combos before any compute\n",
    "\n",
    "### Why validate first?\n",
    "\n",
    "`SentenceTransformer.encode()` silently truncates tokens beyond `model.max_seq_length`.\n",
    "For `all-MiniLM-L6-v2` (limit = 256) with `chunk_size = 512`, the index builds without\n",
    "error but encodes only the first 256 tokens of every chunk β€” the rest is silently dropped.\n",
    "The resulting metrics look fine but the comparison across models is meaningless.\n",
    "\n",
    "There are three separate limits in every HuggingFace embedding model:\n",
    "\n",
    "| Property | Description |\n",
    "|---|---|\n",
    "| `config.max_position_embeddings` | Architectural capacity of the transformer |\n",
    "| `tokenizer.model_max_length` | Tokenizer-level limit (may be 512 even for 256-limit models) |\n",
    "| `model.max_seq_length` | **Operative limit** β€” what `SentenceTransformer.encode()` actually uses |\n",
    "\n",
    "This cell uses known `max_seq_length` values to validate all combos without loading any model.\n",
    "The runtime `validate_combo()` call (Cell 9) performs the definitive check against the\n",
    "actually-loaded model.\n",
    "\n",
    "**Run this cell before running any build. Fix any `EXCEEDS LIMIT` rows in the COMBOS config.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-validate",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Known effective max_seq_length values (SentenceTransformer.max_seq_length).\n",
    "# These are the operative limits for encode() β€” NOT tokenizer.model_max_length.\n",
    "KNOWN_MAX_SEQ_LENGTHS = {\n",
    "    \"sentence-transformers/all-MiniLM-L6-v2\": 256,\n",
    "    \"sentence-transformers/all-mpnet-base-v2\": 384,\n",
    "    \"BAAI/bge-base-en-v1.5\":                  512,\n",
    "    \"BAAI/bge-large-en-v1.5\":                 512,\n",
    "    \"thenlper/gte-large\":                      512,\n",
    "    \"Alibaba-NLP/gte-modernbert-base\":         8192,\n",
    "}\n",
    "\n",
    "print(f\"{'IDX':>3}  {'STATUS':<18}  {'MODEL':<38}  {'LIMIT':>6}  {'CHUNK':>6}\")\n",
    "print(\"-\" * 82)\n",
    "issues = []\n",
    "for i, c in enumerate(COMBOS):\n",
    "    strategy   = c[\"chunking_strategy\"]\n",
    "    chunk_size = c[\"chunk_size\"]\n",
    "    model_id   = c[\"embedding_model\"]\n",
    "    limit      = KNOWN_MAX_SEQ_LENGTHS.get(model_id, \"?\")\n",
    "\n",
    "    if strategy == \"passthrough\":\n",
    "        status = \"OK (passthrough)\"\n",
    "    elif limit == \"?\":\n",
    "        status = \"? limit unknown\"\n",
    "    elif chunk_size > limit:\n",
    "        status = \"EXCEEDS LIMIT\"\n",
    "        issues.append(i)\n",
    "    else:\n",
    "        status = \"valid\"\n",
    "\n",
    "    short = model_id.split(\"/\")[-1]\n",
    "    print(f\"{i:>3}  {status:<18}  {short:<38}  {str(limit):>6}  {chunk_size:>6}\")\n",
    "\n",
    "print()\n",
    "if issues:\n",
    "    print(f\"FAIL: {len(issues)} combo(s) have invalid chunk sizes: indices {issues}\")\n",
    "    print(\"Fix chunk_size in COMBOS (Cell 2) before running any build.\")\n",
    "else:\n",
    "    print(\"All combos valid. Safe to build.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-status",
   "metadata": {},
   "source": [
    "## Cell 7 β€” Status: which combos are done / pending\n",
    "\n",
    "Queries the HF repo for already-uploaded subfolders and matches them against\n",
    "the current COMBOS list. Run this at the start of every session to choose\n",
    "which `COMBO_IDX` to build next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-status",
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import list_repo_files\n",
    "\n",
    "\n",
    "def _uploaded_index_ids() -> set:\n",
    "    \"\"\"Return subfolder names already present in the HF dataset repo.\"\"\"\n",
    "    try:\n",
    "        files = list(list_repo_files(repo_id=HF_REPO, repo_type=\"dataset\", token=HF_TOKEN))\n",
    "        return {f.split(\"/\")[0] for f in files if \"/\" in f}\n",
    "    except Exception:\n",
    "        return set()\n",
    "\n",
    "\n",
    "done_ids = _uploaded_index_ids()\n",
    "\n",
    "print(f\"{'IDX':>3}  {'STATUS':<10}  {'INDEX_ID':<14}  COMBO\")\n",
    "print(\"-\" * 80)\n",
    "for i, c in enumerate(COMBOS):\n",
    "    idx_id = make_cache_key(c)\n",
    "    status = \"done\" if idx_id in done_ids else \"pending\"\n",
    "    short  = c[\"embedding_model\"].split(\"/\")[-1]\n",
    "    label  = (\n",
    "        f\"{c['dataset']} / {short} / \"\n",
    "        f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n",
    "        f\"scope={c['corpus_scope']}\"\n",
    "    )\n",
    "    print(f\"{i:>3}  {status:<10}  {idx_id:<14}  {label}\")\n",
    "\n",
    "n_done    = sum(1 for c in COMBOS if make_cache_key(c) in done_ids)\n",
    "n_pending = len(COMBOS) - n_done\n",
    "print(f\"\\n{n_done} done / {n_pending} pending / {len(COMBOS)} total\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-pick",
   "metadata": {},
   "source": [
    "## Cell 8 β€” Pick the combo to build\n",
    "\n",
    "Set `COMBO_IDX` to the row number shown in Cell 7 that you want to build,\n",
    "then run **Cells 8–12** in sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-pick",
   "metadata": {},
   "outputs": [],
   "source": [
    "COMBO_IDX = 0  # <── CHANGE THIS\n",
    "\n",
    "combo    = COMBOS[COMBO_IDX]\n",
    "INDEX_ID = make_cache_key(combo)\n",
    "\n",
    "print(f\"Selected combo {COMBO_IDX}:\")\n",
    "print(f\"  dataset           : {combo['dataset']} ({combo['domain']})\")\n",
    "print(f\"  corpus_scope      : {combo['corpus_scope']}\")\n",
    "print(f\"  embedding_model   : {combo['embedding_model']}\")\n",
    "print(f\"  model_revision    : {combo.get('model_revision', 'main')}\")\n",
    "print(f\"  query_prefix      : {combo.get('query_prefix', '')!r}\")\n",
    "print(f\"  passage_prefix    : {combo.get('passage_prefix', '')!r}\")\n",
    "print(f\"  chunking_strategy : {combo['chunking_strategy']}\")\n",
    "print(f\"  chunk_size        : {combo['chunk_size']}\")\n",
    "print(f\"  chunk_overlap     : {combo['chunk_overlap']}\")\n",
    "print(f\"  index_id (key)    : {INDEX_ID}\")\n",
    "\n",
    "if INDEX_ID in done_ids:\n",
    "    print(\"\\nWARNING: This combo is already uploaded.\")\n",
    "    print(\"Continue to re-build and overwrite, or change COMBO_IDX.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-build-kb",
   "metadata": {},
   "source": [
    "## Cell 9 β€” Load dataset, build knowledge base, chunk\n",
    "\n",
    "Steps:\n",
    "1. Load RAGBench rows from the splits defined by `corpus_scope`.\n",
    "2. Flatten the per-row context lists into a deduplicated document table.\n",
    "3. Load the embedding model (needed for the tokenizer in recursive chunking).\n",
    "4. Run the pre-build validation guard β€” raises immediately if `chunk_size` exceeds\n",
    "   the model's effective sequence limit.\n",
    "5. Chunk documents using the strategy declared in the combo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-build-kb",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"Loading {combo['dataset']} [{combo['corpus_scope']}] ...\")\n",
    "full_df = load_ragbench(combo[\"dataset\"], combo[\"corpus_scope\"])\n",
    "\n",
    "print(\"\\nDeduplicating documents ...\")\n",
    "docs_df = build_knowledge_base(full_df)\n",
    "\n",
    "print(f\"\\nLoading embedding model: {combo['embedding_model']} ...\")\n",
    "embed_model = SentenceTransformer(\n",
    "    combo[\"embedding_model\"],\n",
    "    revision=combo.get(\"model_revision\", \"main\"),\n",
    ")\n",
    "print(f\"  max_seq_length : {embed_model.max_seq_length}\")\n",
    "print(f\"  embedding_dim  : {embed_model.get_sentence_embedding_dimension()}\")\n",
    "\n",
    "print(\"\\nValidating combo against model limits ...\")\n",
    "validate_combo(combo, embed_model)\n",
    "print(\"  Validation passed\")\n",
    "\n",
    "print(\"\\nChunking documents ...\")\n",
    "chunks_df = chunk_documents(docs_df, embed_model, combo)"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-build-idx",
   "metadata": {},
   "source": [
    "## Cell 10 β€” Build dense and BM25 indices\n",
    "\n",
    "**Dense index:** each chunk is encoded with the embedding model. If the combo\n",
    "specifies a `passage_prefix`, it is prepended to every chunk before encoding.\n",
    "Vectors are L2-normalised so FAISS inner-product search is equivalent to cosine\n",
    "similarity. `IndexFlatIP` performs exact search β€” no approximation.\n",
    "\n",
    "**BM25 index:** built with improved regex tokenisation. BM25 has no incremental\n",
    "update API; if the corpus scope is expanded later the BM25 index must be rebuilt\n",
    "from scratch (which is why the full pipeline is re-run for each combo)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-build-idx",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Building dense index ...\")\n",
    "embeddings, faiss_index = build_dense_index(\n",
    "    chunks_df,\n",
    "    embed_model,\n",
    "    passage_prefix=combo.get(\"passage_prefix\", \"\"),\n",
    ")\n",
    "\n",
    "print(\"\\nBuilding BM25 index ...\")\n",
    "bm25 = build_bm25(chunks_df)\n",
    "print(f\"  BM25 done ({len(chunks_df):,} tokenized chunks)\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-save",
   "metadata": {},
   "source": [
    "## Cell 11 β€” Save artifacts locally and upload to HF Hub\n",
    "\n",
    "Artifacts saved per combo:\n",
    "\n",
    "| File | Contents |\n",
    "|---|---|\n",
    "| `faiss.index` | FAISS `IndexFlatIP` β€” serialised binary |\n",
    "| `embeddings.npy` | Float32 numpy array of L2-normalised vectors |\n",
    "| `bm25.pkl` | Pickled `BM25Okapi` object |\n",
    "| `chunks.parquet` | Chunk table: `chunk_id`, `doc_id`, `chunk_idx`, `text` |\n",
    "| `docs.parquet` | Document table: `doc_id`, `text` |\n",
    "| `meta.json` | Full provenance record (see Cell 4 for schema) |\n",
    "\n",
    "All six files are uploaded to `{HF_REPO}/{index_id}/` in one `upload_folder` call."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-save",
   "metadata": {},
   "outputs": [],
   "source": [
    "OUT_DIR = Path(f\"/tmp/rag_indices/{INDEX_ID}\")\n",
    "\n",
    "print(f\"Saving artifacts to {OUT_DIR} ...\")\n",
    "meta = save_artifacts(\n",
    "    OUT_DIR, chunks_df, docs_df,\n",
    "    embeddings, faiss_index, bm25,\n",
    "    combo, INDEX_ID, embed_model,\n",
    ")\n",
    "\n",
    "print(f\"\\nUploading {OUT_DIR} β†’ {HF_REPO}/{INDEX_ID} ...\")\n",
    "api.upload_folder(\n",
    "    folder_path=str(OUT_DIR),\n",
    "    path_in_repo=INDEX_ID,\n",
    "    repo_id=HF_REPO,\n",
    "    repo_type=\"dataset\",\n",
    "    token=HF_TOKEN,\n",
    "    commit_message=(\n",
    "        f\"add {INDEX_ID} \"\n",
    "        f\"({combo['dataset']} / {combo['embedding_model']} / \"\n",
    "        f\"{combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']} / \"\n",
    "        f\"scope={combo['corpus_scope']})\"\n",
    "    ),\n",
    ")\n",
    "print(\"  Upload complete.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-update-config",
   "metadata": {},
   "source": [
    "## Cell 12 β€” Update `index_config.json`\n",
    "\n",
    "Downloads the current registry, upserts the new combo entry, and re-uploads.\n",
    "The Gradio app reads this file to build its dataset / model / chunk dropdowns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-update-config",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Updating index_config.json ...\")\n",
    "current_cfg = download_index_config()\n",
    "updated_cfg = register_combo(current_cfg, combo, meta)\n",
    "upload_index_config(updated_cfg)\n",
    "\n",
    "# Refresh done_ids so Cell 7 is accurate if re-run in the same session.\n",
    "done_ids = _uploaded_index_ids()\n",
    "\n",
    "print(\"\\n── Registered chunk_config entry ──\")\n",
    "ds_cfg = updated_cfg[\"datasets\"].get(combo[\"dataset\"], {})\n",
    "em_cfg = ds_cfg.get(\"embedding_models\", {}).get(combo[\"embedding_model\"], {})\n",
    "for cc in em_cfg.get(\"chunk_configs\", []):\n",
    "    if cc[\"index_id\"] == INDEX_ID:\n",
    "        print(json.dumps(cc, indent=2))\n",
    "        break\n",
    "\n",
    "print(f\"\\nCombo {COMBO_IDX} complete. Run Cell 7 to see remaining combos.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-batch",
   "metadata": {},
   "source": [
    "## Cell 13 β€” Batch: build all pending combos automatically\n",
    "\n",
    "Alternative to running Cells 8–12 one combo at a time. Discovers every pending\n",
    "combo from the HF repo, then builds and uploads them in sequence.\n",
    "\n",
    "**Optimisation:** combos are sorted by `(dataset, corpus_scope, embedding_model)` so\n",
    "each dataset is loaded once and each model is loaded once across all its chunk-size\n",
    "variants. This avoids redundant downloads on free-tier Colab.\n",
    "\n",
    "Set `DRY_RUN = True` to preview what would be built without running any compute.\n",
    "\n",
    "Each combo's result is uploaded immediately on completion so progress is never lost\n",
    "if the session is interrupted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-batch",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gc\n",
    "from itertools import groupby\n",
    "\n",
    "DRY_RUN = False  # set True to preview without building\n",
    "\n",
    "# ── Gather pending combos ──────────────────────────────────────────────────────\n",
    "done_ids = _uploaded_index_ids()\n",
    "pending = [\n",
    "    (i, make_cache_key(c), c)\n",
    "    for i, c in enumerate(COMBOS)\n",
    "    if make_cache_key(c) not in done_ids\n",
    "]\n",
    "\n",
    "print(f\"{len(pending)} pending / {len(COMBOS)} total\")\n",
    "for i, idx_id, c in pending:\n",
    "    short = c[\"embedding_model\"].split(\"/\")[-1]\n",
    "    print(\n",
    "        f\"  [{i}] {idx_id}  {c['dataset']} / {short} / \"\n",
    "        f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n",
    "        f\"scope={c['corpus_scope']}\"\n",
    "    )\n",
    "\n",
    "if DRY_RUN:\n",
    "    print(\"\\nDRY_RUN=True β€” nothing built.\")\n",
    "else:\n",
    "    # Sort so dataset+scope and model are each loaded once.\n",
    "    keyfn = lambda t: (t[2][\"dataset\"], t[2][\"corpus_scope\"], t[2][\"embedding_model\"])\n",
    "    pending_sorted = sorted(pending, key=keyfn)\n",
    "\n",
    "    _ds_cache    = {}   # \"dataset::scope\" -> docs_df\n",
    "    _model_key   = None\n",
    "    _model       = None\n",
    "\n",
    "    for (ds_name, scope, em_name), group in groupby(pending_sorted, key=keyfn):\n",
    "        group = list(group)\n",
    "        ds_scope_key = f\"{ds_name}::{scope}\"\n",
    "\n",
    "        if ds_scope_key not in _ds_cache:\n",
    "            print(f\"\\n── Loading dataset: {ds_name} [{scope}] ──\")\n",
    "            raw_df = load_ragbench(ds_name, scope)\n",
    "            _ds_cache[ds_scope_key] = build_knowledge_base(raw_df)\n",
    "\n",
    "        if _model_key != em_name:\n",
    "            print(f\"\\n── Loading model: {em_name} ──\")\n",
    "            _model     = SentenceTransformer(em_name)\n",
    "            _model_key = em_name\n",
    "\n",
    "        docs_df     = _ds_cache[ds_scope_key]\n",
    "        embed_model = _model\n",
    "\n",
    "        for combo_idx, index_id, combo in group:\n",
    "            print(f\"\\n{'='*60}\")\n",
    "            print(f\"Building [{combo_idx}] {index_id}\")\n",
    "            print(f\"  {combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']}\")\n",
    "            print(f\"{'='*60}\")\n",
    "            try:\n",
    "                validate_combo(combo, embed_model)\n",
    "                chunks_df = chunk_documents(docs_df, embed_model, combo)\n",
    "                embeddings, faiss_index = build_dense_index(\n",
    "                    chunks_df, embed_model,\n",
    "                    passage_prefix=combo.get(\"passage_prefix\", \"\"),\n",
    "                )\n",
    "                bm25    = build_bm25(chunks_df)\n",
    "                out_dir = Path(f\"/tmp/rag_indices/{index_id}\")\n",
    "                meta    = save_artifacts(\n",
    "                    out_dir, chunks_df, docs_df,\n",
    "                    embeddings, faiss_index, bm25,\n",
    "                    combo, index_id, embed_model,\n",
    "                )\n",
    "                api.upload_folder(\n",
    "                    folder_path=str(out_dir),\n",
    "                    path_in_repo=index_id,\n",
    "                    repo_id=HF_REPO,\n",
    "                    repo_type=\"dataset\",\n",
    "                    token=HF_TOKEN,\n",
    "                    commit_message=(\n",
    "                        f\"add {index_id} \"\n",
    "                        f\"({combo['dataset']}/{combo['embedding_model']}/\"\n",
    "                        f\"{combo['chunking_strategy']}:{combo['chunk_size']}-{combo['chunk_overlap']})\"\n",
    "                    ),\n",
    "                )\n",
    "                current_cfg = download_index_config()\n",
    "                updated_cfg = register_combo(current_cfg, combo, meta)\n",
    "                upload_index_config(updated_cfg)\n",
    "                done_ids = _uploaded_index_ids()\n",
    "                del embeddings, faiss_index, bm25, chunks_df\n",
    "                shutil.rmtree(out_dir, ignore_errors=True)\n",
    "                gc.collect()\n",
    "                print(f\"[{combo_idx}] done\")\n",
    "            except Exception as exc:\n",
    "                print(f\"[{combo_idx}] FAILED: {exc}\")\n",
    "                print(\"  Skipping to next combo ...\")\n",
    "\n",
    "    print(\"\\nAll pending combos processed.\")"
   ]
  },

  {
   "cell_type": "markdown",
   "id": "md-final",
   "metadata": {},
   "source": [
    "## Cell 14 β€” Final status\n",
    "\n",
    "Re-fetches the uploaded subfolder list from HF and shows the full progress table.\n",
    "Run after each session to confirm what has been uploaded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd-final",
   "metadata": {},
   "outputs": [],
   "source": [
    "done_ids = _uploaded_index_ids()\n",
    "n_done   = sum(1 for c in COMBOS if make_cache_key(c) in done_ids)\n",
    "\n",
    "print(f\"Progress: {n_done}/{len(COMBOS)} combos uploaded\\n\")\n",
    "print(f\"{'IDX':>3}  {'STATUS':<10}  {'INDEX_ID':<14}  COMBO\")\n",
    "print(\"-\" * 80)\n",
    "for i, c in enumerate(COMBOS):\n",
    "    idx_id = make_cache_key(c)\n",
    "    status = \"done\" if idx_id in done_ids else \"pending\"\n",
    "    short  = c[\"embedding_model\"].split(\"/\")[-1]\n",
    "    label  = (\n",
    "        f\"{c['dataset']} / {short} / \"\n",
    "        f\"{c['chunking_strategy']}:{c['chunk_size']}-{c['chunk_overlap']} / \"\n",
    "        f\"scope={c['corpus_scope']}\"\n",
    "    )\n",
    "    print(f\"{i:>3}  {status:<10}  {idx_id:<14}  {label}\")"
   ]
  }

 ]
}