File size: 55,727 Bytes
f326e95
3055cc8
 
 
 
 
 
 
 
 
cba561e
9206e91
 
 
 
76d8a43
 
b92c43f
 
 
 
9206e91
4352f73
9206e91
 
 
 
 
857fc54
ee7a22f
 
 
 
3055cc8
b158bbc
3055cc8
 
 
b158bbc
 
76d8a43
 
 
3055cc8
 
 
 
 
 
 
 
 
 
 
 
58b87db
3055cc8
 
 
 
 
 
58b87db
 
 
 
 
 
 
 
3055cc8
 
 
 
 
 
 
58b87db
 
f326e95
58b87db
3055cc8
58b87db
 
3055cc8
 
 
58b87db
f326e95
58b87db
 
f326e95
 
58b87db
3055cc8
 
58b87db
3055cc8
 
58b87db
 
 
 
3055cc8
58b87db
 
3055cc8
 
 
58b87db
3055cc8
58b87db
 
 
3055cc8
58b87db
 
 
 
 
 
3055cc8
 
 
58b87db
3055cc8
 
9206e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76d8a43
 
 
 
cba561e
76d8a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
76d8a43
cba561e
76d8a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
76d8a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92c43f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
b92c43f
 
 
 
 
cba561e
b92c43f
 
 
 
 
 
 
 
cba561e
 
 
b92c43f
cba561e
b92c43f
 
 
 
 
cba561e
b92c43f
 
cba561e
b92c43f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
b92c43f
 
 
cba561e
b92c43f
 
 
 
 
 
 
 
 
 
 
cba561e
b92c43f
 
 
 
 
 
 
 
 
 
cba561e
b92c43f
 
 
cba561e
b92c43f
 
 
 
 
 
 
cba561e
b92c43f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
 
db9df30
 
 
 
 
 
 
 
cba561e
 
 
 
db9df30
 
 
 
 
f326e95
db9df30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
db9df30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba561e
db9df30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4352f73
db9df30
4352f73
db9df30
 
364a0dd
b158bbc
364a0dd
b158bbc
 
 
364a0dd
b158bbc
 
 
364a0dd
 
b158bbc
364a0dd
 
857fc54
 
 
8f78213
857fc54
 
 
cba561e
857fc54
 
 
 
 
 
 
8f78213
 
857fc54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee7a22f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f326e95
ee7a22f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f78213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85ed145
 
 
cba561e
85ed145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3055cc8
ee7a22f
 
 
 
 
 
cba561e
 
ee7a22f
4352f73
ee7a22f
 
 
 
 
 
 
 
 
 
8f78213
85ed145
 
3055cc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ruff: noqa: T201  # CLI build-script report payload (CLAUDE.md whitelist)
"""Build NuBerea/concept-analysis — consolidated analytical layer for concept topology.

Absorbs all of NuBerea/concept-trajectories and migrates three analytical configs
from NuBerea/concept-graph (community_candidate, community_membership, concept_centroids).

Boundary principle:
  concept-graph   = topology (span_node, span_edge, concept_node, concept_span_edge, ...)
  concept-analysis = derived outputs (centroids, communities, trajectories, drift)

Output configs (20 total, writing 22 parquet dirs — pseu builds write deut+pseu each):
  concept_verse_edge       — 28,909 rows; concept×verse, LXX+NT strata, shlm-grc-en 768-dim
  concept_trajectory       — 112 rows; concept×stratum centroids, LXX+NT
  concept_verse_edge_sp    — 59,478 rows; concept×verse, LXX+NT+Vulgate, SPhilBerta 768-dim
  concept_trajectory_sp    — 190 rows; concept×stratum centroids, LXX+NT+Vulgate
  concept_verse_edge_bt    — 59,478 rows; concept_verse_edge_sp + bt_layer + plate_segment (T8)
  concept_trajectory_bt    — ~960 rows; concept×bt_layer centroids (T8, match_grain=pericope)
  concept_verse_edge_deut  — ~5,857 rows; Deuterocanon verses, nearest-centroid assignment
  concept_verse_edge_pseu  — ~15,043 rows; Pseudepigrapha verses, nearest-centroid assignment
  concept_trajectory_deut  — per-concept centroids for Deuterocanon stratum
  concept_trajectory_pseu  — per-concept centroids for Pseudepigrapha stratum
  concept_drift            — 78 rows; Schlattmann&Vogl 2024 drift metrics per concept×transition
  concept_drift_itp        — 78 rows; PSEU-extended drift (5 pairs: lxx→deut/pseu, deut/pseu→nt, deut→pseu)
  concept_drift_hamilton   — 5,023 rows; Hamilton/CADE word2vec drift per lemma (3 languages)
  community_candidate      — 55 rows; community summaries (from concept-graph)
  community_membership     — 2,412 rows; pericope→community assignments (from concept-graph)
  concept_centroids        — 156 rows; L1+L2 bi_encoder_v1 384-dim centroids (from concept-graph)
  concept_aliases          — 567 rows; TF-IDF English term → bt1_xxx concept_id list mappings
  concept_verse_edge_patr  — ~40K rows; patristic GRC segments, nearest-centroid assignment
  concept_verse_edge_philo — ~7.9K rows; Philo of Alexandria GRC segments, nearest-centroid
  concept_verse_edge_josephus — ~12.7K rows; Josephus GRC segments, nearest-centroid
  concept_verse_edge_targum   — ~28K rows; Targum English translations, nearest-centroid
  concept_verse_edge_talmud   — ~200K rows; Mishnah+Tosefta English translations, nearest-centroid

Source data (local build dirs + HF for HF-native configs):
  huggingface/candidates/build/concept-trajectories/data/
  huggingface/candidates/build/concept-graph/data/
  huggingface/candidates/build/concept-trajectories/data/concept_drift_analysis.csv
  concept_aliases: HF-native — NuBerea/AI-models bi_encoder_v1 + question_bin_assignment.json
                              + NuBerea/concept-graph concept_node centroids
  concept_verse_edge_bt / concept_trajectory_bt: T8 — read NuBerea/pericope-genealogy
    composition_dag (local until genealogy HF upload); promote concept-analysis to T8 for
    bt-indexed configs only.

Usage:
    python scripts/build.py              # build all configs
    python scripts/build.py --config X   # build only config X

For HF-native reproducibility of the trajectory configs, see verify.py in this directory.
"""

from __future__ import annotations

import argparse
import pathlib
import sys

import pandas as pd

BUILD = pathlib.Path("huggingface/candidates/build")
OUT = BUILD / "concept-analysis/data"

# Make hf_registry importable
_THIS = pathlib.Path(__file__).resolve()
_CANDIDATES = _THIS.parents[2]
if str(_CANDIDATES) not in sys.path:
    sys.path.insert(0, str(_CANDIDATES))

from hf_registry import load_hf_or_local


def _parquet_out(config: str) -> pathlib.Path:
    p = OUT / config
    p.mkdir(parents=True, exist_ok=True)
    return p / "train-00000-of-00001.parquet"


def import_trajectory_config(name: str) -> None:
    """Import a trajectory config from NuBerea/concept-trajectories (HF-native, local fallback)."""
    ds = load_hf_or_local("NuBerea/concept-analysis", name)
    df = ds.to_pandas()
    dst = _parquet_out(name)
    df.to_parquet(dst, index=False)
    print(f"  {name}: {len(df):,} rows, {len(df.columns)} cols — imported from NuBerea/concept-trajectories")


def build_concept_drift() -> None:
    """Compute drift inline from concept_trajectory_sp + concept_verse_edge_sp (HF-native)."""
    sys.path.insert(0, str(_THIS.parent))
    from analyze_concept_drift import compute_drift_dataframe

    traj = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_sp").to_pandas()
    cve  = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas()
    df = compute_drift_dataframe(traj, cve)
    dst = _parquet_out("concept_drift")
    df.to_parquet(dst, index=False)
    print(f"  concept_drift: {len(df)} rows, {len(df.columns)} cols — computed inline (HF-native)")


def import_community_config(name: str) -> None:
    """Import a community config from NuBerea/concept-graph (HF-native, local fallback)."""
    ds = load_hf_or_local("NuBerea/concept-graph", name)
    df = ds.to_pandas()
    dst = _parquet_out(name)
    df.to_parquet(dst, index=False)
    print(f"  {name}: {len(df):,} rows, {len(df.columns)} cols — imported from NuBerea/concept-graph")


def build_concept_centroids() -> None:
    """Build concept_centroids from NuBerea/concept-graph concept_node (HF-native).

    The concept_node config carries each L1/L2 BERTopic node's centroid inline as a
    `centroid` column (bi_encoder_v1 384-dim vectors). We project to a 3-column
    parquet (concept_id, level, centroid) matching the historical schema.
    """
    ds = load_hf_or_local("NuBerea/concept-graph", "concept_node")
    df = ds.to_pandas()
    df = df[df["level"].isin([1, 2])].copy()
    df["level"] = df["level"].map({1: "l1", 2: "l2"})
    df = df[["concept_id", "level", "centroid"]].sort_values(["level", "concept_id"]).reset_index(drop=True)

    dst = _parquet_out("concept_centroids")
    df.to_parquet(dst, index=False)
    per_level = df.groupby("level").size().to_dict()
    print(f"  concept_centroids: {len(df)} rows ({per_level}) — built from concept_node (HF-native)")


def build_concept_drift_hamilton() -> None:
    """Run the Hamilton/CADE word2vec drift analysis (requires gensim).

    Delegates to build_hamilton.py, which trains word2vec per corpus slice,
    aligns via orthogonal Procrustes, and computes drift_score per shared lemma.
    Three independent analyses: Hebrew EBH→LBH, Greek LXX→NT, Latin VG_OT→VG_NT.

    Requires Python 3.12 venv with gensim installed:
        /tmp/gensim_venv/bin/python scripts/build_hamilton.py
    Or equivalently:
        python scripts/build.py --config concept_drift_hamilton
    (which calls build_hamilton.py via subprocess using the same interpreter that
    has gensim, or prints existing stats if the parquet already exists.)
    """
    import subprocess
    import sys

    parquet = OUT / "concept_drift_hamilton" / "train-00000-of-00001.parquet"
    # Try running build_hamilton.py with current interpreter first; fall back to gensim venv
    interpreters = [sys.executable, "/tmp/gensim_venv/bin/python"]
    for interp in interpreters:
        try:
            result = subprocess.run(
                [interp, "scripts/build_hamilton.py"],
                check=True, capture_output=False,
            )
            break
        except (subprocess.CalledProcessError, FileNotFoundError):
            continue
    else:
        if parquet.exists():
            df = pd.read_parquet(parquet)
            print(f"  concept_drift_hamilton: {len(df):,} rows (pre-built; gensim unavailable)")
        else:
            raise RuntimeError(
                "build_hamilton.py failed and no pre-built parquet found. "
                "Run: /tmp/gensim_venv/bin/python scripts/build_hamilton.py"
            )
        return
    df = pd.read_parquet(parquet)
    print(f"  concept_drift_hamilton: {len(df):,} rows — Hamilton/CADE word2vec drift")


def _build_verse_bt_lookup(dag: "pd.DataFrame", nrsv: "pd.DataFrame") -> dict:
    """Return dict mapping OSIS verse ref (dot format) → (bt_layer, plate_segment).

    Covers three node types in composition_dag:
    - otp:/pseu: rows with osis_start/osis_end → range-expanded to constituent verses
    - single-verse rows (unit_id matches 'Book.ch.v') → direct mapping
    """
    import re

    # Parse OSIS ref to (chapter, verse) numeric key for range comparison
    _osis_key_re = re.compile(r'^[^.]+\.(\d+)\.(\d+)$')

    def _key(ref: str) -> tuple[int, int] | None:
        m = _osis_key_re.match(ref)
        if not m:
            return None
        return (int(m.group(1)), int(m.group(2)))

    verse_bt: dict = {}

    # ── 1. Range-based: otp + pseu rows (have osis_start / osis_end) ────────
    range_rows = dag[
        dag['unit_id'].str.startswith(('otp:', 'pseu:'), na=False)
        & dag['osis_start'].ne('')
    ][['osis_start', 'osis_end', 'bt_layer', 'plate_segment']].copy()

    range_rows['_book'] = range_rows['osis_start'].str.split('.').str[0]
    range_rows['_sk'] = range_rows['osis_start'].apply(_key)
    range_rows['_ek'] = range_rows['osis_end'].apply(_key)
    range_rows = range_rows.dropna(subset=['_sk', '_ek'])

    # Build a numeric sort key for merge_asof (ch * 10000 + v fits all Bible ranges)
    range_rows['_start_num'] = range_rows['_sk'].apply(lambda k: k[0] * 10000 + k[1])
    range_rows['_end_num'] = range_rows['_ek'].apply(lambda k: k[0] * 10000 + k[1])

    nrsv_ot = nrsv[nrsv['osis_ref'].str.contains(r'^\w+\.\d+\.\d+$', regex=True, na=False)].copy()
    nrsv_ot['_book'] = nrsv_ot['osis_ref'].str.split('.').str[0]
    nrsv_ot['_num'] = nrsv_ot['osis_ref'].apply(
        lambda r: (lambda k: k[0] * 10000 + k[1] if k else None)(_key(r))
    )
    nrsv_ot = nrsv_ot.dropna(subset=['_num'])
    nrsv_ot['_num'] = nrsv_ot['_num'].astype(int)

    for book, book_perps in range_rows.groupby('_book'):
        book_verses = nrsv_ot[nrsv_ot['_book'] == book][['osis_ref', '_num']].sort_values('_num')
        if book_verses.empty:
            continue
        perps_sorted = book_perps[['_start_num', '_end_num', 'bt_layer', 'plate_segment']].sort_values('_start_num')

        # merge_asof: for each verse, find the last pericope whose start ≤ verse
        merged = pd.merge_asof(
            book_verses,
            perps_sorted,
            left_on='_num',
            right_on='_start_num',
            direction='backward',
        )
        # Keep only verses that also fall before the pericope's end
        merged = merged[merged['_num'] <= merged['_end_num']]
        for _, row in merged.iterrows():
            verse_bt[row['osis_ref']] = (int(row['bt_layer']), str(row['plate_segment']))

    # ── 2. Single-verse nodes: unit_id IS the verse OSIS ref ───────────────
    single_mask = dag['unit_id'].str.match(r'^\w+\.\d+\.\d+$', na=False)
    for _, row in dag[single_mask][['unit_id', 'bt_layer', 'plate_segment']].iterrows():
        verse_bt[row['unit_id']] = (int(row['bt_layer']), str(row['plate_segment']))

    return verse_bt


def _normalize_osis(ref: str) -> str:
    """Convert lxx-style '1Chr 1:1' to OSIS dot-format '1Chr.1.1'."""
    if ' ' in ref:
        book, rest = ref.split(' ', 1)
        return f"{book}.{rest.replace(':', '.')}"
    return ref


def build_concept_verse_edge_bt() -> None:
    """Extend concept_verse_edge_sp with bt_layer and plate_segment from pericope-genealogy.

    Cardinal rule (CLAUDE.md): preserves ALL verse-level rows (match_grain='verse').
    bt_layer is nullable (pd.NA) for NT verses not represented as intertextuality
    anchor nodes in composition_dag. osisRef is the normalized OSIS dot-format ref.

    T8 dependency: reads NuBerea/pericope-genealogy composition_dag (T7). Falls back
    to local build dir until genealogy HF upload is complete.
    """
    import numpy as np

    cve = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas()
    dag = load_hf_or_local("NuBerea/analytics", "composition_dag").to_pandas()
    nrsv = load_hf_or_local("NuBerea/nrsv").to_pandas()

    verse_bt = _build_verse_bt_lookup(dag, nrsv)

    # Normalize all osis_refs to dot format for lookup
    cve['osisRef'] = cve['osis_ref'].apply(_normalize_osis)

    bt_layers = []
    plate_segments = []
    for ref in cve['osisRef']:
        val = verse_bt.get(ref)
        if val is not None:
            bt_layers.append(val[0])
            plate_segments.append(val[1])
        else:
            bt_layers.append(pd.NA)
            plate_segments.append(pd.NA)

    cve['bt_layer'] = pd.array(bt_layers, dtype=pd.Int64Dtype())
    cve['plate_segment'] = plate_segments
    cve['match_grain'] = 'verse'

    dst = _parquet_out("concept_verse_edge_bt")
    cve.to_parquet(dst, index=False)
    matched = cve['bt_layer'].notna().sum()
    print(
        f"  concept_verse_edge_bt: {len(cve):,} rows, "
        f"{matched:,} ({100*matched/len(cve):.1f}%) with bt_layer — "
        f"T8 (pericope-genealogy)"
    )


def build_concept_trajectory_bt() -> None:
    """Build concept × bt_layer centroids from concept_verse_edge_bt.

    Cardinal rule: pericope-level derived view (match_grain='pericope') alongside
    concept_trajectory_sp (3-way stratum). Never replaces it.

    Only rows with a non-null bt_layer contribute. Concepts with fewer than 2
    matched verses in a bt_layer are excluded (no meaningful centroid).

    Schema mirrors concept_trajectory_sp with bt_layer replacing stratum, plus
    match_grain='pericope' and osisRef (book prefix of contributing verses).
    """
    import numpy as np

    # Load from local build output (concept_verse_edge_bt must be built first)
    bt_path = _parquet_out("concept_verse_edge_bt")
    if not bt_path.exists():
        raise RuntimeError(
            "concept_verse_edge_bt not found — run build_concept_verse_edge_bt first."
        )
    cve_bt = pd.read_parquet(bt_path)

    # Work only on rows with bt_layer assigned
    matched = cve_bt[cve_bt['bt_layer'].notna()].copy()
    matched['bt_layer'] = matched['bt_layer'].astype(int)

    def _numpy_centroid(embeddings) -> list:
        arr = np.stack([np.asarray(e) for e in embeddings])
        c = arr.mean(axis=0)
        return c.tolist()

    def _mean_cosine(embeddings, centroid) -> float:
        c = np.asarray(centroid)
        sims = []
        for e in embeddings:
            v = np.asarray(e)
            denom = np.linalg.norm(v) * np.linalg.norm(c)
            if denom > 0:
                sims.append(float(np.dot(v, c) / denom))
        return float(np.mean(sims)) if sims else 0.0

    rows = []
    for (concept_id, bt_layer), grp in matched.groupby(['concept_id', 'bt_layer']):
        if len(grp) < 2:
            continue
        embeddings = grp['embedding'].tolist()
        centroid = _numpy_centroid(embeddings)
        rows.append({
            'concept_id': concept_id,
            'concept_label': grp['concept_label'].iloc[0],
            'bt_layer': int(bt_layer),
            'verse_count': len(grp),
            'centroid': centroid,
            'mean_cosine_to_centroid': _mean_cosine(embeddings, centroid),
            'verse_refs': sorted(set(grp['osisRef'].tolist())),
            'model_id': grp['model_id'].iloc[0],
            'match_grain': 'pericope',
        })

    df = pd.DataFrame(rows).sort_values(['concept_id', 'bt_layer']).reset_index(drop=True)
    dst = _parquet_out("concept_trajectory_bt")
    df.to_parquet(dst, index=False)
    print(
        f"  concept_trajectory_bt: {len(df):,} rows "
        f"({df['concept_id'].nunique()} concepts × {df['bt_layer'].nunique()} bt_layers) — "
        f"T8 derived view, match_grain=pericope"
    )


def _build_reference_centroids() -> "tuple[list, list, np.ndarray]":
    """Compute per-concept reference centroids pooled from LXX+NT+VG in SPhilBerta space.

    Returns:
        (concept_ids, concept_labels, centroid_unit_matrix)
        centroid_unit_matrix shape: (n_concepts, 768), L2-normalized rows.
    """
    import numpy as np

    print("  Loading concept_verse_edge_sp for reference centroids...")
    cve_sp = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas()

    concept_ids = []
    concept_labels_list = []
    centroid_list = []
    for cid, grp in cve_sp.groupby("concept_id"):
        mats = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]])
        centroid_list.append(mats.mean(axis=0))
        concept_ids.append(cid)
        concept_labels_list.append(grp["concept_label"].iloc[0])

    centroid_matrix = np.stack(centroid_list)  # (n_concepts, 768)
    norms = np.linalg.norm(centroid_matrix, axis=1, keepdims=True)
    centroid_unit = centroid_matrix / (norms + 1e-8)
    print(f"  Reference space: {len(concept_ids)} concept centroids (768-dim SPhilBerta)")
    return concept_ids, concept_labels_list, centroid_unit


def _project_pseu_stratum(
    stratum: str,
    concept_ids: list,
    concept_labels_list: list,
    centroid_unit: "np.ndarray",
) -> "pd.DataFrame":
    """Project one PSEU stratum onto pre-computed concept centroids.

    Each verse is assigned to its single nearest concept (top-1 cosine similarity).
    assignment_method='nearest_centroid' distinguishes these rows from topology-based
    pericope_containment rows in concept_verse_edge_sp.
    """
    import numpy as np

    config_name = "deut_verse_embeddings_sp" if stratum == "deut" else "pseu_verse_embeddings_sp"
    print(f"  Loading {config_name} from NuBerea/features...")
    pseu_df = load_hf_or_local("NuBerea/features", config_name).to_pandas()
    print(f"  Loaded {len(pseu_df):,} {stratum} verses")

    emb_matrix = np.stack([np.asarray(e, dtype=np.float32) for e in pseu_df["embedding"]])
    emb_norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True)
    emb_unit = emb_matrix / (emb_norms + 1e-8)

    cos_scores = emb_unit @ centroid_unit.T  # (n_verses, n_concepts)
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(pseu_df)), best_idx]

    rows = []
    for i, (_, verse_row) in enumerate(pseu_df.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id": concept_ids[ci],
            "concept_label": concept_labels_list[ci],
            "osis_ref": verse_row["osis_ref"],
            "stratum": stratum,
            "edge_weight": float(best_score[i]),
            "embedding": verse_row["embedding"],
            "model_id": verse_row["model_id"],
            "assignment_method": "nearest_centroid",
        })

    return pd.DataFrame(rows)


def build_concept_verse_edge_pseu() -> None:
    """Build concept_verse_edge_deut and concept_verse_edge_pseu.

    Both use nearest-centroid projection from the pooled LXX+NT+VG concept
    centroids in SPhilBerta space. PSEU pericopes are not yet represented in
    concept-graph topology, so pericope_containment is not available for these
    strata. assignment_method='nearest_centroid' records this distinction.

    Loads the reference centroid matrix once and reuses it for both strata.
    """
    import numpy as np

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    for stratum in ("deut", "pseu"):
        config = f"concept_verse_edge_{stratum}"
        df = _project_pseu_stratum(stratum, concept_ids, concept_labels_list, centroid_unit)
        dst = _parquet_out(config)
        df.to_parquet(dst, index=False)
        concept_count = df["concept_id"].nunique()
        mean_score = df["edge_weight"].mean()
        print(
            f"  {config}: {len(df):,} rows "
            f"({concept_count} unique concepts, mean cosine={mean_score:.4f})"
        )


def build_concept_trajectory_pseu() -> None:
    """Build concept_trajectory_deut and concept_trajectory_pseu.

    Aggregates concept_verse_edge_deut/pseu to per-concept centroids.
    build_concept_verse_edge_pseu must be run first.
    """
    import numpy as np

    for stratum in ("deut", "pseu"):
        edge_path = _parquet_out(f"concept_verse_edge_{stratum}")
        if not edge_path.exists():
            raise RuntimeError(
                f"concept_verse_edge_{stratum} not found — run build_concept_verse_edge_pseu first."
            )
        cve = pd.read_parquet(edge_path)

        rows = []
        for cid, grp in cve.groupby("concept_id"):
            mats = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]])
            centroid = mats.mean(axis=0)
            cnorm = np.linalg.norm(centroid)
            centroid_unit = centroid / (cnorm + 1e-8)
            norms = np.linalg.norm(mats, axis=1, keepdims=True)
            units = mats / (norms + 1e-8)
            mean_cos = float((units @ centroid_unit).mean())
            rows.append({
                "concept_id": cid,
                "concept_label": grp["concept_label"].iloc[0],
                "stratum": stratum,
                "verse_count": len(grp),
                "centroid": centroid.tolist(),
                "mean_cosine_to_centroid": mean_cos,
                "verse_refs": grp["osis_ref"].tolist(),
                "model_id": grp["model_id"].iloc[0],
                "assignment_method": "nearest_centroid",
            })

        df = pd.DataFrame(rows).sort_values("concept_id").reset_index(drop=True)
        config = f"concept_trajectory_{stratum}"
        dst = _parquet_out(config)
        df.to_parquet(dst, index=False)
        mean_cos_all = df["mean_cosine_to_centroid"].mean()
        print(
            f"  {config}: {len(df):,} rows "
            f"({df['concept_id'].nunique()} concepts, mean coherence={mean_cos_all:.4f})"
        )


def build_concept_drift_pseu() -> None:
    """Compute PSEU-extended drift metrics across 5 new stratum transition pairs.

    Pairs: lxx→deut, lxx→pseu, deut→nt, pseu→nt, deut→pseu.
    Mirrors the Schlattmann & Vogl 2024 methodology used in build_concept_drift(),
    extending to LXX Deuterocanon (stratum 6) and Second Temple Pseudepigrapha (stratum 7).

    Inputs:
      NuBerea/concept-trajectories  concept_trajectory_sp   — lxx/nt/vg centroids
      NuBerea/concept-trajectories  concept_verse_edge_sp   — lxx/nt/vg embeddings
      NuBerea/concept-analysis      concept_trajectory_deut — deut centroids (PSEU)
      NuBerea/concept-analysis      concept_trajectory_pseu — pseu centroids (PSEU)
      NuBerea/concept-analysis      concept_verse_edge_deut — deut embeddings (PSEU)
      NuBerea/concept-analysis      concept_verse_edge_pseu — pseu embeddings (PSEU)

    Output: 78 rows (one per concept); wide format with per-stratum crystallization
    and per-pair cross-stratum drift metrics.
    """
    import numpy as np
    sys.path.insert(0, str(_THIS.parent))
    from analyze_concept_drift import cosine_sim, cross_density

    traj_sp   = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_sp").to_pandas()
    traj_deut = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_deut").to_pandas()
    traj_pseu = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_pseu").to_pandas()
    traj_all  = pd.concat([traj_sp, traj_deut, traj_pseu], ignore_index=True)
    traj_idx  = traj_all.set_index(["concept_id", "stratum"])

    cve_sp   = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas()
    cve_deut = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_deut").to_pandas()
    cve_pseu = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_pseu").to_pandas()
    cve_all  = pd.concat([cve_sp, cve_deut, cve_pseu], ignore_index=True)

    emb_index: dict[tuple, np.ndarray] = {}
    for (cid, stratum), grp in cve_all.groupby(["concept_id", "stratum"]):
        emb_index[(cid, stratum)] = np.stack(
            [np.array(e, dtype=np.float32) for e in grp["embedding"]]
        )

    all_concepts = traj_sp["concept_id"].unique()
    concept_label = (
        traj_sp.drop_duplicates("concept_id")
        .set_index("concept_id")["concept_label"]
        .to_dict()
    )

    pseu_pairs = [
        ("lxx", "deut"), ("lxx", "pseu"),
        ("deut", "nt"), ("pseu", "nt"),
        ("deut", "pseu"),
    ]
    all_strata = ["lxx", "nt", "vg", "deut", "pseu"]

    records = []
    for cid in all_concepts:
        label = concept_label.get(cid, "")
        row: dict = {"concept_id": cid, "concept_label": label}

        for s in all_strata:
            key = (cid, s)
            if key in traj_idx.index:
                row[f"verse_count_{s}"]     = int(traj_idx.loc[key, "verse_count"])
                row[f"crystallization_{s}"] = float(traj_idx.loc[key, "mean_cosine_to_centroid"])
                row[f"dispersion_{s}"]      = 1.0 - row[f"crystallization_{s}"]
            else:
                row[f"verse_count_{s}"]     = 0
                row[f"crystallization_{s}"] = float("nan")
                row[f"dispersion_{s}"]      = float("nan")

        for s_a, s_b in pseu_pairs:
            tag   = f"{s_a}_{s_b}"
            key_a = (cid, s_a)
            key_b = (cid, s_b)
            have_a = key_a in traj_idx.index
            have_b = key_b in traj_idx.index

            if have_a and have_b:
                c_a = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32)
                c_b = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32)
                cc  = cosine_sim(c_a, c_b)
                row[f"centroid_cosine_{tag}"] = cc
                row[f"centroid_drift_{tag}"]  = 1.0 - cc
            else:
                row[f"centroid_cosine_{tag}"] = float("nan")
                row[f"centroid_drift_{tag}"]  = float("nan")

            d_a = row[f"dispersion_{s_a}"]
            d_b = row[f"dispersion_{s_b}"]
            row[f"delta_dispersion_{tag}"] = (
                d_b - d_a
                if (not np.isnan(d_a) and not np.isnan(d_b))
                else float("nan")
            )

            if have_a and key_b in emb_index:
                c_a   = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32)
                emb_b = emb_index[key_b]
                cd_ab = cross_density(emb_b, c_a)
                row[f"cross_density_{tag}"] = cd_ab
                row[f"cross_drift_{tag}"]   = 1.0 - cd_ab
            else:
                row[f"cross_density_{tag}"] = float("nan")
                row[f"cross_drift_{tag}"]   = float("nan")

            if have_b and key_a in emb_index:
                c_b   = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32)
                emb_a = emb_index[key_a]
                row[f"cross_density_{s_b}_{s_a}"] = cross_density(emb_a, c_b)
            else:
                row[f"cross_density_{s_b}_{s_a}"] = float("nan")

            cd_tag = row[f"centroid_drift_{tag}"]
            xd_tag = row[f"cross_drift_{tag}"]
            both_ok = not np.isnan(cd_tag) and not np.isnan(xd_tag)
            row[f"drift_score_{tag}"] = (cd_tag + xd_tag) / 2.0 if both_ok else float("nan")

        records.append(row)

    df = pd.DataFrame(records)
    dst = _parquet_out("concept_drift_itp")
    df.to_parquet(dst, index=False)
    print(f"  concept_drift_itp: {len(df)} rows, {len(df.columns)} cols — 5 PSEU drift pairs (lxx→deut/pseu, deut/pseu→nt, deut→pseu)")


def build_concept_aliases() -> None:
    """Build concept_aliases (TF-IDF English term → bt1_xxx mapping) from HF inputs.

    Fully HF-native: loads bi_encoder_v1 + question_bin_assignment.json from
    NuBerea/AI-models and L1 centroids from NuBerea/concept-graph, then runs the
    BERTopic alias TF-IDF logic. See build_aliases_from_hf.py for details.
    """
    from build_aliases_from_hf import build_aliases_dataframe

    df = build_aliases_dataframe()
    dst = _parquet_out("concept_aliases")
    df.to_parquet(dst, index=False)
    print(f"  concept_aliases: {len(df)} rows, {len(df.columns)} cols — built HF-native")


def build_concept_verse_edge_patr() -> None:
    """Project patristic GRC segments onto concept centroids via nearest-centroid assignment.

    Loads pre-computed SPhilBerta embeddings from NuBerea/features
    (patr_grc_embeddings_sp, ~40K rows) and assigns each segment to its
    nearest concept from the pooled LXX+NT+VG reference centroids.

    Output schema matches concept_verse_edge_pseu but uses `segment_id` instead
    of `osis_ref` and adds `cts_urn`, `author_label`, and `family_id` fields
    for downstream patristic-specific joins.
    """
    import numpy as np

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    print("  Loading patristics embeddings from NuBerea/features (patr_grc_embeddings_sp)...")
    patr_df = load_hf_or_local("NuBerea/features", "patr_grc_embeddings_sp").to_pandas()
    print(f"  Loaded {len(patr_df):,} patristic GRC segments")

    emb_matrix = np.stack([np.asarray(e, dtype=np.float32) for e in patr_df["embedding"]])
    emb_norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True)
    emb_unit = emb_matrix / (emb_norms + 1e-8)

    cos_scores = emb_unit @ centroid_unit.T  # (n_segments, n_concepts)
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(patr_df)), best_idx]

    rows = []
    for i, (_, seg_row) in enumerate(patr_df.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id": concept_ids[ci],
            "concept_label": concept_labels_list[ci],
            "segment_id": seg_row["segment_id"],
            "cts_urn": seg_row["cts_urn"],
            "author_label": seg_row["author_label"],
            "family_id": seg_row["family_id"],
            "stratum": "patr",
            "edge_weight": float(best_score[i]),
            "embedding": seg_row["embedding"],
            "model_id": seg_row["model_id"],
            "assignment_method": "nearest_centroid",
        })

    df = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_patr")
    df.to_parquet(dst, index=False)
    concept_count = df["concept_id"].nunique()
    mean_score = df["edge_weight"].mean()
    print(
        f"  concept_verse_edge_patr: {len(df):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f}, "
        f"{df['family_id'].nunique()} families)"
    )


_TARGUM_OSIS_MAP: dict[str, str] = {
    # Torah
    "Genesis": "Gen", "Exodus": "Exod", "Leviticus": "Lev",
    "Numbers": "Num", "Deuteronomy": "Deut",
    # Former Prophets
    "Joshua": "Josh", "Judges": "Judg", "Ruth": "Ruth",
    "I Samuel": "1Sam", "II Samuel": "2Sam",
    "I Kings": "1Kgs", "II Kings": "2Kgs",
    # Latter Prophets
    "Isaiah": "Isa", "Jeremiah": "Jer", "Ezekiel": "Ezek",
    "Hosea": "Hos", "Joel": "Joel", "Amos": "Amos", "Obadiah": "Obad",
    "Jonah": "Jonah", "Micah": "Mic", "Nahum": "Nah", "Habakkuk": "Hab",
    "Zephaniah": "Zeph", "Haggai": "Hag", "Zechariah": "Zech", "Malachi": "Mal",
    # Writings
    "Psalms": "Ps", "Proverbs": "Prov", "Job": "Job",
    "Song of Songs": "Song", "Lamentations": "Lam", "Ecclesiastes": "Eccl",
    "Esther": "Esth", "Daniel": "Dan", "Ezra": "Ezra", "Nehemiah": "Neh",
    "I Chronicles": "1Chr", "II Chronicles": "2Chr",
}


def _embed_texts_sphilberta(texts: list[str], batch_size: int = 32) -> tuple:
    """Embed texts with SPhilBerta. Returns (vecs: np.ndarray float32, model_id: str)."""
    from sentence_transformers import SentenceTransformer
    import torch

    model_id = "bowphs/SPhilBerta"
    if torch.backends.mps.is_available():
        device = "mps"
    elif torch.cuda.is_available():
        device = "cuda"
    else:
        device = "cpu"
    print(f"    Loading {model_id} on {device}...")
    model = SentenceTransformer(model_id, device=device)
    print(f"    Embedding {len(texts):,} texts (batch_size={batch_size})...")
    vecs = model.encode(
        texts,
        batch_size=batch_size,
        show_progress_bar=True,
        normalize_embeddings=False,
        convert_to_numpy=True,
    )
    return vecs.astype("float32"), model_id


def build_concept_verse_edge_philo() -> None:
    """Project Philo of Alexandria GRC segments onto concept centroids.

    Loads philo_grc from NuBerea/secondary-sources (7,906 rows), embeds with
    SPhilBerta, and assigns each segment to its nearest concept centroid.
    Schema mirrors concept_verse_edge_patr.
    """
    import numpy as np

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    print("  Loading philo_grc from NuBerea/secondary-sources...")
    philo_df = load_hf_or_local("NuBerea/secondary-sources", "philo_grc").to_pandas()
    print(f"  Loaded {len(philo_df):,} Philo segments")

    vecs, model_id = _embed_texts_sphilberta(philo_df["text"].tolist())

    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs_unit = vecs / (norms + 1e-8)
    cos_scores = vecs_unit @ centroid_unit.T
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(philo_df)), best_idx]

    rows = []
    for i, (_, seg) in enumerate(philo_df.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id": concept_ids[ci],
            "concept_label": concept_labels_list[ci],
            "segment_id": seg["segment_id"],
            "cts_urn": seg["cts_urn"],
            "author_label": seg["author_label"],
            "work_label": seg["work_label"],
            "stratum": "philo",
            "edge_weight": float(best_score[i]),
            "embedding": vecs[i],
            "model_id": model_id,
            "assignment_method": "nearest_centroid",
        })

    df = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_philo")
    df.to_parquet(dst, index=False)
    concept_count = df["concept_id"].nunique()
    mean_score = df["edge_weight"].mean()
    print(
        f"  concept_verse_edge_philo: {len(df):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f})"
    )


def build_concept_verse_edge_josephus() -> None:
    """Project Josephus GRC segments onto concept centroids.

    Loads josephus_grc from NuBerea/secondary-sources (12,735 rows), embeds with
    SPhilBerta, and assigns each segment to its nearest concept centroid.
    """
    import numpy as np

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    print("  Loading josephus_grc from NuBerea/secondary-sources...")
    jos_df = load_hf_or_local("NuBerea/secondary-sources", "josephus_grc").to_pandas()
    print(f"  Loaded {len(jos_df):,} Josephus segments")

    vecs, model_id = _embed_texts_sphilberta(jos_df["text"].tolist())

    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs_unit = vecs / (norms + 1e-8)
    cos_scores = vecs_unit @ centroid_unit.T
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(jos_df)), best_idx]

    rows = []
    for i, (_, seg) in enumerate(jos_df.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id": concept_ids[ci],
            "concept_label": concept_labels_list[ci],
            "segment_id": seg["segment_id"],
            "cts_urn": seg["cts_urn"],
            "author_label": seg["author_label"],
            "work_label": seg["work_label"],
            "stratum": "josephus",
            "edge_weight": float(best_score[i]),
            "embedding": vecs[i],
            "model_id": model_id,
            "assignment_method": "nearest_centroid",
        })

    df = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_josephus")
    df.to_parquet(dst, index=False)
    concept_count = df["concept_id"].nunique()
    mean_score = df["edge_weight"].mean()
    print(
        f"  concept_verse_edge_josephus: {len(df):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f})"
    )


def build_concept_verse_edge_targum() -> None:
    """Project Targum (Aramaic OT paraphrase) English translations onto concept centroids.

    Loads targum config from NuBerea/second-temple (~28K rows), embeds text_en
    with SPhilBerta (Aramaic is unvalidated; English preserves interpretive content),
    and assigns each verse to its nearest concept centroid. Derives canonical osis_ref
    from book + section_0 (chapter) + section_1 (verse) for downstream pericope joins.
    """
    import numpy as np

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    print("  Loading targum from NuBerea/second-temple...")
    tg_df = load_hf_or_local("NuBerea/second-temple", "targum").to_pandas()
    print(f"  Loaded {len(tg_df):,} Targum rows")

    # Drop rows with no English translation
    tg_df = tg_df[tg_df["text_en"].notna() & (tg_df["text_en"].str.strip() != "")].copy()
    print(f"  {len(tg_df):,} rows with text_en available")

    texts = tg_df["text_en"].tolist()
    vecs, model_id = _embed_texts_sphilberta(texts)

    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs_unit = vecs / (norms + 1e-8)
    cos_scores = vecs_unit @ centroid_unit.T
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(tg_df)), best_idx]

    def _osis_book_from_targum(book: str, targum_name: str | None) -> str | None:
        osis = _TARGUM_OSIS_MAP.get(book)
        if osis:
            return osis
        # book is typically "{targum_name} {canonical_name}" — strip the prefix
        prefix = (targum_name or "").strip()
        if prefix and book.startswith(prefix + " "):
            osis = _TARGUM_OSIS_MAP.get(book[len(prefix) + 1:])
        if osis:
            return osis
        # Fallback: try each word-count suffix (handles unexpected prefix variants)
        words = book.split()
        for skip in range(1, len(words)):
            osis = _TARGUM_OSIS_MAP.get(" ".join(words[skip:]))
            if osis:
                return osis
        return None

    rows = []
    for i, (_, seg) in enumerate(tg_df.iterrows()):
        ci = int(best_idx[i])
        book = seg.get("book") or ""
        targum_name = seg.get("targum_name")
        osis_book = _osis_book_from_targum(book, targum_name)
        s0 = seg.get("section_0")
        s1 = seg.get("section_1")
        if osis_book and s0 is not None and s1 is not None:
            osis_ref = f"{osis_book}.{int(s0) + 1}.{int(s1) + 1}"
        elif osis_book and s0 is not None:
            osis_ref = f"{osis_book}.{int(s0) + 1}"
        else:
            osis_ref = None
        rows.append({
            "concept_id": concept_ids[ci],
            "concept_label": concept_labels_list[ci],
            "segment_id": seg["segment_id"],
            "osis_ref": osis_ref,
            "targum_name": seg.get("targum_name"),
            "section": seg.get("section"),
            "book": book,
            "stratum": "targum",
            "edge_weight": float(best_score[i]),
            "embedding": vecs[i],
            "model_id": model_id,
            "assignment_method": "nearest_centroid",
        })

    df = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_targum")
    df.to_parquet(dst, index=False)
    concept_count = df["concept_id"].nunique()
    mean_score = df["edge_weight"].mean()
    osis_coverage = df["osis_ref"].notna().mean()
    print(
        f"  concept_verse_edge_targum: {len(df):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f}, "
        f"osis_ref coverage={osis_coverage:.1%})"
    )


def build_concept_verse_edge_talmud() -> None:
    """Project Talmud English translations onto concept centroids.

    Reads mishnah and tosefta directly from NuBerea/talmud via HfFileSystem
    (load_dataset fails on this repo; parquets are read directly). Bavli and
    yerushalmi are skipped until their parquets are uploaded. Embeds text_en
    with SPhilBerta (Mishnaic Hebrew and Talmudic Aramaic are unembeddable
    directly; English translations preserve interpretive content).

    Stratum values: mishnah (~200 CE), tosefta (~220 CE).
    """
    import numpy as np
    from huggingface_hub import HfFileSystem

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    fs = HfFileSystem()
    _TALMUD_PATHS = [
        ("datasets/NuBerea/talmud/data/mishnah/train-00000-of-00001.parquet", "mishnah"),
        ("datasets/NuBerea/talmud/data/tosefta/train-00000-of-00001.parquet", "tosefta"),
    ]

    all_dfs: list[pd.DataFrame] = []
    for hf_path, stratum in _TALMUD_PATHS:
        try:
            df = pd.read_parquet(fs.open(hf_path))
        except Exception as e:  # noqa: BLE001  best-effort catch (logs/records)
            print(f"  Skipping talmud/{stratum}: {e}")
            continue
        if len(df) == 0:
            print(f"  Skipping talmud/{stratum}: empty")
            continue
        total = len(df)
        df = df[df["text_en"].notna() & (df["text_en"].str.strip() != "")].copy()
        df["_stratum"] = stratum
        print(f"  talmud/{stratum}: {len(df):,} rows with text_en (of {total:,} total)")
        all_dfs.append(df)

    if not all_dfs:
        print("  No Talmud data available — skipping")
        return

    combined = pd.concat(all_dfs, ignore_index=True)
    print(f"  Total: {len(combined):,} Talmud rows across {len(all_dfs)} config(s)")

    texts = combined["text_en"].tolist()
    vecs, model_id = _embed_texts_sphilberta(texts, batch_size=128)

    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs_unit = vecs / (norms + 1e-8)
    cos_scores = vecs_unit @ centroid_unit.T
    best_idx = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(combined)), best_idx]

    rows = []
    for i, (_, seg) in enumerate(combined.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id":        concept_ids[ci],
            "concept_label":     concept_labels_list[ci],
            "segment_id":        seg["segment_id"],
            "ref":               seg.get("ref"),
            "title":             seg.get("title"),
            "tractate":          seg.get("tractate"),
            "order":             seg.get("order"),
            "stratum":           seg["_stratum"],
            "edge_weight":       float(best_score[i]),
            "embedding":         vecs[i],
            "model_id":          model_id,
            "assignment_method": "nearest_centroid",
        })

    df_out = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_talmud")
    df_out.to_parquet(dst, index=False)
    concept_count = df_out["concept_id"].nunique()
    mean_score = df_out["edge_weight"].mean()
    strata = df_out["stratum"].value_counts().to_dict()
    print(
        f"  concept_verse_edge_talmud: {len(df_out):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f})"
    )
    print(f"  Strata: {strata}")


def build_concept_verse_edge_nhc() -> None:
    """Project Nag Hammadi Corpus segments onto concept centroids.

    Reuses pre-computed SPhilBerta embeddings from NuBerea/features →
    gnostic_ln_bridge rather than re-running inference.  The embedding
    column is a 768-dim float32 vector already L2-normalised at build time.
    """
    import numpy as np
    from datasets import load_dataset

    concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids()

    ds = load_dataset("NuBerea/features", "gnostic_ln_bridge", split="train")
    df = ds.to_pandas()

    emb_col = df["embedding"].tolist()
    vecs = np.array(emb_col, dtype=np.float32)
    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs_unit = vecs / (norms + 1e-8)

    cos_scores = vecs_unit @ centroid_unit.T
    best_idx   = cos_scores.argmax(axis=1)
    best_score = cos_scores[np.arange(len(df)), best_idx]

    rows = []
    for i, (_, seg) in enumerate(df.iterrows()):
        ci = int(best_idx[i])
        rows.append({
            "concept_id":        concept_ids[ci],
            "concept_label":     concept_labels_list[ci],
            "segment_id":        seg["segment_id"],
            "codex":             seg.get("codex"),
            "tractate_num":      seg.get("tractate_num"),
            "work_slug":         seg.get("work_slug"),
            "work_title":        seg.get("work_title"),
            "stratum":           "nhc",
            "edge_weight":       float(best_score[i]),
            "embedding":         vecs[i],
            "model_id":          "bowphs/SPhilBerta",
            "assignment_method": "nearest_centroid",
        })

    df_out = pd.DataFrame(rows)
    dst = _parquet_out("concept_verse_edge_nhc")
    df_out.to_parquet(dst, index=False)
    concept_count = df_out["concept_id"].nunique()
    mean_score    = df_out["edge_weight"].mean()
    print(
        f"  concept_verse_edge_nhc: {len(df_out):,} rows "
        f"({concept_count} unique concepts, mean cosine={mean_score:.4f})"
    )


# ──────────────────────────────────────────────────────────────────────────────
# concept_trajectory_series + concept_drift_sequential
# Corpus-timeline view: per-concept centroids across 11 strata in temporal order
# (OT-LXX → PSEU → Philo/Josephus → NT → Patristics → Targum/Mishnah/Tosefta → VG)
# ──────────────────────────────────────────────────────────────────────────────

_SERIES_STRATA = [
    # (stratum_name, stratum_order, language, edge_config, stratum_filter)
    # stratum_filter: column value to select when one config covers multiple strata
    ("lxx",      1,  "grc", "concept_verse_edge_sp",       "lxx"),
    ("deut",     2,  "grc", "concept_verse_edge_deut",     None),
    ("pseu",     3,  "grc", "concept_verse_edge_pseu",     None),
    ("philo",    4,  "grc", "concept_verse_edge_philo",    None),
    ("nt",       5,  "grc", "concept_verse_edge_sp",       "nt"),
    ("josephus", 6,  "grc", "concept_verse_edge_josephus", None),
    ("patr",     7,  "grc", "concept_verse_edge_patr",     None),
    ("targum",   8,  "en",  "concept_verse_edge_targum",   None),
    ("mishnah",  9,  "en",  "concept_verse_edge_talmud",   "mishnah"),
    ("tosefta",  10, "en",  "concept_verse_edge_talmud",   "tosefta"),
    ("vg",       11, "lat", "concept_verse_edge_sp",       "vg"),
]

_SERIES_PAIRS = [
    # (stratum_a, stratum_b, pair_order)
    # patr→targum (pair 7) and tosefta→vg (pair 10) are cross-language
    ("lxx",      "deut",      1),
    ("deut",     "pseu",      2),
    ("pseu",     "philo",     3),
    ("philo",    "nt",        4),
    ("nt",       "josephus",  5),
    ("josephus", "patr",      6),
    ("patr",     "targum",    7),
    ("targum",   "mishnah",   8),
    ("mishnah",  "tosefta",   9),
    ("tosefta",  "vg",       10),
]


def build_concept_trajectory_series() -> None:
    """Per-concept centroids across all 11 strata in temporal order.

    Long format: ~858 rows (78 concepts × up to 11 strata).
    Crystallization = mean cosine of member embeddings to their own per-stratum centroid.
    mean_edge_weight = mean cosine to the reference centroid (pooled LXX+NT+VG).

    Strata with no segments for a concept are omitted (so row count may be <858).
    concept_verse_edge_sp is loaded once and reused for lxx, nt, vg strata.
    concept_verse_edge_talmud is loaded once and reused for mishnah, tosefta strata.
    """
    import numpy as np

    _cache: dict[str, pd.DataFrame] = {}
    all_rows: list[dict] = []

    for stratum, stratum_order, language, edge_config, stratum_filter in _SERIES_STRATA:
        print(f"  [{stratum_order}/11] {stratum}{edge_config}...")
        if edge_config not in _cache:
            _cache[edge_config] = load_hf_or_local(
                "NuBerea/concept-analysis", edge_config
            ).to_pandas()
        df = _cache[edge_config].copy()

        if stratum_filter is not None:
            df = df[df["stratum"] == stratum_filter]

        if len(df) == 0:
            print(f"    Skipping {stratum}: no rows")
            continue

        model_id = str(df["model_id"].iloc[0]) if "model_id" in df.columns else "SPhilBerta"

        for cid, grp in df.groupby("concept_id"):
            embs = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]])

            centroid = embs.mean(axis=0)
            cnorm = np.linalg.norm(centroid)
            centroid_unit = centroid / (cnorm + 1e-8)

            norms = np.linalg.norm(embs, axis=1, keepdims=True)
            units = embs / (norms + 1e-8)
            crystallization = float((units @ centroid_unit).mean())

            all_rows.append({
                "concept_id":       cid,
                "concept_label":    grp["concept_label"].iloc[0],
                "stratum":          stratum,
                "stratum_order":    stratum_order,
                "language":         language,
                "verse_count":      len(grp),
                "mean_edge_weight": float(grp["edge_weight"].mean()),
                "crystallization":  crystallization,
                "centroid":         centroid.tolist(),
                "model_id":         model_id,
            })

        n_concepts = df["concept_id"].nunique()
        print(f"    {stratum}: {len(df):,} segments → {n_concepts} concept groups")

    result = (
        pd.DataFrame(all_rows)
        .sort_values(["concept_id", "stratum_order"])
        .reset_index(drop=True)
    )
    dst = _parquet_out("concept_trajectory_series")
    result.to_parquet(dst, index=False)
    print(
        f"  concept_trajectory_series: {len(result):,} rows "
        f"({result['concept_id'].nunique()} concepts × "
        f"{result['stratum'].nunique()} strata)"
    )


def build_concept_drift_sequential() -> None:
    """Adjacent-pair drift across the 11-stratum corpus timeline.

    Reads concept_trajectory_series (must be built first).
    Outputs ~780 rows (78 concepts × 10 adjacent pairs).
    same_language=False marks cross-language pairs (patr→targum, tosefta→vg)
    where centroid_drift is confounded by model-language mismatch.

    centroid_drift = 1 − cosine(centroid_a, centroid_b); range [0, 2].
    delta_crystallization = crystallization_b − crystallization_a.
    delta_mean_edge_weight = mean_edge_weight_b − mean_edge_weight_a.
    """
    import numpy as np

    series_path = _parquet_out("concept_trajectory_series")
    if not series_path.exists():
        raise RuntimeError(
            "concept_trajectory_series not found — "
            "run build_concept_trajectory_series first."
        )

    traj = pd.read_parquet(series_path)
    traj_idx = traj.set_index(["concept_id", "stratum"])
    lang_map = traj.drop_duplicates("stratum").set_index("stratum")["language"].to_dict()
    concept_ids = traj["concept_id"].unique()

    all_rows: list[dict] = []
    for stratum_a, stratum_b, pair_order in _SERIES_PAIRS:
        lang_a = lang_map.get(stratum_a, "?")
        lang_b = lang_map.get(stratum_b, "?")

        for cid in concept_ids:
            try:
                row_a = traj_idx.loc[(cid, stratum_a)]
                row_b = traj_idx.loc[(cid, stratum_b)]
            except KeyError:
                continue

            c_a = np.asarray(row_a["centroid"], dtype=np.float32)
            c_b = np.asarray(row_b["centroid"], dtype=np.float32)
            c_a_u = c_a / (np.linalg.norm(c_a) + 1e-8)
            c_b_u = c_b / (np.linalg.norm(c_b) + 1e-8)
            cos_sim = float(np.dot(c_a_u, c_b_u))

            all_rows.append({
                "concept_id":             cid,
                "concept_label":          row_a["concept_label"],
                "stratum_a":              stratum_a,
                "stratum_b":              stratum_b,
                "pair_order":             pair_order,
                "language_a":             lang_a,
                "language_b":             lang_b,
                "same_language":          lang_a == lang_b,
                "centroid_cosine":        cos_sim,
                "centroid_drift":         1.0 - cos_sim,
                "delta_crystallization":  float(row_b["crystallization"] - row_a["crystallization"]),
                "delta_mean_edge_weight": float(row_b["mean_edge_weight"] - row_a["mean_edge_weight"]),
            })

    result = (
        pd.DataFrame(all_rows)
        .sort_values(["concept_id", "pair_order"])
        .reset_index(drop=True)
    )
    dst = _parquet_out("concept_drift_sequential")
    result.to_parquet(dst, index=False)
    n_pairs = result["pair_order"].nunique()
    same_lang_count = int(result["same_language"].sum())
    print(
        f"  concept_drift_sequential: {len(result):,} rows "
        f"({n_pairs} pairs × ~{len(result) // max(n_pairs, 1)} concepts; "
        f"{same_lang_count} same-language rows)"
    )


CONFIGS = {
    "concept_verse_edge":          lambda: import_trajectory_config("concept_verse_edge"),
    "concept_trajectory":          lambda: import_trajectory_config("concept_trajectory"),
    "concept_verse_edge_sp":       lambda: import_trajectory_config("concept_verse_edge_sp"),
    "concept_trajectory_sp":       lambda: import_trajectory_config("concept_trajectory_sp"),
    "concept_verse_edge_bt":       build_concept_verse_edge_bt,
    "concept_trajectory_bt":       build_concept_trajectory_bt,
    "concept_verse_edge_pseu":     build_concept_verse_edge_pseu,
    "concept_trajectory_pseu":     build_concept_trajectory_pseu,
    "concept_drift":               build_concept_drift,
    "concept_drift_itp":           build_concept_drift_pseu,
    "concept_drift_hamilton":      build_concept_drift_hamilton,
    "community_candidate":         lambda: import_community_config("community_candidate"),
    "community_membership":        lambda: import_community_config("community_membership"),
    "concept_centroids":           build_concept_centroids,
    "concept_aliases":             build_concept_aliases,
    "concept_verse_edge_patr":     build_concept_verse_edge_patr,
    "concept_verse_edge_philo":    build_concept_verse_edge_philo,
    "concept_verse_edge_josephus": build_concept_verse_edge_josephus,
    "concept_verse_edge_targum":   build_concept_verse_edge_targum,
    "concept_verse_edge_talmud":   build_concept_verse_edge_talmud,
    "concept_verse_edge_nhc":      build_concept_verse_edge_nhc,
    "concept_trajectory_series":   build_concept_trajectory_series,
    "concept_drift_sequential":    build_concept_drift_sequential,
}


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="Build only this config")
    args = parser.parse_args()

    configs = {args.config: CONFIGS[args.config]} if args.config else CONFIGS
    if args.config and args.config not in CONFIGS:
        print(f"Unknown config '{args.config}'. Valid: {list(CONFIGS)}")
        raise SystemExit(1)

    print(f"Building {len(configs)} concept-analysis config(s) ...")
    for name, fn in configs.items():
        fn()

    print(f"\nDone. Output in {OUT}")


if __name__ == "__main__":
    main()