File size: 71,046 Bytes
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
ac04b84
1bd5e76
1f231e9
1bd5e76
 
 
 
 
 
 
 
 
 
aa7a784
1bd5e76
 
 
ecfe7f5
 
1bcc6c0
e1e2e3d
ac04b84
ecfe7f5
 
1bcc6c0
e1e2e3d
ac04b84
ecfe7f5
1bd5e76
1f231e9
e1c252e
1f231e9
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
85f00da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
85f00da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1c252e
85f00da
 
e1c252e
 
 
85f00da
 
 
e1c252e
 
 
 
 
 
 
 
85f00da
 
ac04b84
85f00da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f00da
 
1bd5e76
 
 
 
 
85f00da
 
 
1bd5e76
 
 
 
 
 
 
ac04b84
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f00da
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
aa7a784
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
 
 
1bd5e76
 
 
 
 
aa7a784
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
1bd5e76
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
aa7a784
 
 
 
 
 
 
 
1bd5e76
 
 
aa7a784
 
 
 
 
 
 
 
 
 
1bd5e76
aa7a784
 
 
 
 
 
 
1bd5e76
aa7a784
1bd5e76
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bcc6c0
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac04b84
aa7a784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f231e9
aa7a784
 
 
 
 
 
 
1f231e9
 
 
 
 
 
aa7a784
 
 
1bd5e76
 
 
1f231e9
 
 
 
aa7a784
 
 
 
ecfe7f5
 
 
1bd5e76
 
 
 
 
ecfe7f5
1bd5e76
 
 
 
 
 
4a0d2b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
ac04b84
1bd5e76
 
 
 
85f00da
 
1bd5e76
e1e2e3d
 
 
1bd5e76
ecfe7f5
 
 
 
 
 
 
 
 
85f00da
1bd5e76
1bcc6c0
 
 
 
ac04b84
e1c252e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac04b84
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
4a0d2b0
 
24c3b46
4a0d2b0
 
 
 
 
 
 
 
 
 
 
 
 
24c3b46
 
 
 
 
 
e1e2e3d
 
 
 
 
 
24c3b46
 
 
 
 
 
 
1bd5e76
 
4a0d2b0
 
24c3b46
 
ecfe7f5
ac04b84
 
e1c252e
 
1bcc6c0
e1e2e3d
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d44b077
1bd5e76
 
 
 
d44b077
aa7a784
d44b077
 
 
 
1bd5e76
1f231e9
 
1bd5e76
85f00da
1bd5e76
 
4a0d2b0
ecfe7f5
1bd5e76
 
ecfe7f5
 
 
1bd5e76
ecfe7f5
 
 
 
 
1bd5e76
 
 
 
 
 
 
85f00da
 
ecfe7f5
85f00da
 
 
 
 
1bd5e76
 
d44b077
 
 
 
 
 
 
 
 
 
1bd5e76
1f231e9
 
 
85f00da
4a0d2b0
 
 
ecfe7f5
 
 
 
4a0d2b0
 
ecfe7f5
 
 
 
 
4a0d2b0
 
 
85f00da
1f231e9
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
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
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
#!/usr/bin/env python3
"""Build the Sphregis beta dataset from frozen Ancient Greek treebanks.

The build is deliberately source-driven: source repositories are not vendored in
the dataset repository.  Pass their checkout root with ``--sources``.  Every
published row records the exact upstream commit used by the build.
"""

from __future__ import annotations

import argparse
import hashlib
import html
import io
import json
import random
import re
import subprocess
import unicodedata
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
from typing import Iterable

import edlib
import pyarrow as pa
import pyarrow.parquet as pq

try:
    from scripts.dataset_variants import make_dataset_variants, variant_schema
    from scripts.metrical_lines import load_public_metrical_lines, public_metrical_line
    from scripts.text_units import load_text_units
    from scripts.vendor.conll18_ud_eval import UDError, load_conllu
except ModuleNotFoundError:  # Direct execution from the scripts directory.
    from dataset_variants import make_dataset_variants, variant_schema
    from metrical_lines import load_public_metrical_lines, public_metrical_line
    from text_units import load_text_units
    from vendor.conll18_ud_eval import UDError, load_conllu


RANDOM_SEED = 776
SAFE_CONLLU_MISC_KEYS = {"NativeRel", "NativeHead", "HeadRepair", "SpaceAfter"}


SOURCE_INFO = {
    "agdt": {
        "directory": "treebank_data",
        "url": "https://github.com/PerseusDL/treebank_data",
        "license": "CC-BY-SA-3.0-US",
        "annotation": "manual syntax; Morpheus-assisted morphology; normalized in AGDT 2.1",
        "scheme": "AGDT/ALDT",
    },
    "ud_perseus": {
        "directory": "perseus",
        "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-Perseus",
        "license": "CC-BY-NC-SA-2.5",
        "annotation": "UD conversion of manually annotated AGDT syntax",
        "scheme": "Universal Dependencies 2",
    },
    "ud_proiel": {
        "directory": "proiel",
        "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-PROIEL",
        "license": "CC-BY-NC-SA-3.0",
        "annotation": "UD conversion of manually annotated PROIEL data",
        "scheme": "Universal Dependencies 2",
    },
    "ud_ptnk": {
        "directory": "ptnk",
        "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-PTNK",
        "license": "CC-BY-SA-4.0",
        "annotation": "cross-lingual projection with automatic and manual correction",
        "scheme": "Universal Dependencies 2",
    },
    "gorman": {
        "directory": "gorman",
        "url": "https://github.com/vgorman1/Greek-Dependency-Trees",
        # The README says NC; the bundled license text omits NC. Use the
        # conservative interpretation until the maintainer resolves it.
        "license": "CC-BY-NC-SA-4.0 (conservative; upstream files conflict)",
        "annotation": "hand annotated, or hand corrected after preparsing",
        "scheme": "AGDT/Arethusa",
    },
    "pedalion": {
        "directory": "pedalion",
        "url": "https://github.com/perseids-publications/pedalion-trees",
        "license": "CC-BY-SA-4.0",
        "annotation": "human corrected after automatic preparsing; beta annotations",
        "scheme": "AGDT/Arethusa",
    },
    "harrington": {
        "directory": "harrington",
        "url": "https://github.com/perseids-publications/harrington-trees",
        "license": "CC-BY-SA-4.0",
        "annotation": "student annotation edited by J. Matthew Harrington",
        "scheme": "Harrington/Arethusa",
    },
    "hypotactic": {
        "directory": "hypotactic",
        "url": "https://github.com/Urdatorn/hypotactic",
        "license": "CC-BY-4.0",
        "annotation": "human metrical annotation by David Chamberlain",
        "scheme": "Hypotactic scansion HTML",
    },
}


AGDT_WORKS = {
    "tlg0003.tlg001": ("Thucydides", "Histories, Book 1", "prose"),
    "tlg0007.tlg004": ("Plutarch", "Lycurgus", "prose"),
    "tlg0007.tlg015": ("Plutarch", "Alcibiades", "prose"),
    "tlg0008.tlg001": ("Athenaeus", "Deipnosophists, Books 12–13", "prose"),
    "tlg0011.tlg001": ("Sophocles", "Trachiniae", "verse"),
    "tlg0011.tlg002": ("Sophocles", "Antigone", "verse"),
    "tlg0011.tlg003": ("Sophocles", "Ajax", "verse"),
    "tlg0011.tlg004": ("Sophocles", "Oedipus Tyrannus", "verse"),
    "tlg0011.tlg005": ("Sophocles", "Electra", "verse"),
    "tlg0012.tlg001": ("Homer", "Iliad", "verse"),
    "tlg0012.tlg002": ("Homer", "Odyssey", "verse"),
    "tlg0013.tlg002": ("Pseudo-Homer", "Hymn to Demeter", "verse"),
    "tlg0016.tlg001": ("Herodotus", "Histories, Book 1", "prose"),
    "tlg0020.tlg001": ("Hesiod", "Theogony", "verse"),
    "tlg0020.tlg002": ("Hesiod", "Works and Days", "verse"),
    "tlg0020.tlg003": ("Hesiod", "Shield of Heracles", "verse"),
    "tlg0059.tlg001": ("Plato", "Euthyphro", "prose"),
    "tlg0060.tlg001": ("Diodorus Siculus", "Library, Book 11", "prose"),
    "tlg0085.tlg001": ("Aeschylus", "Suppliants", "verse"),
    "tlg0085.tlg002": ("Aeschylus", "Persians", "verse"),
    "tlg0085.tlg003": ("Aeschylus", "Prometheus Bound", "verse"),
    "tlg0085.tlg004": ("Aeschylus", "Seven Against Thebes", "verse"),
    "tlg0085.tlg005": ("Aeschylus", "Agamemnon", "verse"),
    "tlg0085.tlg006": ("Aeschylus", "Libation Bearers", "verse"),
    "tlg0085.tlg007": ("Aeschylus", "Eumenides", "verse"),
    "tlg0096.tlg002": ("Aesop", "Fables 1–50", "prose"),
    "tlg0540.tlg001": ("Lysias", "On the Murder of Eratosthenes", "prose"),
    "tlg0540.tlg014": ("Lysias", "Against Alcibiades 1", "prose"),
    "tlg0540.tlg015": ("Lysias", "Against Alcibiades 2", "prose"),
    "tlg0540.tlg023": ("Lysias", "Against Pancleon", "prose"),
    "tlg0543.tlg001": ("Polybius", "Histories, Book 1", "prose"),
    "tlg0548.tlg001": ("Pseudo-Apollodorus", "Library 1.1.1–1.4.1", "prose"),
}


# Hypotactic file stems aligned to human treebanks.  Booked works expand below.
VERSE_LINKS = {
    "tlg0012.tlg001": {"files": [f"iliad{i}" for i in range(1, 25)]},
    "tlg0012.tlg002": {"files": [f"odyssey{i}" for i in range(1, 25)]},
    "tlg0013.tlg002": {"files": ["HHDemeter"]},
    "tlg0020.tlg001": {"files": ["theogony"]},
    "tlg0020.tlg002": {"files": ["worksanddays"]},
    "tlg0020.tlg003": {"files": ["scutum"]},
    "tlg0085.tlg002": {"files": ["persians"]},
    "tlg0085.tlg003": {"files": ["prometheus"]},
    "tlg0085.tlg004": {"files": ["seven"]},
    "pedalion:batracho.xml": {"files": ["batmumach"]},
    "pedalion:semonides.xml": {"files": ["semonides"]},
    "pedalion:theoc.xml": {"files": ["theoc1", "theoc2", "theoc3", "theoc4"]},
}


PEDALION_VERSE = {
    "achar.xml",
    "thesmo.xml",
    "euripides_medea.xml",
    "ez.xml",
    "batracho.xml",
    "menander_dyskolos.xml",
    "sappho.xml",
    "semonides.xml",
    "theoc.xml",
    "mimn.xml",
}

PEDALION_EXCLUDE = {
    "papyri.xml",
    "example-sentences.xml",
    "external_examplesentences.xml",
    "chilia-sentences.xml",
}


GORMAN_AUTHOR_PATTERNS = [
    (r"^Aeschines", "Aeschines"), (r"^Andocides", "Andocides"),
    (r"^[Aa]ntiphon", "Antiphon"), (r"^Appian", "Appian"),
    (r"^Aristotle", "Aristotle"), (r"^[Dd]em", "Demosthenes"),
    (r"^Isaeus", "Isaeus"), (r"^Isocrates", "Isocrates"),
    (r"^[Ll]ysias", "Lysias"), (r"^[Pp]lato", "Plato"),
    (r"^[Pp]lut", "Plutarch"), (r"^[Pp]olybius", "Polybius"),
    (r"^[Xx]en", "Xenophon"), (r"^[Aa]then", "Athenaeus"),
    (r"^[Dd]iod", "Diodorus Siculus"), (r"^[Dd]ion hal", "Dionysius of Halicarnassus"),
    (r"^[Hh]dt", "Herodotus"), (r"^[Jj]osephus", "Josephus"),
    (r"^[Tt]huc", "Thucydides"), (r"^ps xen", "Pseudo-Xenophon"),
]


NT_BOOKS = {
    "MATT": ("Matthew (traditional)", "Gospel of Matthew"),
    "MARK": ("Mark (traditional)", "Gospel of Mark"),
    "LUKE": ("Luke (traditional)", "Gospel of Luke"),
    "ACTS": ("Luke (traditional)", "Acts"),
    "JOHN": ("John (traditional)", "Gospel of John"),
    "ROM": ("Paul (traditional)", "Romans"),
    "GAL": ("Paul", "Galatians"), "EPH": ("Paul (traditional)", "Ephesians"),
    "PHIL": ("Paul", "Philippians"), "COL": ("Paul (traditional)", "Colossians"),
    "TIT": ("Paul (traditional)", "Titus"), "PHILEM": ("Paul", "Philemon"),
    "HEB": ("Anonymous", "Hebrews"), "JAS": ("James (traditional)", "James"),
    "JUDE": ("Jude (traditional)", "Jude"), "REV": ("John of Patmos", "Revelation"),
}


# Sphregis is intended to provide conservative ground truth for authorship
# attribution.  Received corpora with anonymous, pseudonymous, mediated, or
# substantially disputed authorship are kept out of the benchmark rather than
# being presented as known-author training data.
EXCLUDED_AUTHOR_WORKS = {
    ("Aeschylus", "Prometheus Bound"): "disputed_aeschylean_authorship",
    ("Aesop", "Fables"): "traditional_aesopic_collection",
    ("Aesop", "Fables 1–50"): "traditional_aesopic_collection",
    ("Antiphon", "antiphon 1 bu2"): "disputed_antiphontic_authorship",
    ("Antiphon", "antiphon 2 bu2"): "disputed_antiphontic_authorship",
    ("Chion", "Letters"): "pseudonymous_epistolary_novel",
    ("Epictetus", "Dissertationes ab Arriano digestae"): "mediated_by_arrian",
    ("First Council of Nicea", "Nicene Creed 325 CE"): "corporate_authorship",
    ("Hesiod", "Shield of Heracles"): "pseudo_hesiodic",
    ("Isocrates", "Letters"): "disputed_isocratean_letters",
    ("John of Patmos", "Revelation"): "author_identity_not_secure",
    ("Plato", "Cleitophon"): "disputed_platonic_authorship",
    ("Xenophon", "xen cyr 8.8 bu1"): "disputed_cyropaedia_epilogue",
}

EXCLUDED_WORK_IDS = {
    "tlg0028.tlg001": "disputed_antiphontic_authorship",
    "tlg0028.tlg002": "disputed_antiphontic_authorship",
    "tlg0540.tlg014": "disputed_lysian_authorship",
    "tlg0540.tlg015": "disputed_lysian_authorship",
}

EXCLUDED_DEMOSTHENIC_SPEECHS = {7, 17, 46, 47, 49, 50, 52, 53, 59}

# Only these portions of Seven Against Thebes are excluded.  Removing complete
# alignment components below preserves exhaustive sentence/line coverage.
DISPUTED_VERSE_PASSAGES = {
    ("Aeschylus", "Seven Against Thebes"): ((861, 874), (1005, 1078)),
}


POS_MAP = {
    "n": "NOUN", "v": "VERB", "a": "ADJ", "d": "ADV", "c": "SCONJ",
    "r": "ADP", "p": "PRON", "l": "DET", "g": "PART", "b": "CCONJ",
    "m": "NUM", "i": "INTJ", "u": "PUNCT", "e": "X", "x": "X",
    "-": "X", "t": "VERB", "q": "ADV",
}

UPOS_TO_AGDT_POS = {
    "ADJ": "a", "ADP": "r", "ADV": "d", "AUX": "v", "CCONJ": "b",
    "DET": "l", "INTJ": "i", "NOUN": "n", "NUM": "m", "PART": "g",
    "PRON": "p", "PROPN": "n", "PUNCT": "u", "SCONJ": "c",
    "SYM": "x", "VERB": "v", "X": "x",
}

UD_TO_AGDT_FEATURE = {
    "Person": {"1": "1", "2": "2", "3": "3"},
    "Number": {"Sing": "s", "Plur": "p", "Dual": "d"},
    "Mood": {"Ind": "i", "Sub": "s", "Opt": "o", "Imp": "m"},
    "Voice": {"Act": "a", "Mid": "m", "Pass": "p"},
    "Gender": {"Masc": "m", "Fem": "f", "Neut": "n", "Com": "c"},
    "Case": {"Nom": "n", "Gen": "g", "Dat": "d", "Acc": "a", "Voc": "v", "Loc": "l"},
    "Degree": {"Cmp": "c", "Sup": "s", "Pos": "p"},
}

UD_V2_RELATIONS = {
    "acl", "advcl", "advmod", "amod", "appos", "aux", "case", "cc",
    "ccomp", "clf", "compound", "conj", "cop", "csubj", "dep", "det",
    "discourse", "dislocated", "expl", "fixed", "flat", "goeswith",
    "iobj", "list", "mark", "nmod", "nsubj", "nummod", "obj", "obl",
    "orphan", "parataxis", "punct", "reparandum", "root", "vocative",
    "xcomp",
}

FEATURE_MAPS = [
    ("Person", {"1": "1", "2": "2", "3": "3"}),
    ("Number", {"s": "Sing", "p": "Plur", "d": "Dual"}),
    ("Tense", {"p": "Pres", "i": "Past", "r": "Past", "l": "Past", "t": "Past", "f": "Fut", "a": "Past"}),
    ("Mood", {"i": "Ind", "s": "Sub", "o": "Opt", "m": "Imp", "n": "Inf", "p": "Part", "g": "Ger"}),
    ("Voice", {"a": "Act", "m": "Mid", "p": "Pass", "e": "Mid"}),
    ("Gender", {"m": "Masc", "f": "Fem", "n": "Neut", "c": "Com"}),
    ("Case", {"n": "Nom", "g": "Gen", "d": "Dat", "a": "Acc", "v": "Voc", "l": "Loc"}),
    ("Degree", {"c": "Cmp", "s": "Sup", "p": "Pos"}),
]


def canonical_xpos(upos: str, xpos: str, feats: str) -> str:
    """Return one consistent nine-position Ancient Greek XPOS tag.

    Valid AGDT/Perseus positional tags retain their more precise native tense
    and mood distinctions. Other source-specific XPOS schemes (notably the
    two-character PROIEL tags) are converted from the universal UPOS and FEATS
    columns. Missing distinctions are represented by ``-`` rather than by
    interpreting characters from an incompatible tag system.
    """
    xpos = xpos or "_"
    if re.fullmatch(r"[a-z][a-z0-9-]{0,9}", xpos):
        return xpos.ljust(9, "-")[:9]

    tag = ["-"] * 9
    tag[0] = UPOS_TO_AGDT_POS.get(upos, "x")
    parsed = {}
    if feats and feats != "_":
        for item in feats.split("|"):
            if "=" in item:
                name, value = item.split("=", 1)
                parsed[name] = value.split(",", 1)[0]
    positions = {
        "Person": 1, "Number": 2, "Tense": 3, "Mood": 4,
        "Voice": 5, "Gender": 6, "Case": 7, "Degree": 8,
    }
    for name, position in positions.items():
        value = parsed.get(name)
        if name == "Tense":
            if value == "Pres":
                tag[position] = "p"
            elif value == "Fut":
                tag[position] = "f"
            elif value == "Past":
                tag[position] = "i" if parsed.get("Aspect") == "Imp" else "a"
        elif value in UD_TO_AGDT_FEATURE.get(name, {}):
            tag[position] = UD_TO_AGDT_FEATURE[name][value]
    verb_form = parsed.get("VerbForm")
    if verb_form == "Inf":
        tag[4] = "n"
    elif verb_form == "Part":
        tag[4] = "p"
    return "".join(tag)


def canonicalize_conllu_xpos(conllu: str) -> str:
    """Normalize XPOS and retain only the non-identifying text comment."""
    lines = []
    for line in conllu.splitlines():
        if line.startswith("#") and not line.startswith("# text = "):
            continue
        if not line or line.startswith("# text = "):
            lines.append(line)
            continue
        columns = line.split("\t")
        if len(columns) == 10:
            misc = [
                item for item in columns[9].split("|")
                if item != "_" and item.split("=", 1)[0] in SAFE_CONLLU_MISC_KEYS
            ]
            columns[9] = "|".join(misc) or "_"
            if re.fullmatch(r"\d+", columns[0]):
                columns[4] = canonical_xpos(columns[3], columns[4], columns[5])
            line = "\t".join(columns)
        lines.append(line)
    return "\n".join(lines).rstrip("\n") + "\n\n"


def canonical_native_deprel(relation: str, child_upos: str, head: int) -> str:
    """Conservatively map an AGDT/Arethusa relation to UD v2.

    The native value remains losslessly available in MISC as ``NativeRel``.
    Coordination/apposition suffixes and obvious grammatical functions are
    mapped explicitly; opaque or annotation-specific categories fall back to
    the universal ``dep`` relation rather than being presented as UD subtypes.
    """
    if head == 0:
        return "root"
    if child_upos == "PUNCT":
        return "punct"
    cleaned = re.sub(r"[^A-Z0-9]+", "_", (relation or "").upper()).strip("_")
    parts = [part for part in cleaned.split("_") if part]
    if "CO" in parts or cleaned.endswith("CO"):
        return "conj"
    if "APOS" in parts or cleaned == "APOS":
        return "appos"
    if cleaned.startswith(("SBJ", "N_SUBJ", "A_SUBJ")):
        return "csubj" if child_upos in {"VERB", "AUX"} else "nsubj"
    if cleaned.startswith(("OBJ", "A_DO", "A_INTOBJ", "G_OBJEC", "NOM_")):
        return "ccomp" if child_upos in {"VERB", "AUX"} else "obj"
    if cleaned.startswith("ATR"):
        return {
            "ADJ": "amod", "DET": "det", "NUM": "nummod",
            "VERB": "acl", "AUX": "acl", "ADV": "advmod",
        }.get(child_upos, "nmod")
    if cleaned.startswith(("ADV", "CP_")):
        if child_upos in {"VERB", "AUX"}:
            return "advcl"
        if child_upos in {"NOUN", "PROPN", "PRON", "NUM"}:
            return "obl"
        return "advmod"
    if cleaned.startswith(("G_", "D_", "A_ORIENT", "A_EXTENT", "A_RESPECT")):
        return "obl"
    if cleaned.startswith(("OCOMP", "INF_COMP", "INF_EXPL")):
        return "ccomp" if child_upos in {"VERB", "AUX"} else "xcomp"
    if cleaned.startswith(("PNOM", "PRED", "N_PRED", "A_PRED", "D_PRED", "ATV")):
        return "xcomp"
    if cleaned.startswith("ADJ_RC"):
        return "acl"
    if cleaned.startswith("AUXP"):
        return "case"
    if cleaned.startswith("AUXC"):
        return "cc" if child_upos == "CCONJ" else "mark"
    if cleaned.startswith("AUXY") or cleaned in {"INTRJ", "SP_SUPPL"}:
        return "discourse"
    if cleaned.startswith("AUXZ"):
        return "advmod"
    if cleaned.startswith("AUXV"):
        return "aux"
    if cleaned.startswith(("COORD", "CO")):
        return "conj"
    if cleaned.startswith(("EXD", "XSEG")):
        return "dislocated"
    if cleaned.startswith("PARENTH"):
        return "parataxis"
    if cleaned.startswith(("MWE", "RELATION_NOT_RECOGNIZED_MWE")):
        return "fixed"
    if cleaned.startswith("GAP"):
        return "orphan"
    if cleaned.startswith("V_VOC"):
        return "vocative"
    return "dep"


@dataclass
class Sentence:
    source: str
    source_file: str
    source_sentence_id: str
    author: str
    work: str
    work_id: str
    text: str
    conllu: str
    cts_urn: str = ""
    passage: str = ""
    genre: str = "prose"
    native_cites: list[str] = field(default_factory=list)
    priority: int = 50
    source_records: list[dict] = field(default_factory=list)

    @property
    def normalized(self) -> str:
        return normalize(self.text)


def normalize(text: str) -> str:
    text = text.lower().replace("ς", "σ")
    text = "".join(
        char for char in unicodedata.normalize("NFD", text)
        if unicodedata.category(char) != "Mn"
    )
    return "".join(char for char in text if char.isalpha())


def slug(text: str) -> str:
    value = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
    value = re.sub(r"[^a-z0-9]+", "-", value).strip("-")
    return value or "unknown"


def canonical_author(author: str) -> str:
    return {
        "Aesopus": "Aesop",
        "Anon.": "Anonymous (Septuagint)",
        "Lucianus": "Lucian",
        "Pseudo-Lucianus": "Pseudo-Lucian",
        "(Pseudo-Homer)": "Pseudo-Homer",
        "Ezechiël": "Ezechiel",
    }.get(author.strip(), author.strip() or "Unknown")


def demosthenic_speech_number(work: str) -> int | None:
    match = re.match(r"^dem(?:osthenes)?[ _]+(\d+)", work, re.I)
    return int(match.group(1)) if match else None


def authorship_decision(sentence: Sentence) -> tuple[str | None, str | None]:
    """Return a curated author and, if excluded, a machine-readable reason."""
    author = canonical_author(sentence.author)
    work = sentence.work.strip()

    # Romans is part of the normally undisputed Pauline core; its upstream
    # "traditional" qualifier is therefore a metadata inconsistency.
    if author == "Paul (traditional)" and work == "Romans":
        author = "Paul"

    # The Homeric epics remain useful corpus labels, but not claims about one
    # biographical author shared by both poems.
    if author == "Homer" and work in {"Iliad", "Odyssey"}:
        author = f"Homeric-{work}"

    lowered_author = author.casefold()
    if lowered_author.startswith("unknown"):
        return None, "unknown_author"
    if lowered_author.startswith("anonymous"):
        return None, "anonymous_author"
    if lowered_author.startswith("pseudo-") or lowered_author.startswith("(pseudo-"):
        return None, "pseudonymous_author_label"
    if "(traditional)" in lowered_author:
        return None, "traditional_author_label"
    if re.search(r"\bfragments?\b", work, re.I):
        return None, "fragmentary_work_label"

    reason = EXCLUDED_AUTHOR_WORKS.get((author, work))
    if reason:
        return None, reason
    reason = EXCLUDED_WORK_IDS.get(sentence.work_id)
    if reason:
        return None, reason
    if author == "Demosthenes" and demosthenic_speech_number(work) in EXCLUDED_DEMOSTHENIC_SPEECHS:
        return None, "pseudo_or_disputed_demosthenic_speech"
    return author, None


def curate_sentences(rows: list[Sentence]) -> tuple[list[Sentence], dict]:
    retained = []
    excluded = Counter()
    excluded_works = Counter()
    relabeled = Counter()
    for sentence in rows:
        original_author = sentence.author
        author, reason = authorship_decision(sentence)
        if reason:
            excluded[reason] += 1
            excluded_works[(original_author, sentence.work, sentence.work_id)] += 1
            continue
        assert author is not None
        if author != original_author:
            relabeled[(original_author, author, sentence.work)] += 1
            sentence.author = author
        retained.append(sentence)
    return retained, {
        "input_rows": len(rows),
        "retained_rows": len(retained),
        "excluded_rows": len(rows) - len(retained),
        "excluded_by_reason": dict(sorted(excluded.items())),
        "excluded_works": [
            {"author": author, "work": work, "work_id": work_id, "rows": count}
            for (author, work, work_id), count in sorted(excluded_works.items())
        ],
        "relabeled": [
            {"from": old, "to": new, "work": work, "rows": count}
            for (old, new, work), count in sorted(relabeled.items())
        ],
    }


def stable_id(*parts: str, length: int = 20) -> str:
    return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:length]


def git_revision(path: Path) -> str:
    return subprocess.check_output(["git", "-C", str(path), "rev-parse", "HEAD"], text=True).strip()


def source_record(source: str, revisions: dict[str, str], source_file: str, sentence_id: str) -> dict:
    info = SOURCE_INFO[source]
    return {
        "source": source,
        "source_file": source_file,
        "source_sentence_id": sentence_id,
        "url": info["url"],
        "revision": revisions[source],
        "license": info["license"],
        "annotation_provenance": info["annotation"],
        "syntax_scheme": info["scheme"],
    }


def infer_cts(value: str) -> str:
    match = re.search(r"urn:cts:[^\s]+", value or "")
    if not match:
        return ""
    return match.group(0).removesuffix(".tb")


def cts_key(value: str) -> str:
    match = re.search(r"(tlg\d+\.tlg\d+)", value)
    return match.group(1) if match else ""


def morph_features(postag: str) -> str:
    tag = (postag or "---------").ljust(9, "-")[:9]
    values = []
    for index, (name, mapping) in enumerate(FEATURE_MAPS, 1):
        if tag[index] in mapping:
            values.append(f"{name}={mapping[tag[index]]}")
    return "|".join(sorted(values)) or "_"


def misc_field(values: dict[str, str]) -> str:
    fields = []
    for key, value in values.items():
        if value:
            clean = str(value).replace("|", ",").replace(" ", "_")
            fields.append(f"{key}={clean}")
    return "|".join(fields) or "_"


def smart_text(forms: Iterable[str]) -> str:
    result = ""
    no_space_before = set(",.;··:!?;)]}»”")
    no_space_after = set("([{«“")
    for form in forms:
        if not result:
            result = form
        elif form and form[0] in no_space_before:
            result += form
        elif result[-1] in no_space_after:
            result += form
        else:
            result += " " + form
    return result


def xml_sentence_to_conllu(sentence: ET.Element, metadata: dict[str, str]) -> tuple[str, str, list[str]]:
    words = list(sentence.findall("word"))
    real = [
        word for word in words
        if not word.get("artificial")
        and (word.get("form") or "").strip() not in {"", "[0]", "_"}
    ]
    id_map = {word.get("id", ""): index for index, word in enumerate(real, 1)}
    by_old_id = {word.get("id", ""): word for word in words}

    def resolved_head(word: ET.Element) -> int:
        head = word.get("head", "0")
        seen = set()
        while head not in id_map and head not in {"", "0", None} and head not in seen:
            seen.add(head)
            parent = by_old_id.get(head)
            head = parent.get("head", "0") if parent is not None else "0"
        return id_map.get(head, 0)

    forms = [word.get("form", "_") for word in real]
    text = smart_text(forms)
    lines = [
        f"# text = {text}",
    ]

    initial_heads = [resolved_head(word) for word in real]
    root_candidates = [
        index for index, (word, head) in enumerate(zip(real, initial_heads), 1)
        if head == 0 and not word.get("postag", "").startswith("u")
    ]
    primary_root = root_candidates[0] if root_candidates else 1
    final_heads = list(initial_heads)
    for index, head in enumerate(final_heads, 1):
        if index == primary_root:
            final_heads[index - 1] = 0
        elif head in {0, index}:
            final_heads[index - 1] = primary_root
    # A few beta trees contain cycles. Break each cycle at one node while
    # retaining all other original heads; record provenance still points back
    # to the source tree for audit.
    for token_id in range(1, len(final_heads) + 1):
        trail = []
        cursor = token_id
        while cursor:
            if cursor in trail:
                cycle = trail[trail.index(cursor):]
                break_id = min(cycle)
                final_heads[break_id - 1] = 0 if break_id == primary_root else primary_root
                break
            trail.append(cursor)
            cursor = final_heads[cursor - 1]
    cites = []
    for new_id, word in enumerate(real, 1):
        postag = word.get("postag", "---------")
        head = final_heads[new_id - 1]
        relation = word.get("relation", "dep")
        upos = POS_MAP.get(postag[:1].lower(), "X")
        dep = canonical_native_deprel(relation, upos, head)
        cite = word.get("cite", "") or word.get("ref", "")
        if cite:
            cites.append(cite)
        row = [
            str(new_id), word.get("form", "_"), word.get("lemma", "_"),
            upos,
            canonical_xpos(upos, postag, morph_features(postag)),
            morph_features(postag),
            str(head), dep, "_", misc_field({
                "NativeRel": relation,
                "NativeHead": word.get("head", ""),
                "HeadRepair": "Yes" if head != initial_heads[new_id - 1] else "",
            }),
        ]
        lines.append("\t".join(row))
    return text, "\n".join(lines) + "\n\n", cites


def parse_agdt(root: Path, revisions: dict[str, str]) -> tuple[list[Sentence], list[Sentence]]:
    prose, verse = [], []
    text_root = root / "v2.1" / "Greek" / "texts"
    for path in sorted(text_root.glob("*.xml")):
        tree = ET.parse(path)
        xml_root = tree.getroot()
        key = cts_key(xml_root.get("cts", "") or path.name)
        if key not in AGDT_WORKS:
            continue
        author, work, genre = AGDT_WORKS[key]
        cts = infer_cts(xml_root.get("cts", "")) or f"urn:cts:greekLit:{key}"
        for index, sent in enumerate(xml_root.iter("sentence"), 1):
            sid = sent.get("id", str(index))
            passage = sent.get("subdoc", "")
            text, conllu, cites = xml_sentence_to_conllu(sent, {
                "sent_id": f"agdt:{key}:{sid}", "source": path.name,
                "cts": cts, "passage": passage,
            })
            if not normalize(text):
                continue
            row = Sentence(
                source="agdt", source_file=path.name, source_sentence_id=sid,
                author=author, work=work, work_id=key, text=text, conllu=conllu,
                cts_urn=cts, passage=passage, genre=genre, native_cites=cites,
                priority=10,
            )
            row.source_records = [source_record("agdt", revisions, path.name, sid)]
            (verse if genre == "verse" else prose).append(row)
    return prose, verse


def conllu_blocks(path: Path) -> Iterable[dict]:
    for raw in path.read_text(encoding="utf8").strip().split("\n\n"):
        comments = {}
        token_rows = []
        for line in raw.splitlines():
            if line.startswith("# ") and " = " in line:
                key, value = line[2:].split(" = ", 1)
                comments[key] = value
            elif line and not line.startswith("#"):
                fields = line.split("\t")
                if len(fields) == 10:
                    token_rows.append(fields)
        if token_rows:
            yield {"comments": comments, "tokens": token_rows, "conllu": raw + "\n"}


def ud_identity(source: str, block: dict) -> tuple[str, str, str, str, str]:
    comments, tokens = block["comments"], block["tokens"]
    sent_id = comments.get("sent_id", "")
    if source == "ud_perseus":
        doc = sent_id.split("@", 1)[0]
        key = cts_key(doc)
        author, work, genre = AGDT_WORKS.get(key, ("Unknown", doc, "prose"))
        return author, work, key or doc, genre, infer_cts(doc)
    refs = [row[9] for row in tokens]
    if source == "ud_ptnk":
        joined = "|".join(refs)
        book = "Ruth" if "Septuagint-Ruth" in joined else "Genesis"
        return "Anonymous (Septuagint)", book, f"septuagint-{book.lower()}", "prose", ""
    # PROIEL: Herodotus refs are numeric; New Testament refs carry a book prefix.
    for misc in refs:
        match = re.search(r"(?:^|\|)Ref=([A-Z]+)_", misc)
        if match:
            code = match.group(1)
            author, work = NT_BOOKS.get(code, (f"Unknown ({code})", code))
            return author, work, f"proiel-{code.lower()}", "prose", ""
    return "Herodotus", "Histories (PROIEL selections)", "tlg0016.tlg001", "prose", "urn:cts:greekLit:tlg0016.tlg001"


def parse_ud(source: str, root: Path, revisions: dict[str, str]) -> tuple[list[Sentence], list[Sentence]]:
    prose, verse = [], []
    for path in sorted(root.glob("*.conllu")):
        for block in conllu_blocks(path):
            comments = block["comments"]
            author, work, work_id, genre, cts = ud_identity(source, block)
            sid = comments.get("sent_id", stable_id(block["conllu"]))
            text = comments.get("text") or smart_text(
                row[1] for row in block["tokens"] if re.fullmatch(r"\d+", row[0])
            )
            if not normalize(text):
                continue
            cites = []
            for token in block["tokens"]:
                match = re.search(r"(?:^|\|)Ref=([^|]+)", token[9])
                if match:
                    cites.append(match.group(1))
            row = Sentence(
                source=source, source_file=path.name, source_sentence_id=sid,
                author=author, work=work, work_id=work_id, text=text,
                conllu=canonicalize_conllu_xpos(block["conllu"]), cts_urn=cts,
                passage=comments.get("source", ""), genre=genre, native_cites=cites,
                priority=0,
            )
            row.source_records = [source_record(source, revisions, path.name, sid)]
            (verse if genre == "verse" else prose).append(row)
    return prose, verse


def gorman_author(filename: str) -> str:
    for pattern, author in GORMAN_AUTHOR_PATTERNS:
        if re.search(pattern, filename, re.I if pattern.startswith("^") else 0):
            return author
    return "Unknown"


def parse_native_collection(
    source: str,
    files: Iterable[Path],
    revisions: dict[str, str],
    metadata: dict[str, tuple[str, str]] | None = None,
    verse_files: set[str] | None = None,
) -> tuple[list[Sentence], list[Sentence]]:
    prose, verse = [], []
    metadata = metadata or {}
    verse_files = verse_files or set()
    for path in sorted(files):
        try:
            tree = ET.parse(path)
        except ET.ParseError:
            continue
        xml_root = tree.getroot()
        if xml_root.get("{http://www.w3.org/XML/1998/namespace}lang") == "lat":
            continue
        first = next(xml_root.iter("sentence"), None)
        if first is None:
            continue
        if source == "gorman":
            author, work = gorman_author(path.name), path.stem
        else:
            author, work = metadata.get(path.name, (first.get("Author", "") or "Unknown", path.stem))
        author = canonical_author(author)
        genre = "verse" if path.name in verse_files else "prose"
        doc = first.get("document_id", "")
        cts = infer_cts(doc)
        work_id = cts_key(doc) or f"{source}:{slug(author)}:{slug(work)}"
        for index, sent in enumerate(xml_root.iter("sentence"), 1):
            sid = sent.get("id", str(index))
            passage = sent.get("subdoc", "")
            text, conllu, cites = xml_sentence_to_conllu(sent, {
                "sent_id": f"{source}:{slug(path.stem)}:{sid}", "source": path.name,
                "cts": cts, "passage": passage,
            })
            if not normalize(text):
                continue
            row = Sentence(
                source=source, source_file=path.name, source_sentence_id=sid,
                author=author, work=work, work_id=work_id, text=text, conllu=conllu,
                cts_urn=cts, passage=passage, genre=genre, native_cites=cites,
                priority={"gorman": 5, "harrington": 15, "pedalion": 20}.get(source, 20),
            )
            row.source_records = [source_record(source, revisions, path.name, sid)]
            (verse if genre == "verse" else prose).append(row)
    return prose, verse


def publication_metadata(config_path: Path) -> dict[str, tuple[str, str]]:
    config = json.loads(config_path.read_text())
    result = {}

    def visit(value):
        if isinstance(value, dict):
            if "author" in value and "work" in value:
                for section in value.get("sections", []):
                    xml = section.get("xml", "")
                    if xml:
                        result[Path(xml).name] = (value["author"], value["work"])
            for child in value.values():
                visit(child)
        elif isinstance(value, list):
            for child in value:
                visit(child)

    visit(config)
    return result


class HypotacticParser(HTMLParser):
    def __init__(self, stem: str):
        super().__init__(convert_charrefs=True)
        self.stem = stem
        self.container = {}
        self.poem = {}
        self.poem_depth = None
        self.poem_counter = 0
        self.depth = 0
        self.line_depth = None
        self.line = None
        self.word_depth = None
        self.word_text = []
        self.syll_depth = None
        self.syllable = None
        self.lines = []

    def handle_starttag(self, tag, attrs):
        self.depth += 1
        attrs = dict(attrs)
        classes = set(attrs.get("class", "").split())
        if tag == "div" and self.line is None and "line" not in classes:
            for key in ("data-author", "data-work", "data-book", "data-metre"):
                if key in attrs and key not in self.container:
                    self.container[key] = attrs[key]
        if tag == "div" and "poem" in classes:
            self.poem_counter += 1
            book = attrs.get("data-book", "")
            poem_number = attrs.get("data-number", "")
            if not any(char.isdigit() for char in book):
                book = poem_number or book
            self.poem_depth = self.depth
            self.poem = {
                "data-author": attrs.get("data-author", self.container.get("data-author", "")),
                "data-work": attrs.get("data-work", self.container.get("data-work", "")),
                "data-book": book,
                "data-metre": attrs.get("data-metre", self.container.get("data-metre", "")),
                "sequence": str(self.poem_counter),
            }
        if tag == "div" and "line" in classes:
            self.line_depth = self.depth
            self.line = {
                "number": attrs.get("data-number", ""),
                "metre": attrs.get("data-metre", self.poem.get("data-metre", self.container.get("data-metre", ""))),
                "speaker": attrs.get("data-speaker", ""),
                "words": [], "syllables": [],
            }
        elif self.line is not None and tag == "span" and "word" in classes:
            self.word_depth = self.depth
            self.word_text = []
        if self.line is not None and tag == "span" and "syll" in classes:
            quantity = "long" if "long" in classes else "short" if "short" in classes else "anceps" if "anceps" in classes else "unknown"
            self.syll_depth = self.depth
            self.syllable = {
                "text": "", "quantity": quantity,
                "features": sorted(classes - {"syll", "long", "short", "anceps"}),
            }

    def handle_data(self, data):
        if self.word_depth is not None:
            self.word_text.append(data)
        if self.syllable is not None:
            self.syllable["text"] += data

    def handle_endtag(self, tag):
        if self.syll_depth == self.depth and self.syllable is not None:
            self.line["syllables"].append(self.syllable)
            self.syllable = None
            self.syll_depth = None
        if self.word_depth == self.depth and tag == "span":
            word = "".join(self.word_text).strip()
            if word:
                self.line["words"].append(word)
            self.word_depth = None
            self.word_text = []
        if self.line_depth == self.depth and tag == "div":
            self.line["text"] = " ".join(self.line.pop("words"))
            symbols = {"long": "–", "short": "⏑", "anceps": "×", "unknown": "?"}
            self.line["scansion"] = "".join(symbols[s["quantity"]] for s in self.line["syllables"])
            self.line["hypotactic_file"] = self.stem + ".html"
            self.line.update({
                "hypotactic_author": self.poem.get("data-author", self.container.get("data-author", "")),
                "hypotactic_work": self.poem.get("data-work", self.container.get("data-work", "")),
                "book": self.poem.get("data-book", self.container.get("data-book", "")),
                "poem_sequence": self.poem.get("sequence", "1"),
            })
            if self.line["text"] and self.line["number"]:
                self.lines.append(self.line)
            self.line = None
            self.line_depth = None
        if self.poem_depth == self.depth and tag == "div":
            self.poem = {}
            self.poem_depth = None
        self.depth -= 1


def parse_hypotactic_file(path: Path) -> list[dict]:
    parser = HypotacticParser(path.stem)
    parser.feed(path.read_text(encoding="utf8"))
    # Older files do not carry book metadata; recover it from their stem.
    book_match = re.match(r"(?:iliad|odyssey|dionysiaca|qsmyrnaeus)(\d+)$", path.stem)
    for line in parser.lines:
        if not line["book"] and book_match:
            line["book"] = book_match.group(1)
        line["normalized"] = normalize(line["text"])
    return parser.lines


def load_hypotactic(root: Path) -> dict[str, list[dict]]:
    html_root = root / "hypotactic_htmls_greek"
    needed = sorted({stem for link in VERSE_LINKS.values() for stem in link["files"]})
    return {stem: parse_hypotactic_file(html_root / f"{stem}.html") for stem in needed}


def verse_sentence_order_key(sentence: Sentence) -> tuple:
    references = []
    for cite in sentence.native_cites:
        match = re.search(r":(\d+)(?:\.(\d+))?$", cite)
        if match:
            references.append((int(match.group(1)), int(match.group(2) or 0)))
    if references:
        return 0, min(references)
    numbers = tuple(int(value) for value in re.findall(r"\d+", sentence.source_sentence_id))
    return 1, numbers or (10**9,)


def cumulative_boundaries(items: list, text_key) -> list[int]:
    boundaries = [0]
    for item in items:
        boundaries.append(boundaries[-1] + len(text_key(item)))
    return boundaries


def exact_alignment_components(
    sentences: list[Sentence], lines: list[dict],
) -> tuple[list[tuple[int, int, int, int]], dict]:
    sentence_stream = "".join(sentence.normalized for sentence in sentences)
    line_stream = "".join(line["normalized"] for line in lines)
    sentence_boundaries = cumulative_boundaries(sentences, lambda item: item.normalized)
    line_boundaries = cumulative_boundaries(lines, lambda item: item["normalized"])
    sentence_at = {position: index for index, position in enumerate(sentence_boundaries)}
    line_at = {position: index for index, position in enumerate(line_boundaries)}

    result = edlib.align(sentence_stream, line_stream, mode="HW", task="path")
    if result["cigar"] is None or not result["locations"]:
        return [], {"edit_distance": result["editDistance"]}
    sentence_position = 0
    line_position = result["locations"][0][0]
    last_joint_boundary = (
        (sentence_position, line_position)
        if sentence_position in sentence_at and line_position in line_at
        else None
    )
    exact_since_joint = True
    components = []
    for length, operation in re.findall(r"(\d+)([=XID])", result["cigar"]):
        for _ in range(int(length)):
            if operation in "=X":
                sentence_position += 1
                line_position += 1
            elif operation == "I":
                sentence_position += 1
            else:  # D advances only the Hypotactic stream in edlib's CIGAR.
                line_position += 1
            if operation != "=":
                exact_since_joint = False
            if sentence_position in sentence_at and line_position in line_at:
                if exact_since_joint and last_joint_boundary is not None:
                    previous_sentence, previous_line = last_joint_boundary
                    if sentence_position > previous_sentence and line_position > previous_line:
                        component = (
                            sentence_at[previous_sentence], sentence_at[sentence_position],
                            line_at[previous_line], line_at[line_position],
                        )
                        sentence_text = "".join(
                            sentence.normalized for sentence in sentences[component[0]:component[1]]
                        )
                        line_text = "".join(
                            line["normalized"] for line in lines[component[2]:component[3]]
                        )
                        assert sentence_text == line_text
                        components.append(component)
                last_joint_boundary = (sentence_position, line_position)
                exact_since_joint = True

    return components, {
        "edit_distance": result["editDistance"],
        "target_start": result["locations"][0][0],
        "target_end": result["locations"][0][1],
        "normalized_sentence_chars": len(sentence_stream),
        "normalized_line_chars": len(line_stream),
    }


def unique_source_records(records: Iterable[dict]) -> list[dict]:
    output = []
    seen = set()
    for record in records:
        key = (record["source"], record["source_file"], record["source_sentence_id"])
        if key not in seen:
            seen.add(key)
            output.append(record)
    return output


def hypotactic_source_records(lines: list[dict], revisions: dict[str, str]) -> list[dict]:
    by_file = defaultdict(list)
    for line in lines:
        by_file[line["hypotactic_file"]].append(line)
    return [
        source_record(
            "hypotactic", revisions, source_file,
            ",".join(
                f"{line['poem_sequence']}:{line['book']}:{line['number']}"
                for line in file_lines
            ),
        )
        for source_file, file_lines in sorted(by_file.items())
    ]


def line_identity(work_id: str, line: dict) -> tuple[str, ...]:
    return (
        work_id, line["hypotactic_file"], line["poem_sequence"],
        line["book"], line["number"],
    )


def align_verse_blocks(
    verse_sentences: list[Sentence], hyp: dict[str, list[dict]], revisions: dict[str, str],
) -> tuple[list[dict], list[dict], dict]:
    sentence_rows, metre_rows = [], []
    alignment_stats = {}
    grouped_sentences = defaultdict(list)
    for sentence in verse_sentences:
        link_key = f"pedalion:{sentence.source_file}" if sentence.source == "pedalion" else sentence.work_id
        if link_key in VERSE_LINKS:
            grouped_sentences[link_key].append(sentence)

    for link_key, link in VERSE_LINKS.items():
        sentences = sorted(grouped_sentences[link_key], key=verse_sentence_order_key)
        lines = [line for stem in link["files"] for line in hyp[stem]]
        if not sentences:
            alignment_stats[link_key] = {
                "sentences": 0,
                "lines": len(lines),
                "alignment_components": 0,
                "matched_sentences": 0,
                "matched_lines": 0,
                "excluded_sentences": 0,
                "excluded_lines": len(lines),
                "cross_boundary_sentences": 0,
                "cross_boundary_lines": 0,
                "excluded_by_authorship_curation": True,
            }
            continue
        components, stats = exact_alignment_components(sentences, lines)
        matched_sentence_indices = set()
        matched_line_indices = set()
        cross_boundary_lines = 0
        cross_boundary_sentences = 0

        for sentence_start, sentence_end, line_start, line_end in components:
            component_sentences = sentences[sentence_start:sentence_end]
            component_lines = lines[line_start:line_end]
            sentence_bounds = cumulative_boundaries(component_sentences, lambda item: item.normalized)
            line_bounds = cumulative_boundaries(component_lines, lambda item: item["normalized"])
            component_id = "va-" + stable_id(
                link_key,
                component_sentences[0].source_file,
                component_sentences[0].source_sentence_id,
                component_sentences[-1].source_sentence_id,
                *line_identity(component_sentences[0].work_id, component_lines[0]),
                *line_identity(component_sentences[0].work_id, component_lines[-1]),
            )
            sentence_ids = [
                "vs-" + stable_id(sentence.source, sentence.source_file, sentence.source_sentence_id)
                for sentence in component_sentences
            ]
            line_ids = [
                "vm-" + stable_id(*line_identity(component_sentences[0].work_id, line))
                for line in component_lines
            ]

            sentence_to_lines = []
            for sentence_index in range(len(component_sentences)):
                start, end = sentence_bounds[sentence_index:sentence_index + 2]
                overlaps = [
                    line_index for line_index in range(len(component_lines))
                    if max(start, line_bounds[line_index]) < min(end, line_bounds[line_index + 1])
                ]
                assert overlaps
                sentence_to_lines.append(overlaps)
                if len(overlaps) > 1:
                    cross_boundary_sentences += 1

            line_to_sentences = []
            for line_index in range(len(component_lines)):
                start, end = line_bounds[line_index:line_index + 2]
                overlaps = [
                    sentence_index for sentence_index in range(len(component_sentences))
                    if max(start, sentence_bounds[sentence_index]) < min(end, sentence_bounds[sentence_index + 1])
                ]
                assert overlaps
                line_to_sentences.append(overlaps)
                if len(overlaps) > 1:
                    cross_boundary_lines += 1

            for sentence_index, sentence in enumerate(component_sentences):
                overlapping_indices = sentence_to_lines[sentence_index]
                overlapping_lines = [component_lines[index] for index in overlapping_indices]
                published_lines = []
                for index in overlapping_indices:
                    line = component_lines[index]
                    published_lines.append(public_metrical_line(line))
                records = unique_source_records(
                    list(sentence.source_records) + hypotactic_source_records(overlapping_lines, revisions)
                )
                sentence_rows.append({
                    "id": sentence_ids[sentence_index], "author": sentence.author, "work": sentence.work,
                    "work_id": sentence.work_id, "genre": "verse_sentence", "text": sentence.text,
                    "conllu": sentence.conllu, "cts_urn": sentence.cts_urn, "passage": sentence.passage,
                    "alignment_component_id": component_id,
                    "component_sentence_index": sentence_index,
                    "metre": sorted({line["metre"] for line in overlapping_lines}),
                    "metrical_line_ids": [line_ids[index] for index in overlapping_indices],
                    "metrical_lines": json.dumps(published_lines, ensure_ascii=False),
                    "treebank_source": sentence.source,
                    "source_records": json.dumps(records, ensure_ascii=False, sort_keys=True),
                    "licenses": sorted({record["license"] for record in records}),
                    "dedup_key": hashlib.sha256(sentence.normalized.encode()).hexdigest(),
                })

            for line_index, line in enumerate(component_lines):
                overlapping_indices = line_to_sentences[line_index]
                parents = [component_sentences[index] for index in overlapping_indices]
                parent_ids = [sentence_ids[index] for index in overlapping_indices]
                records = unique_source_records(
                    [record for parent in parents for record in parent.source_records]
                    + hypotactic_source_records([line], revisions)
                )
                metre_rows.append({
                    "id": line_ids[line_index], "parent_sentence_ids": parent_ids,
                    "author": parents[0].author, "work": parents[0].work, "work_id": parents[0].work_id,
                    "genre": "verse_metre", "text": line["text"],
                    "conllu": "\n\n".join(parent.conllu.strip() for parent in parents) + "\n\n",
                    "cts_urn": parents[0].cts_urn,
                    "passage": " | ".join(dict.fromkeys(parent.passage for parent in parents if parent.passage)),
                    "alignment_component_id": component_id,
                    "component_line_index": line_index,
                    "book": line["book"], "poem_sequence": line["poem_sequence"],
                    "line_number": line["number"], "metre": line["metre"],
                    "syllables": json.dumps(line["syllables"], ensure_ascii=False),
                    "hypotactic_file": line["hypotactic_file"], "treebank_source": parents[0].source,
                    "source_records": json.dumps(records, ensure_ascii=False, sort_keys=True),
                    "licenses": sorted({record["license"] for record in records}),
                    "dedup_key": hashlib.sha256(line["normalized"].encode()).hexdigest(),
                })

            matched_sentence_indices.update(range(sentence_start, sentence_end))
            matched_line_indices.update(range(line_start, line_end))

        alignment_stats[link_key] = {
            **stats,
            "sentences": len(sentences), "lines": len(lines),
            "alignment_components": len(components),
            "matched_sentences": len(matched_sentence_indices),
            "matched_lines": len(matched_line_indices),
            "excluded_sentences": len(sentences) - len(matched_sentence_indices),
            "excluded_lines": len(lines) - len(matched_line_indices),
            "cross_boundary_sentences": cross_boundary_sentences,
            "cross_boundary_lines": cross_boundary_lines,
        }
    return sentence_rows, metre_rows, alignment_stats


def numeric_line_number(value: str) -> int | None:
    match = re.match(r"^(\d+)", str(value))
    return int(match.group(1)) if match else None


def exclude_disputed_verse_components(
    sentence_rows: list[dict], metre_rows: list[dict],
) -> tuple[list[dict], list[dict], dict]:
    """Remove complete aligned components touching a disputed verse passage."""
    excluded_components = set()
    matched_ranges = Counter()
    for row in metre_rows:
        ranges = DISPUTED_VERSE_PASSAGES.get((row["author"], row["work"]), ())
        line_number = numeric_line_number(row["line_number"])
        if line_number is None:
            continue
        for start, end in ranges:
            if start <= line_number <= end:
                excluded_components.add(row["alignment_component_id"])
                matched_ranges[(row["author"], row["work"], start, end)] += 1
                break

    retained_sentences = [
        row for row in sentence_rows
        if row["alignment_component_id"] not in excluded_components
    ]
    retained_lines = [
        row for row in metre_rows
        if row["alignment_component_id"] not in excluded_components
    ]
    return retained_sentences, retained_lines, {
        "excluded_components": len(excluded_components),
        "excluded_sentence_rows": len(sentence_rows) - len(retained_sentences),
        "excluded_metre_rows": len(metre_rows) - len(retained_lines),
        "matched_ranges": [
            {"author": author, "work": work, "start": start, "end": end, "matched_lines": count}
            for (author, work, start, end), count in sorted(matched_ranges.items())
        ],
    }


def deduplicate_prose(rows: list[Sentence]) -> tuple[list[dict], dict]:
    groups = defaultdict(list)
    for row in rows:
        if row.normalized:
            groups[hashlib.sha256(row.normalized.encode()).hexdigest()].append(row)
    output = []
    duplicate_groups = 0
    duplicate_rows = 0
    conflicting_author_groups = 0
    conflicting_author_rows = 0
    conflict_examples = []
    for key, members in groups.items():
        authors = {canonical_author(member.author) for member in members}
        if len(authors) > 1:
            conflicting_author_groups += 1
            conflicting_author_rows += len(members)
            if len(conflict_examples) < 25:
                conflict_examples.append({
                    "dedup_key": key,
                    "authors": sorted(authors),
                    "normalized_length": len(members[0].normalized),
                    "sources": sorted({member.source for member in members}),
                })
            continue
        members.sort(key=lambda row: (row.priority, row.source, row.source_file, row.source_sentence_id))
        chosen = members[0]
        source_records = []
        seen = set()
        for member in members:
            for record in member.source_records:
                record_key = (record["source"], record["source_file"], record["source_sentence_id"])
                if record_key not in seen:
                    seen.add(record_key)
                    source_records.append(record)
        if len(members) > 1:
            duplicate_groups += 1
            duplicate_rows += len(members) - 1
        output.append({
            "id": "p-" + stable_id(chosen.source, chosen.source_file, chosen.source_sentence_id),
            "author": chosen.author, "work": chosen.work, "work_id": chosen.work_id,
            "genre": "prose", "text": chosen.text, "conllu": chosen.conllu,
            "cts_urn": chosen.cts_urn, "passage": chosen.passage,
            "treebank_source": chosen.source,
            "source_records": json.dumps(source_records, ensure_ascii=False, sort_keys=True),
            "licenses": sorted({record["license"] for record in source_records}),
            "dedup_key": key,
        })
    output.sort(key=lambda row: row["id"])
    return output, {
        "input_rows": len(rows), "output_rows": len(output),
        "duplicate_groups": duplicate_groups, "removed_exact_duplicates": duplicate_rows,
        "conflicting_author_groups_removed": conflicting_author_groups,
        "conflicting_author_rows_removed": conflicting_author_rows,
        "conflict_examples": conflict_examples,
    }


def split_counts(n: int) -> dict[str, int]:
    if n < 3:
        n_val = n_test = 0
    elif n < 10:
        n_val = n_test = 1
    else:
        n_val = max(1, round(n * 0.1))
        n_test = max(1, round(n * 0.1))
    return {"train": n - n_val - n_test, "validation": n_val, "test": n_test}


def split_labels(n: int) -> list[str]:
    counts = split_counts(n)
    return [split for split in ("train", "validation", "test") for _ in range(counts[split])]


def assign_splits(rows: list[dict]) -> None:
    groups = defaultdict(list)
    for row in rows:
        groups[(row["author"], row["work_id"])].append(row)
    rng = random.Random(RANDOM_SEED)
    for group in sorted(groups):
        group_rows = sorted(groups[group], key=lambda row: row["id"])
        rng.shuffle(group_rows)
        for row, split in zip(group_rows, split_labels(len(group_rows))):
            row["split"] = split


def write_parquet(
    rows: list[dict], output_root: Path, config: str, schema: pa.Schema | None = None,
) -> dict:
    stats = {}
    config_root = output_root / config
    config_root.mkdir(parents=True, exist_ok=True)
    for split in ("train", "validation", "test"):
        split_rows = [row for row in rows if row["split"] == split]
        table = pa.Table.from_pylist(split_rows, schema=schema)
        path = config_root / f"{split}-00000-of-00001.parquet"
        pq.write_table(table, path, compression="zstd", compression_level=9)
        stats[split] = len(split_rows)
    return stats


def validate_source_verse_alignment(rows_by_base_config: dict[str, list[dict]]) -> None:
    """Validate exact syntax/metre coverage before task-level row selection."""
    components = defaultdict(lambda: {"sentences": [], "lines": []})
    for row in rows_by_base_config["verse_sentence"]:
        components[row["alignment_component_id"]]["sentences"].append(row)
    for row in rows_by_base_config["verse_metre"]:
        components[row["alignment_component_id"]]["lines"].append(row)
    for component in components.values():
        sentences = sorted(
            component["sentences"], key=lambda row: row["component_sentence_index"],
        )
        lines = sorted(component["lines"], key=lambda row: row["component_line_index"])
        assert sentences and lines
        assert "".join(normalize(row["text"]) for row in sentences) == "".join(
            normalize(row["text"]) for row in lines
        )


def validate(rows_by_config: dict[str, list[dict]]) -> dict:
    report = {}
    checked_conllu = set()
    for config, rows in rows_by_config.items():
        ids = [row["id"] for row in rows]
        dedup = [row["dedup_key"] for row in rows]
        assert len(ids) == len(set(ids)), f"duplicate ids in {config}"
        base_config = config.rsplit("_", 1)[0]
        assert all(row["genre"] == base_config for row in rows)
        assert all(row["text"] and row["author"] and row["work"] for row in rows)
        for row in rows:
            text_units = load_text_units(row["text"])
            assert len(text_units) == row.get("chunk_size", 1)
        assert all(row["split"] in {"train", "validation", "test"} for row in rows)
        suffix = config.rsplit("_", 1)[1]
        if suffix != "1":
            target = int(suffix)
            assert all(
                row["chunk_size"] == (1 if row["split"] == "train" else target)
                for row in rows
            )
            assert all(row["chunk_target_size"] == target for row in rows)
            assert all(len(row["constituent_ids"]) == row["chunk_size"] for row in rows)
        if base_config == "prose":
            assert len(dedup) == len(set(dedup)), "prose exact-text deduplication failed"
        elif base_config == "verse_sentence":
            for row in rows:
                lines = load_public_metrical_lines(row["metrical_lines"])
                assert len(lines) == len(row["metrical_line_ids"])
        for row in rows:
            comments = [
                line for line in row["conllu"].splitlines()
                if line.startswith("#")
            ]
            assert all(line.startswith("# text = ") for line in comments), (
                f"Identifying CoNLL-U comment in {config}, row {row['id']}: {comments}"
            )
            for line in row["conllu"].splitlines():
                if not line or line.startswith("#"):
                    continue
                columns = line.split("\t")
                assert len(columns) == 10
                misc_keys = {
                    item.split("=", 1)[0]
                    for item in columns[9].split("|")
                    if item != "_"
                }
                assert misc_keys <= SAFE_CONLLU_MISC_KEYS, (
                    f"Identifying CoNLL-U MISC field in {config}, "
                    f"row {row['id']}: {misc_keys}"
                )
            digest = hashlib.sha256(row["conllu"].encode("utf-8")).digest()
            if digest in checked_conllu:
                continue
            try:
                load_conllu(io.StringIO(row["conllu"]))
            except UDError as error:
                raise AssertionError(
                    f"Malformed CoNLL-U in {config}, row {row['id']}: {error}"
                ) from error
            checked_conllu.add(digest)
        report[config] = {
            "rows": len(rows),
            "authors": len({row["author"] for row in rows}),
            "works": len({row["work_id"] for row in rows}),
            "sources": dict(Counter(row["treebank_source"] for row in rows)),
            "splits": dict(Counter(row["split"] for row in rows)),
        }
    for base_config in ("prose", "verse_sentence", "verse_metre"):
        atomic = rows_by_config[f"{base_config}_1"]
        atomic_by_id = {row["id"]: row for row in atomic}
        for target in (10, 100):
            variant = rows_by_config[f"{base_config}_{target}"]
            for split in ("train", "validation", "test"):
                expected_ids = {
                    row["id"] for row in atomic if row["split"] == split
                }
                represented_ids = [
                    constituent_id
                    for row in variant if row["split"] == split
                    for constituent_id in row["constituent_ids"]
                ]
                assert len(represented_ids) == len(set(represented_ids))
                assert set(represented_ids) == expected_ids
                for row in variant:
                    if row["split"] != split or row["chunk_size"] == 1:
                        continue
                    constituents = [
                        atomic_by_id[row_id] for row_id in row["constituent_ids"]
                    ]
                    expected_text_units = [
                        unit
                        for item in constituents
                        for unit in load_text_units(item["text"])
                    ]
                    assert load_text_units(row["text"]) == expected_text_units
                    if base_config == "verse_metre":
                        expected_syllables = [
                            syllable
                            for item in constituents
                            for syllable in json.loads(item["syllables"])
                        ]
                        assert json.loads(row["syllables"]) == expected_syllables
    report["checks"] = {
        "unique_ids": True, "prose_exact_text_unique": True,
        "source_verse_component_exact_coverage": True,
        "identical_source_rows_across_task_sizes": True,
        "complete_chunk_text_and_syllable_aggregation": True,
        "scansion_column_absent": True,
        "fixed_exact_evaluation_chunks": True,
        "official_conll18_loader": True,
        "unique_conllu_documents_checked": len(checked_conllu),
        "identifier_free_conllu_comments": True,
        "identifier_free_conllu_misc": True,
        "privacy_safe_metrical_lines": True,
        "json_list_text_fields": True,
    }
    return report


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--sources", type=Path, required=True)
    parser.add_argument("--output", type=Path, default=Path("data"))
    parser.add_argument("--metadata", type=Path, default=Path("metadata"))
    args = parser.parse_args()

    revisions = {
        key: git_revision(args.sources / info["directory"])
        for key, info in SOURCE_INFO.items()
    }

    agdt_prose, agdt_verse = parse_agdt(args.sources / "treebank_data", revisions)
    ud_perseus_prose, _ = parse_ud("ud_perseus", args.sources / "perseus", revisions)
    proiel_prose, _ = parse_ud("ud_proiel", args.sources / "proiel", revisions)
    ptnk_prose, _ = parse_ud("ud_ptnk", args.sources / "ptnk", revisions)

    gorman_prose, _ = parse_native_collection(
        "gorman", (args.sources / "gorman" / "xml versions").glob("*.xml"), revisions,
    )
    pedalion_meta = publication_metadata(args.sources / "pedalion" / "src" / "config.json")
    # The Pedalion card groups these three files under "diverse authors";
    # restore the file-level attributions encoded in the XML.
    pedalion_meta.update({
        "semonides.xml": ("Semonides", "Typology of Women"),
        "theoc.xml": ("Theocritus", "Fragments"),
        "mimn.xml": ("Mimnermus", "Fragments"),
    })
    pedalion_files = [
        path for path in (args.sources / "pedalion" / "public" / "xml").glob("*.xml")
        if path.name not in PEDALION_EXCLUDE
    ]
    pedalion_prose, pedalion_verse = parse_native_collection(
        "pedalion", pedalion_files, revisions, pedalion_meta, PEDALION_VERSE,
    )
    harrington_meta = publication_metadata(args.sources / "harrington" / "src" / "config.json")
    harrington_prose, _ = parse_native_collection(
        "harrington",
        (args.sources / "harrington" / "public" / "xml" / "CITE_TREEBANK_XML" / "perseus" / "grctb").rglob("*.xml"),
        revisions, harrington_meta,
    )

    prose_input = (
        ud_perseus_prose + proiel_prose + ptnk_prose + agdt_prose + gorman_prose
        + pedalion_prose + harrington_prose
    )
    prose_input, prose_curation = curate_sentences(prose_input)
    prose, dedup_stats = deduplicate_prose(prose_input)
    assign_splits(prose)

    hyp = load_hypotactic(args.sources / "hypotactic")
    verse_input, verse_curation = curate_sentences(agdt_verse + pedalion_verse)
    verse_sentence, verse_metre, alignment_stats = align_verse_blocks(
        verse_input, hyp, revisions,
    )
    verse_sentence, verse_metre, passage_curation = exclude_disputed_verse_components(
        verse_sentence, verse_metre,
    )
    assign_splits(verse_sentence)
    assign_splits(verse_metre)

    rows_by_base_config = {
        "prose": prose, "verse_sentence": verse_sentence, "verse_metre": verse_metre,
    }
    validate_source_verse_alignment(rows_by_base_config)
    rows_by_config, variant_report = make_dataset_variants(rows_by_base_config)
    validation = validate(rows_by_config)

    base_schemas = {
        config: pa.Table.from_pylist(rows).schema
        for config, rows in rows_by_base_config.items()
    }
    data_stats = {}
    for config, rows in rows_by_config.items():
        base_config = config.rsplit("_", 1)[0]
        schema = None if config.endswith("_1") else variant_schema(base_schemas[base_config])
        data_stats[config] = write_parquet(rows, args.output, config, schema)
    args.metadata.mkdir(parents=True, exist_ok=True)
    (args.metadata / "source_revisions.json").write_text(
        json.dumps({
            key: {**SOURCE_INFO[key], "revision": revision}
            for key, revision in revisions.items()
        }, indent=2, ensure_ascii=False) + "\n"
    )
    (args.metadata / "dataset_variants.json").write_text(
        json.dumps(
            variant_report,
            indent=2,
            ensure_ascii=False,
            sort_keys=True,
        ) + "\n"
    )
    (args.metadata / "build_report.json").write_text(json.dumps({
        "data_files": data_stats,
        "authorship_curation": {
            "policy": (
                "Conservative known-author benchmark: anonymous, unknown, pseudonymous, "
                "traditional, fragmentary, mediated, corporate, and substantially disputed "
                "attributions are excluded; Homeric epics use separate corpus labels."
            ),
            "prose_input": prose_curation,
            "verse_input": verse_curation,
            "disputed_verse_passages": passage_curation,
        },
        "deduplication": dedup_stats,
        "splitting": {
            "seed": RANDOM_SEED,
            "strategy": "independent row-level 80/10/10 stratification by author and work",
            "variants": {
                "_1": "shared 100-task-eligible atomic rows",
                "_10": "shared atomic training rows; fixed exact 10-row evaluation chunks",
                "_100": "shared atomic training rows; fixed exact 100-row evaluation chunks",
            },
            "evaluation_chunking": {
                "seed": RANDOM_SEED,
                "remainder_policy": (
                    "discard n modulo 100 rows per author and split by stable hash once; "
                    "reuse the retained atomic rows in every task size"
                ),
                "ordering": "natural passage or line order within canonical work ID",
                "work_policy": (
                    "emit complete single-work chunks first, then combine residual work tails"
                ),
                "training_policy": (
                    "retain 100-task-eligible-author training rows as atomic units in all tasks"
                ),
            },
        },
        "alignment": alignment_stats,
        "validation": validation,
        "excluded": {
            "aphthonius": "No redistribution license is specified upstream.",
            "pedalion_mixed": sorted(PEDALION_EXCLUDE),
            "harrington_grctb_805": "File declares xml:lang=lat and contains Cicero despite its grctb path.",
        },
    }, indent=2, ensure_ascii=False, sort_keys=True) + "\n")
    print(json.dumps(validation, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()