File size: 54,531 Bytes
efc6467
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create Prolific-ready Potato data for the math study (MathVision + OrcaMath).



Adapted from the programming (MBPP) data-preparation script. It produces:

- one public Potato-ready CSV with all rows and role/subset metadata

- one public subset manifest for assigning Prolific participants to subsets

- one private gold annotation JSON for training feedback, testing, and controls

- one private local CSV that additionally contains the training feedback



The two math datasets are mixed in every role:

- training and testing: pilot dialogues from both datasets (gold = pilot labels)

- control pairs: the remaining pilot dialogues, balanced across datasets and

  mixed inside every subset

- main annotation: MathVision Verified 100 + OrcaMath Verified 100, split into

  blocks of 5 dialogues (alternately 3+2 and 2+3 from the two datasets)



Subsets (one participant each) chain the blocks: subset i = block i + block

i+1, wrapping around. Every subset has 10 dialogues (5 per dataset); its first

5 are shared with the previous subset and its last 5 with the next one, so

every dialogue is annotated by two different participants.



MathVision rows show the problem image, served by the Space from

`my-annotation-task/images/mathvision/` (see tools/fetch_mathvision_images.py).



The public CSV intentionally does not include gold labels.

"""

from __future__ import annotations

import argparse
import csv
import html
import json
import random
import re
from collections import Counter
from pathlib import Path
from typing import Any


DIMENSION_COLUMNS = [
    "Content Correctness",
    "Learner-State Assessment",
    "Issue Localization",
    "Disclosure Appropriateness",
    "Providing Guidance",
    "Coherence",
    "Actionability",
    "Clarity",
    "Conciseness",
    "Humanness",
]

ANNOTATION_KEY_ALIASES = {
    "Human-likeness": "Humanness",
    "Human-likeness ": "Humanness",
}
VALID_LABELS = {"Yes", "To some extent", "No"}

# Raw model keys as they appear in the JSON files -> (slug, display name).
# Responses from models missing here are rejected, so every model is included.
MODELS = {
    # MathVision
    "Claude Opus 4.6": ("claude_opus46", "Claude Opus 4.6"),
    "Gemini 3.1 Pro": ("gemini31_pro", "Gemini 3.1 Pro"),
    "GPT-5.4 2026-03-05": ("gpt54", "GPT-5.4"),
    "Llama 3.2 11B Vision": ("llama32_11b_vision", "Llama 3.2 11B Vision"),
    "Llama 4 Maverick": ("llama4_maverick", "Llama 4 Maverick"),
    "Ministral 14B": ("ministral_14b", "Ministral 14B"),
    "Phi-4 Reasoning Vision 15B": ("phi4_reasoning_vision_15b", "Phi-4 Reasoning Vision 15B"),
    # OrcaMath
    "ClaudeOpus46": ("claude_opus46", "Claude Opus 4.6"),
    "Gemini31Pro": ("gemini31_pro", "Gemini 3.1 Pro"),
    "GPT5_4": ("gpt54", "GPT-5.4"),
    "GPT54Mini": ("gpt54_mini", "GPT-5.4 Mini"),
    "Llama318B": ("llama31_8b", "Llama 3.1 8B"),
    "Llama3370B": ("llama33_70b", "Llama 3.3 70B"),
    "Mathstral7B": ("mathstral_7b", "Mathstral 7B"),
    "DeepSeekMath7B": ("deepseekmath_7b", "DeepSeekMath 7B"),
}
MODEL_ORDER = list(MODELS)

MATHVISION = "MathVision"
ORCAMATH = "OrcaMath"
DATASETS = [MATHVISION, ORCAMATH]

# Curated training/testing files (labels + per-dimension explanations).
# MathVision: the CSV covers 4 pilot dialogues, split at random (seeded) 2/2 into
# training and testing. OrcaMath: the CSV holds the training dialogues; testing
# dialogues are drawn at random from the other fully labelled pilot dialogues.
MATHVISION_EXPLANATIONS_CSV = "MathVision (train+test) Explanations - 01_06_08_13.csv"
ORCAMATH_EXPLANATIONS_CSV = "math_annotator_train&test_sets - math_annotator_training_set.csv"
PRETEST_DIALOGS_PER_DATASET = 2

FLAG_COLUMNS = ["training", "testing", "annotation", "control"]
TRAINING_FEEDBACK_COLUMN = "training_feedback_json"
MISSING_TEXT_VALUES = {"", "none", "null", "n/a", "na", "nan"}
IMAGE_URL_PREFIX = "/mathvision_images/"

INSTRUCTION_TEXT = (
    "Please read the following dialogue and annotate the tutor's last response "
    "according to the selected quality criteria."
)
GUIDELINES_URL = "https://drive.google.com/file/d/16E43zqGCV8m4X3JtDEvjwmwJg98-7XLz/view?usp=sharing"
GUIDELINES_LINK_TEXT = "guidelines with dimension explanations and examples"

TEXT_TEMPLATE = (
    "{instruction_text}\n"
    "Guidelines with dimension explanations and examples: {guidelines_url}\n\n"
    "Dialogue context:\n"
    "{dialog_context}\n\n"
    "{image_line}"
    "Reference (correct) solution:\n"
    "{correct_solution}\n\n"
    "Failure reason:\n"
    "{failure_reason}\n\n"
    "Next tutor response:\n"
    "{tutor_response}"
)

CODE_BLOCK_STYLE = (
    "background-color: #f6f8fa; border: 1px solid #d0d7de; border-radius: 6px; "
    "padding: 10px; margin: 8px 0 12px 0; font-family: monospace; "
    "font-size: 14px; line-height: 1.45;"
)

PUBLIC_COLUMNS = [
    "id",
    "dialog_id",
    "dataset",
    "source",
    "source_file",
    "role",
    "annotation_scope",
    "subset_id",
    "control_pair_id",
    "task_id",
    "mutant_id",
    "mathvision_instance_id",
    "image_url",
    "model_name",
    "model",
    "sample_id_one",
    "sample_id_two",
    "is_concise_in_prompt",
    "dialog_context",
    "failure_reason",
    "correct_solution",
    "tutor_response",
    "text2show",
    "text2show_html",
    "training",
    "testing",
    "annotation",
    "control",
    TRAINING_FEEDBACK_COLUMN,
]


def resolve_app_root(start: Path) -> Path:
    for candidate in [start, *start.parents]:
        if (candidate / "my-annotation-task" / "data").exists():
            return candidate
    raise FileNotFoundError("Could not find app root containing my-annotation-task/data.")


def clean_id_part(value: Any) -> str:
    text = "" if value is None else str(value).strip()
    if text.endswith(".0"):
        try:
            return str(int(float(text)))
        except ValueError:
            return text
    return text


def is_missing_text(value: Any) -> bool:
    return value is None or str(value).strip().lower() in MISSING_TEXT_VALUES


def normalize_label(value: Any) -> str:
    text = "" if value is None else str(value).strip()
    lowered = text.lower()
    if lowered == "yes":
        return "Yes"
    if lowered in {"to some extent", "some extent", "partial", "partially"}:
        return "To some extent"
    if lowered == "no":
        return "No"
    return text


def read_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=PUBLIC_COLUMNS, lineterminator="\n", extrasaction="ignore")
        writer.writeheader()
        writer.writerows(rows)


def write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def labels_from_annotation(annotation: Any) -> dict[str, str]:
    labels = {dimension: "" for dimension in DIMENSION_COLUMNS}
    if not isinstance(annotation, dict):
        return labels
    for key, value in annotation.items():
        normalized_key = ANNOTATION_KEY_ALIASES.get(key, key)
        if normalized_key in labels:
            labels[normalized_key] = normalize_label(value)
    return labels


def labels_complete(labels: dict[str, str]) -> bool:
    return all(labels.get(dimension) in VALID_LABELS for dimension in DIMENSION_COLUMNS)


# --------------------------------------------------------------------------
# Rendering: markdown-ish text with LaTeX math.
#
# Potato's HTML sanitizer escapes all text between tags again, so text is
# escaped here once and decoded once more in the browser (see config.yaml),
# after which KaTeX renders the explicit \( \) and \[ \] delimiters emitted
# below. Dollar-delimited math is converted with Pandoc's rule so currency
# amounts such as "$5 and $10" stay plain text.
# --------------------------------------------------------------------------

MATH_PLACEHOLDER = "\x00MATH{}\x00"
MATH_PLACEHOLDER_RE = re.compile("\x00MATH(\\d+)\x00")
DISPLAY_MATH_PATTERNS = [
    re.compile(r"\$\$(.+?)\$\$", re.DOTALL),
    re.compile(r"\\\[(.+?)\\\]", re.DOTALL),
    re.compile(r"(\\begin\{([a-zA-Z*]+)\}.+?\\end\{\2\})", re.DOTALL),
]
INLINE_MATH_PATTERNS = [
    re.compile(r"\\\((.+?)\\\)", re.DOTALL),
    re.compile(r"(?<![\\$\w])\$(?=[^\s$])((?:\\.|[^$\\\n])+?)(?<=[^\s\\])\$(?![\d$])"),
    # Bare \boxed{...} written without math delimiters (e.g. student answers).
    re.compile(r"(\\boxed\{(?:[^{}]|\{[^{}]*\})*\})"),
]
FENCE_RE = re.compile(r"^\s*```")
HEADING_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
BULLET_RE = re.compile(r"^\s*[-*+•]\s+(.*)$")
NUMBERED_RE = re.compile(r"^\s*(\d+)[.)]\s+(.*)$")
TABLE_RE = re.compile(r"^\s*\|.*\|\s*$")
TABLE_SEPARATOR_RE = re.compile(r"^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$")
RULE_RE = re.compile(r"^\s*([-*_])(\s*\1){2,}\s*$")
DISPLAY_ONLY_RE = re.compile("^\\s*\x00MATH(\\d+)\x00\\s*$")


def protect_math(text: str) -> tuple[str, list[tuple[str, bool]]]:
    """Replace math segments with placeholders; returns (text, [(tex, is_display)])."""
    segments: list[tuple[str, bool]] = []

    def replacer(is_display: bool, whole_env: bool = False):
        def replace(match: re.Match) -> str:
            tex = match.group(1)
            segments.append((tex, is_display))
            placeholder = MATH_PLACEHOLDER.format(len(segments) - 1)
            return f"\n{placeholder}\n" if is_display else placeholder
        return replace

    for pattern in DISPLAY_MATH_PATTERNS:
        text = pattern.sub(replacer(True), text)
    for pattern in INLINE_MATH_PATTERNS:
        text = pattern.sub(replacer(False), text)
    return text.replace("\\$", "$"), segments


def math_html(tex: str, is_display: bool) -> str:
    escaped = html.escape(tex.strip(), quote=False)
    if is_display:
        return f'<div class="potato-math-display">\\[{escaped}\\]</div>'
    return f'<span class="potato-math">\\({escaped}\\)</span>'


def inline_markup(text: str, segments: list[tuple[str, bool]]) -> str:
    escaped = html.escape(str(text), quote=False)
    marked = re.sub(r"`([^`\n]+)`", lambda m: f"<code>{m.group(1)}</code>", escaped)
    marked = re.sub(r"\*\*(.+?)\*\*", lambda m: f"<strong>{m.group(1)}</strong>", marked)
    marked = re.sub(r"(?<!\w)__(.+?)__(?!\w)", lambda m: f"<strong>{m.group(1)}</strong>", marked)
    marked = re.sub(r"(?<![\w*])\*(?![\s*])([^*\n]+?)(?<![\s*])\*(?![\w*])", lambda m: f"<em>{m.group(1)}</em>", marked)
    return MATH_PLACEHOLDER_RE.sub(lambda m: math_html(*segments[int(m.group(1))]), marked)


def table_html(lines: list[str], segments: list[tuple[str, bool]]) -> str:
    rows = []
    for line in lines:
        if TABLE_SEPARATOR_RE.match(line):
            continue
        cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
        tag = "th" if not rows else "td"
        rows.append("<tr>" + "".join(f"<{tag}>{inline_markup(cell, segments)}</{tag}>" for cell in cells) + "</tr>")
    return '<table class="potato-md-table">' + "".join(rows) + "</table>"


def rich_html(text: Any) -> str:
    """Render markdown-ish text with math as sanitizer-safe HTML."""
    source, segments = protect_math(str(text or "").replace("\r\n", "\n"))
    lines = source.split("\n")
    parts: list[str] = []
    paragraph: list[str] = []
    list_tag = ""
    list_items: list[str] = []
    list_start = 1

    def flush_paragraph() -> None:
        if paragraph:
            parts.append("<p>" + "<br>".join(inline_markup(line, segments) for line in paragraph) + "</p>")
            paragraph.clear()

    def flush_list() -> None:
        nonlocal list_tag
        if list_tag:
            start = f' start="{list_start}"' if list_tag == "ol" and list_start != 1 else ""
            parts.append(f"<{list_tag}{start}>" + "".join(f"<li>{item}</li>" for item in list_items) + f"</{list_tag}>")
            list_items.clear()
            list_tag = ""

    def flush_all() -> None:
        flush_paragraph()
        flush_list()

    index = 0
    while index < len(lines):
        line = lines[index]
        stripped = line.strip()

        if FENCE_RE.match(line):
            flush_all()
            code_lines = []
            index += 1
            while index < len(lines) and not FENCE_RE.match(lines[index]):
                code_lines.append(lines[index])
                index += 1
            code = MATH_PLACEHOLDER_RE.sub(
                lambda m: segments[int(m.group(1))][0], "\n".join(code_lines)
            )
            parts.append(
                f'<pre class="potato-code-block" style="{CODE_BLOCK_STYLE}"><code>'
                f"{html.escape(code.strip(chr(10)), quote=False)}</code></pre>"
            )
            index += 1
            continue

        if not stripped:
            flush_paragraph()
            if list_tag:
                # A blank line inside a list only ends it if the next line is not a list item.
                next_line = next((l for l in lines[index + 1 :] if l.strip()), "")
                if not ((list_tag == "ul" and BULLET_RE.match(next_line)) or (list_tag == "ol" and NUMBERED_RE.match(next_line))):
                    flush_list()
            index += 1
            continue

        display = DISPLAY_ONLY_RE.match(line)
        if display:
            flush_paragraph()
            rendered = math_html(*segments[int(display.group(1))])
            if list_tag and list_items:
                list_items[-1] += rendered
            else:
                flush_list()
                parts.append(rendered)
            index += 1
            continue

        heading = HEADING_RE.match(line)
        if heading:
            flush_all()
            level = min(6, max(4, len(heading.group(1)) + 2))
            parts.append(f"<h{level}>{inline_markup(heading.group(2), segments)}</h{level}>")
            index += 1
            continue

        if RULE_RE.match(line):
            flush_all()
            parts.append("<hr>")
            index += 1
            continue

        if TABLE_RE.match(line):
            flush_all()
            table_lines = []
            while index < len(lines) and TABLE_RE.match(lines[index]):
                table_lines.append(lines[index])
                index += 1
            parts.append(table_html(table_lines, segments))
            continue

        bullet = BULLET_RE.match(line)
        numbered = NUMBERED_RE.match(line)
        if bullet or numbered:
            flush_paragraph()
            tag = "ul" if bullet else "ol"
            if list_tag != tag:
                flush_list()
                list_tag = tag
                list_start = int(numbered.group(1)) if numbered else 1
            list_items.append(inline_markup(bullet.group(1) if bullet else numbered.group(2), segments))
            index += 1
            continue

        if list_tag and list_items and line[:1].isspace():
            list_items[-1] += "<br>" + inline_markup(stripped, segments)
            index += 1
            continue

        flush_list()
        paragraph.append(stripped)
        index += 1

    flush_all()
    return '<div class="potato-tte-rich">' + "\n".join(parts) + "</div>"


def split_dialog_turns(text: str) -> list[tuple[str, str]]:
    """Split 'Tutor: ...' / 'Student: ...' conversation text into turns."""
    turns: list[tuple[str, str]] = []
    for match in re.finditer(r"(?ms)^(Tutor|Student):[ \t]*(.*?)(?=^(?:Tutor|Student):|\Z)", str(text)):
        turns.append((match.group(1), match.group(2).strip()))
    if not turns:
        turns.append(("Tutor", str(text).strip()))
    return turns


def make_instruction_html() -> str:
    return (
        f'<div class="potato-task-instruction">{html.escape(INSTRUCTION_TEXT)} '
        f'See <a href="{GUIDELINES_URL}" target="_blank" rel="noopener noreferrer">'
        f"{html.escape(GUIDELINES_LINK_TEXT)}</a>.</div>"
    )


def utterance_html(label: str, body: str, speaker_class: str) -> str:
    return (
        '<div class="potato-tte-utterance">'
        f'<div class="potato-tte-speaker potato-tte-speaker-{speaker_class}">{html.escape(label)}</div>'
        f"{body}"
        "</div>"
    )


def image_html(image_url: str) -> str:
    return (
        '<figure class="potato-tte-figure">'
        f'<a href="{html.escape(image_url)}" target="_blank" rel="noopener noreferrer">'
        f'<img src="{html.escape(image_url)}" alt="Problem image">'
        "</a>"
        '<figcaption class="potato-tte-figure-caption">Problem image (click to enlarge)</figcaption>'
        "</figure>"
    )


def make_text2show(row: dict[str, Any]) -> str:
    return TEXT_TEMPLATE.format(
        instruction_text=INSTRUCTION_TEXT,
        guidelines_url=GUIDELINES_URL,
        dialog_context=row["dialog_context"],
        image_line=f"Problem image: {row['image_url']}\n\n" if row.get("image_url") else "",
        correct_solution=row["correct_solution"],
        failure_reason=row["failure_reason"] or "Not available",
        tutor_response=row["tutor_response"],
    )


def make_text2show_html(row: dict[str, Any]) -> str:
    dialog_parts = ['<h3 class="potato-tte-title">Dialogue</h3>']
    image_placed = False
    for speaker, body in split_dialog_turns(str(row["dialog_context"])):
        body_html = rich_html(body)
        if row.get("image_url") and speaker == "Tutor" and not image_placed:
            body_html += image_html(str(row["image_url"]))
            image_placed = True
        dialog_parts.append(utterance_html(speaker, body_html, speaker.lower()))
    if row.get("image_url") and not image_placed:
        dialog_parts.insert(1, image_html(str(row["image_url"])))
    dialog_parts.append(utterance_html("Tutor", rich_html(row["tutor_response"]), "tutor"))

    side_sections = [
        '    <div class="potato-tte-side-section">',
        '      <h3 class="potato-tte-side-title">Reference solution</h3>',
        rich_html(row["correct_solution"]),
        "    </div>",
    ]
    if row["failure_reason"]:
        side_sections += [
            '    <div class="potato-tte-side-section">',
            '      <h3 class="potato-tte-side-title">Failure reason</h3>',
            rich_html(row["failure_reason"]),
            "    </div>",
        ]

    return "\n".join(
        [
            make_instruction_html(),
            '<div class="potato-tte-layout">',
            '  <div class="potato-tte-card potato-tte-dialog-card">',
            "\n".join(dialog_parts),
            "  </div>",
            '  <div class="potato-tte-card potato-tte-side-card">',
            *side_sections,
            "  </div>",
            "</div>",
        ]
    )


def with_generated_text(row: dict[str, Any]) -> dict[str, Any]:
    row["text2show"] = make_text2show(row)
    row["text2show_html"] = make_text2show_html(row)
    return row


def role_flags(role: str) -> dict[str, bool]:
    return {flag: flag == role for flag in FLAG_COLUMNS}


# --------------------------------------------------------------------------
# Source dialogues
# --------------------------------------------------------------------------


class SourceData:
    def __init__(self, mathvision_metadata: dict[str, dict], image_dir: Path):
        self.mathvision_metadata = mathvision_metadata
        self.image_dir = image_dir
        # dialog_id -> {"correct_solution": ..., "failure_reason": ...} from curated files.
        self.dialog_overrides: dict[str, dict[str, str]] = {}

    def dialog_fields(self, dialog: dict[str, Any], dataset: str) -> dict[str, str]:
        dialog_id = clean_id_part(dialog["conversation_id"])
        instance_id = clean_id_part(dialog.get("instance_id")) if dataset == MATHVISION else ""
        image_url = ""
        override = self.dialog_overrides.get(dialog_id, {})
        correct_solution = override.get("correct_solution") or (
            "" if is_missing_text(dialog.get("Ground_Truth_Solution")) else str(dialog["Ground_Truth_Solution"])
        )
        failure_reason = override.get("failure_reason") or (
            "" if is_missing_text(dialog.get("failure_reason")) else str(dialog["failure_reason"])
        )

        if dataset == MATHVISION:
            metadata = self.mathvision_metadata.get(instance_id)
            if not metadata:
                raise ValueError(
                    f"No MathVision metadata for instance {instance_id!r} ({dialog_id}); "
                    "run tools/fetch_mathvision_images.py first"
                )
            if not (self.image_dir / metadata["image_file"]).exists():
                raise FileNotFoundError(f"Missing image {metadata['image_file']} for {dialog_id}")
            image_url = IMAGE_URL_PREFIX + metadata["image_file"]
            if not correct_solution:
                # MathVision pilot dialogues have no Ground_Truth_Solution.
                correct_solution = metadata["solution"] or ""
                answer = metadata["answer"]
                if answer:
                    answer_line = f"Correct answer: {answer}"
                    correct_solution = f"{correct_solution}\n\n{answer_line}" if correct_solution else answer_line

        if not correct_solution:
            raise ValueError(f"No reference solution for {dialog_id}")

        return {
            "dialog_id": dialog_id,
            "dataset": dataset,
            "mathvision_instance_id": instance_id,
            "image_url": image_url,
            "dialog_context": str(dialog.get("conversation_history", "")),
            "failure_reason": failure_reason,
            "correct_solution": correct_solution,
        }


def ordered_models(responses: dict[str, Any], dialog_id: str) -> list[str]:
    unknown = sorted(set(responses) - set(MODELS))
    if unknown:
        raise ValueError(f"Unknown model(s) {unknown} in {dialog_id}; add them to MODELS")
    return [model for model in MODEL_ORDER if model in responses]


def make_public_row(

    *,

    row_id: str,

    fields: dict[str, str],

    source: str,

    source_file: str,

    role: str,

    subset_id: str,

    raw_model: str,

    tutor_response: str,

    annotation_scope: str = "",

    control_pair_id: str = "",

) -> dict[str, Any]:
    model_slug, model_display = MODELS[raw_model]
    row: dict[str, Any] = {
        "id": row_id,
        **fields,
        "source": source,
        "source_file": source_file,
        "role": role,
        "annotation_scope": annotation_scope,
        "subset_id": subset_id,
        "control_pair_id": control_pair_id,
        "task_id": "",
        "mutant_id": "",
        "model_name": model_slug,
        "model": model_display,
        "sample_id_one": "",
        "sample_id_two": "",
        "is_concise_in_prompt": "",
        "tutor_response": tutor_response,
        TRAINING_FEEDBACK_COLUMN: "",
        **role_flags(role),
    }
    return with_generated_text(row)


def make_gold_item(

    *,

    row: dict[str, Any],

    labels: dict[str, str],

    explanations: dict[str, str] | None = None,

) -> dict[str, Any]:
    item = {
        "instance_number": 0,
        "dialog_id": row["dialog_id"],
        "dataset": row["dataset"],
        "source": row["source"],
        "role": row["role"],
        "annotation_scope": row["annotation_scope"],
        "subset_id": row["subset_id"],
        "control_pair_id": row["control_pair_id"],
        "training": str(row["training"]),
        "testing": str(row["testing"]),
        "annotation": str(row["annotation"]),
        "control": str(row["control"]),
        "labels": labels,
    }
    if explanations is not None:
        item["explanations"] = explanations
    return item


def block_ids(count: int) -> list[str]:
    return [f"block_{index + 1:02d}" for index in range(count)]


def chained_subsets(blocks: list[str]) -> list[dict[str, Any]]:
    """Subset i = blocks i and i+1 (wrapping), so neighbouring subsets share one block."""
    count = len(blocks)
    names = [f"subset_{index + 1:03d}" for index in range(count)]
    return [
        {
            "subset_id": names[index],
            "blocks": [blocks[index], blocks[(index + 1) % count]],
            "overlaps_with": [names[(index - 1) % count], names[(index + 1) % count]],
        }
        for index in range(count)
    ]


def normalized_text(value: Any) -> str:
    return re.sub(r"\s+", " ", str(value or "")).strip()


def row_explanation(row: dict[str, Any], dimension: str) -> str:
    for column in (f"{dimension} Explanation", f"Explanation for {dimension}", f"Explantation for {dimension}"):
        value = str(row.get(column) or "").strip()
        if value:
            return value
    return ""


def load_curated_csv(

    path: Path,

    dataset: str,

    pilot_dialogs: dict[str, tuple[str, Path, dict[str, Any]]],

    sources: SourceData,

) -> tuple[dict[str, dict[str, dict[str, str]]], dict[str, dict[str, dict[str, str]]]]:
    """Read a curated training/testing CSV for one dataset.



    Rows are matched to pilot responses by their tutor response text. Returns

    (explanations, labels), both keyed dialog_id -> raw model -> dimension, and

    stores the curated reference solution and failure reason as dialogue overrides.

    """
    responses_by_text = {}
    for dialog_id, (dialog_dataset, _, dialog) in pilot_dialogs.items():
        if dialog_dataset != dataset:
            continue
        for raw_model, response in (dialog.get("anno_llm_responses") or {}).items():
            responses_by_text[normalized_text(response.get("response"))] = (dialog_id, raw_model)

    explanations: dict[str, dict[str, dict[str, str]]] = {}
    labels: dict[str, dict[str, dict[str, str]]] = {}
    with path.open(newline="", encoding="utf-8-sig") as handle:
        for row_number, row in enumerate(csv.DictReader(handle), start=2):
            match = responses_by_text.get(normalized_text(row.get("tutor_response")))
            if not match:
                raise ValueError(f"{path.name} line {row_number} does not match any {dataset} pilot response")
            dialog_id, raw_model = match
            explanations.setdefault(dialog_id, {})[raw_model] = {
                dimension: row_explanation(row, dimension) for dimension in DIMENSION_COLUMNS
            }
            labels.setdefault(dialog_id, {})[raw_model] = {
                dimension: normalize_label(row.get(dimension)) for dimension in DIMENSION_COLUMNS
            }
            override = sources.dialog_overrides.setdefault(dialog_id, {})
            solution = str(row.get("correct_solution") or "").strip()
            answer = str(row.get("correct_answer") or "").strip()
            if solution:
                override["correct_solution"] = f"{solution}\n\nCorrect answer: {answer}" if answer else solution
            reason = row.get("reason_for_wrong_solution") or row.get("failure_reason")
            if not is_missing_text(reason):
                override["failure_reason"] = str(reason).strip()
    return explanations, labels


def choose_pretest_dialogs(

    mathvision_candidates: list[str],

    orcamath_training: list[str],

    orcamath_candidates: list[str],

    seed: int,

) -> tuple[list[str], list[str]]:
    """Pick training/testing dialogues (seeded), alternating the two datasets."""
    rng = random.Random(f"{seed}:pretest")
    count = PRETEST_DIALOGS_PER_DATASET
    if len(mathvision_candidates) < 2 * count:
        raise ValueError(f"Need {2 * count} MathVision training/testing dialogues, found {len(mathvision_candidates)}")
    mathvision = rng.sample(sorted(mathvision_candidates), 2 * count)
    mathvision_training, mathvision_testing = mathvision[:count], mathvision[count:]

    orcamath_training = sorted(orcamath_training)
    remaining = sorted(set(orcamath_candidates) - set(orcamath_training))
    if len(remaining) < count:
        raise ValueError(f"Need {count} OrcaMath testing dialogues, found {len(remaining)}")
    orcamath_testing = rng.sample(remaining, count)

    def alternate(first: list[str], second: list[str]) -> list[str]:
        ordered = []
        for index in range(max(len(first), len(second))):
            ordered += first[index : index + 1] + second[index : index + 1]
        return ordered

    return alternate(mathvision_training, orcamath_training), alternate(orcamath_testing, mathvision_testing)


def expand_pretest_dialogs(

    dialog_ids: list[str],

    role: str,

    pilot_dialogs: dict[str, tuple[str, Path, dict[str, Any]]],

    sources: SourceData,

    explanations: dict[str, dict[str, dict[str, str]]],

    label_overrides: dict[str, dict[str, dict[str, str]]],

) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], list[str]]:
    public_rows: list[dict[str, Any]] = []
    gold_items: dict[str, dict[str, Any]] = {}
    missing_explanations: list[str] = []

    for dialog_id in dialog_ids:
        if dialog_id not in pilot_dialogs:
            raise ValueError(f"{role} dialogue {dialog_id!r} is not in the pilot (annotated) files")
        dataset, path, dialog = pilot_dialogs[dialog_id]
        fields = sources.dialog_fields(dialog, dataset)
        responses = dialog.get("anno_llm_responses") or {}
        for raw_model in ordered_models(responses, dialog_id):
            response = responses[raw_model]
            labels = labels_from_annotation(response.get("annotation"))
            override_labels = (label_overrides.get(dialog_id) or {}).get(raw_model)
            if override_labels:
                conflicts = [d for d in DIMENSION_COLUMNS if labels[d] in VALID_LABELS and labels[d] != override_labels[d]]
                if conflicts:
                    raise ValueError(f"Curated labels for {dialog_id} / {raw_model} differ from the pilot on {conflicts}")
                labels = override_labels
            if not labels_complete(labels):
                raise ValueError(f"{role} dialogue {dialog_id} / {raw_model} has incomplete gold labels: {labels}")
            row_id = f"{role}_{dialog_id}_{MODELS[raw_model][0]}"
            public_row = make_public_row(
                row_id=row_id,
                fields=fields,
                source=role,
                source_file=path.name,
                role=role,
                subset_id="all",
                raw_model=raw_model,
                tutor_response=str(response.get("response", "")),
            )
            public_rows.append(public_row)

            item_explanations = None
            if role == "training":
                raw = (explanations.get(dialog_id) or {}).get(raw_model) or {}
                item_explanations = {
                    dimension: "" for dimension in DIMENSION_COLUMNS
                }
                for key, value in raw.items():
                    dimension = ANNOTATION_KEY_ALIASES.get(key, key)
                    if dimension in item_explanations:
                        item_explanations[dimension] = str(value or "").strip()
                if not all(item_explanations.values()):
                    missing_explanations.append(row_id)
            gold_items[row_id] = make_gold_item(row=public_row, labels=labels, explanations=item_explanations)

    return public_rows, gold_items, missing_explanations


def expand_annotation_dialogs(

    main_sources: list[tuple[str, Path]],

    subsets: list[str],

    sources: SourceData,

    seed: int,

) -> list[dict[str, Any]]:
    """Split each dataset's dialogues evenly across blocks, then interleave datasets.



    The second dataset is spread in reverse block order, so with 100 dialogues

    per dataset and 40 blocks the blocks alternate 3+2 and 2+3 and every pair of

    neighbouring blocks holds 5 dialogues of each dataset.

    """
    by_subset: dict[str, dict[str, list[dict[str, Any]]]] = {subset_id: {} for subset_id in subsets}
    for dataset_index, (dataset, path) in enumerate(main_sources):
        dialogs = list(read_json(path))
        if len(subsets) > len(dialogs):
            raise ValueError(f"Cannot split {len(dialogs)} {dataset} dialogues into {len(subsets)} non-empty blocks")
        random.Random(f"{seed}:annotation:{dataset}").shuffle(dialogs)
        for dialog_index, dialog in enumerate(dialogs):
            block_index = (dialog_index * len(subsets)) // len(dialogs)
            if dataset_index % 2:
                block_index = len(subsets) - 1 - block_index
            by_subset[subsets[block_index]].setdefault(dataset, []).append((dialog, path))

    public_rows: list[dict[str, Any]] = []
    for subset_id in subsets:
        queues = [list(by_subset[subset_id].get(dataset, [])) for dataset, _ in main_sources]
        position = 0
        while any(queues):
            queue = queues[position % len(queues)]
            position += 1
            if not queue:
                continue
            dialog, path = queue.pop(0)
            dataset = next(name for name, source_path in main_sources if source_path == path)
            fields = sources.dialog_fields(dialog, dataset)
            responses = dialog.get("anno_llm_responses") or {}
            for raw_model in ordered_models(responses, fields["dialog_id"]):
                public_rows.append(
                    make_public_row(
                        row_id=f"annotation_{fields['dialog_id']}_{MODELS[raw_model][0]}",
                        fields=fields,
                        source="annotation_unique",
                        source_file=path.name,
                        role="annotation",
                        subset_id=subset_id,
                        annotation_scope="unique",
                        raw_model=raw_model,
                        tutor_response=str(responses[raw_model].get("response", "")),
                    )
                )
    return public_rows


def control_pair_candidates(

    dataset: str,

    path: Path,

    exclude_dialogs: set[str],

    excluded: list[dict[str, str]],

) -> list[tuple[dict[str, Any], list[str]]]:
    candidates = []
    for dialog in read_json(path):
        dialog_id = clean_id_part(dialog["conversation_id"])
        if dialog_id in exclude_dialogs:
            excluded.append({"dialog_id": dialog_id, "dataset": dataset, "reason": "used_for_training_or_testing"})
            continue

        responses = dialog.get("anno_llm_responses") or {}
        available_models = ordered_models(responses, dialog_id)
        paired_models = available_models[: len(available_models) - (len(available_models) % 2)]
        for raw_model in available_models[len(paired_models) :]:
            excluded.append({"dialog_id": dialog_id, "dataset": dataset, "model": raw_model, "reason": "unpaired_control_response"})

        for pair_index in range(0, len(paired_models), 2):
            pair_models = paired_models[pair_index : pair_index + 2]
            incomplete = [
                model for model in pair_models
                if not labels_complete(labels_from_annotation(responses[model].get("annotation")))
            ]
            if incomplete:
                excluded.append({
                    "dialog_id": dialog_id,
                    "dataset": dataset,
                    "models": ", ".join(pair_models),
                    "reason": "incomplete_gold_labels",
                })
                continue
            candidates.append((dialog, pair_models))
    return candidates


def expand_control_pairs(

    pilot_sources: list[tuple[str, Path]],

    subsets: list[str],

    exclude_dialogs: set[str],

    control_pairs_per_subset: int,

    sources: SourceData,

) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], list[dict[str, str]]]:
    """Give every subset control pairs from both datasets.



    Slots are filled slot-by-slot across subsets, alternating the dataset per

    subset and slot, so each subset gets a mix of MathVision and OrcaMath pairs

    and consecutive pairs of the same dialogue go to different subsets.

    """
    excluded: list[dict[str, str]] = []
    queues = {
        dataset: control_pair_candidates(dataset, path, exclude_dialogs, excluded)
        for dataset, path in pilot_sources
    }
    paths = dict(pilot_sources)
    dataset_names = [dataset for dataset, _ in pilot_sources]

    assignments: list[tuple[str, str, dict[str, Any], list[str]]] = []
    for slot in range(control_pairs_per_subset):
        for subset_index, subset_id in enumerate(subsets):
            preferred = dataset_names[(subset_index + slot) % len(dataset_names)]
            order = [preferred] + [name for name in dataset_names if name != preferred]
            dataset = next((name for name in order if queues[name]), None)
            if dataset is None:
                raise ValueError("Not enough control pairs in the pilot files for the requested quota")
            dialog, pair_models = queues[dataset].pop(0)
            assignments.append((subset_id, dataset, dialog, pair_models))

    for dataset, remaining in queues.items():
        for dialog, pair_models in remaining:
            excluded.append({
                "dialog_id": clean_id_part(dialog["conversation_id"]),
                "dataset": dataset,
                "models": ", ".join(pair_models),
                "reason": "beyond_control_pair_quota",
            })

    public_rows: list[dict[str, Any]] = []
    gold_items: dict[str, dict[str, Any]] = {}
    # Order rows by subset so the CSV is easy to inspect; numbering stays global.
    assignments.sort(key=lambda item: subsets.index(item[0]))
    for counter, (subset_id, dataset, dialog, pair_models) in enumerate(assignments, start=1):
        fields = sources.dialog_fields(dialog, dataset)
        control_pair_id = f"control_pair_{counter:03d}_{fields['dialog_id']}"
        responses = dialog["anno_llm_responses"]
        for raw_model in pair_models:
            row_id = f"control_{fields['dialog_id']}_{MODELS[raw_model][0]}"
            public_row = make_public_row(
                row_id=row_id,
                fields=fields,
                source="control",
                source_file=paths[dataset].name,
                role="control",
                subset_id=subset_id,
                control_pair_id=control_pair_id,
                raw_model=raw_model,
                tutor_response=str(responses[raw_model].get("response", "")),
            )
            public_rows.append(public_row)
            gold_items[row_id] = make_gold_item(
                row=public_row,
                labels=labels_from_annotation(responses[raw_model].get("annotation")),
            )

    return public_rows, gold_items, excluded


def build_subset_manifest(

    rows: list[dict[str, Any]],

    blocks: list[str],

    subsets: list[dict[str, Any]],

    excluded_controls: list[dict[str, str]],

) -> dict[str, Any]:
    by_block: dict[str, Counter[str]] = {block_id: Counter() for block_id in blocks}
    dialogs_by_block: dict[str, dict[str, set[str]]] = {block_id: {} for block_id in blocks}
    control_pairs_by_block: dict[str, dict[str, set[str]]] = {block_id: {} for block_id in blocks}
    global_counts = Counter()
    pretest_by_dataset: dict[str, Counter[str]] = {}

    for row in rows:
        role = str(row["role"])
        dataset = str(row["dataset"])
        global_counts[role] += 1
        block_id = str(row["subset_id"])
        if block_id not in by_block:
            pretest_by_dataset.setdefault(role, Counter())[dataset] += 1
            continue
        by_block[block_id][role] += 1
        if role == "annotation":
            dialogs_by_block[block_id].setdefault(dataset, set()).add(str(row["dialog_id"]))
        if row.get("control_pair_id"):
            control_pairs_by_block[block_id].setdefault(dataset, set()).add(str(row["control_pair_id"]))

    def merged(source: dict[str, dict[str, set[str]]], block_list: list[str]) -> dict[str, list[str]]:
        result: dict[str, set[str]] = {}
        for block_id in block_list:
            for dataset, ids in source[block_id].items():
                result.setdefault(dataset, set()).update(ids)
        return {dataset: sorted(ids) for dataset, ids in sorted(result.items())}

    manifest_blocks = [
        {
            "block_id": block_id,
            "annotation_dialogs": merged(dialogs_by_block, [block_id]),
            "control_pairs": merged(control_pairs_by_block, [block_id]),
        }
        for block_id in blocks
    ]

    manifest_subsets = []
    for subset in subsets:
        role_counts = Counter()
        for block_id in subset["blocks"]:
            role_counts.update(by_block[block_id])
        dialogs = merged(dialogs_by_block, subset["blocks"])
        control_pairs = merged(control_pairs_by_block, subset["blocks"])
        annotation_instances = role_counts.get("annotation", 0)
        manifest_subsets.append({
            **subset,
            "annotation_instances": annotation_instances,
            "annotation_dialogs": sum(len(ids) for ids in dialogs.values()),
            "annotation_dialogs_by_dataset": {dataset: len(ids) for dataset, ids in dialogs.items()},
            "control_instances": role_counts.get("control", 0),
            "control_pairs": sum(len(ids) for ids in control_pairs.values()),
            "control_pairs_by_dataset": {dataset: len(ids) for dataset, ids in control_pairs.items()},
            "training_instances": global_counts.get("training", 0),
            "testing_instances": global_counts.get("testing", 0),
            "estimated_visible_instances": (
                global_counts.get("training", 0)
                + global_counts.get("testing", 0)
                + annotation_instances
                + role_counts.get("control", 0)
            ),
        })

    return {
        "version": 3,
        "assignment_strategy": (
            "training/testing shown to all; annotation dialogues split into blocks of 5; "
            "subset i = blocks i and i+1 (wrapping), so each dialogue is in two subsets; "
            "control pairs balanced across datasets"
        ),
        "datasets": DATASETS,
        "global_counts": dict(global_counts),
        "pretest_instances_by_dataset": {role: dict(counts) for role, counts in pretest_by_dataset.items()},
        "block_count": len(blocks),
        "subset_count": len(subsets),
        "blocks": manifest_blocks,
        "subsets": manifest_subsets,
        "excluded_controls": excluded_controls,
    }


def build_gold_payload(gold_items: dict[str, dict[str, Any]], rows: list[dict[str, Any]]) -> dict[str, Any]:
    row_order = {row["id"]: index + 1 for index, row in enumerate(rows)}
    ordered_items = {}
    for item_id in sorted(gold_items, key=lambda key: row_order.get(key, 10**9)):
        item = dict(gold_items[item_id])
        item["instance_number"] = row_order.get(item_id)
        ordered_items[item_id] = item
    return {
        "version": 2,
        "source": "prolific_data_prep_math",
        "label_columns": DIMENSION_COLUMNS,
        "items": ordered_items,
    }


def rows_with_training_feedback(rows: list[dict[str, Any]], gold_items: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
    rows_with_feedback = []
    for row in rows:
        copied = dict(row)
        gold_item = gold_items.get(str(row.get("id", "")), {})
        if row.get("role") == "training" and gold_item:
            copied[TRAINING_FEEDBACK_COLUMN] = json.dumps(
                {
                    "labels": gold_item.get("labels", {}),
                    "explanations": gold_item.get("explanations", {}),
                },
                ensure_ascii=False,
                separators=(",", ":"),
            )
        rows_with_feedback.append(copied)
    return rows_with_feedback


def validate(rows: list[dict[str, Any]], subsets: list[dict[str, Any]], training: list[str], testing: list[str]) -> None:
    ids = [row["id"] for row in rows]
    duplicates = [item_id for item_id, count in Counter(ids).items() if count > 1]
    if duplicates:
        raise ValueError(f"Duplicate item ids: {duplicates[:5]}")

    role_dialogs: dict[str, set[str]] = {}
    for row in rows:
        role_dialogs.setdefault(row["role"], set()).add(row["dialog_id"])
    for first, second in [("training", "testing"), ("training", "control"), ("testing", "control")]:
        overlap = role_dialogs.get(first, set()) & role_dialogs.get(second, set())
        if overlap:
            raise ValueError(f"{first}/{second} dialogue overlap: {sorted(overlap)}")

    for role in ("training", "testing"):
        datasets = {row["dataset"] for row in rows if row["role"] == role}
        if datasets != set(DATASETS):
            raise ValueError(f"{role} must contain both datasets, got {sorted(datasets)}")
    for subset in subsets:
        subset_id = subset["subset_id"]
        for role in ("annotation", "control"):
            subset_rows = [r for r in rows if r["role"] == role and r["subset_id"] in subset["blocks"]]
            datasets = {row["dataset"] for row in subset_rows}
            if role == "control" and not datasets:
                continue
            if datasets != set(DATASETS) and len(subset_rows) > 2:
                raise ValueError(f"{subset_id} {role} items do not mix both datasets: {sorted(datasets)}")
        dialogs = Counter(
            dataset for dataset, _ in {
                (row["dataset"], row["dialog_id"]) for row in rows
                if row["role"] == "annotation" and row["subset_id"] in subset["blocks"]
            }
        )
        if len(set(dialogs.values())) > 1:
            raise ValueError(f"{subset_id} has unbalanced dialogues per dataset: {dict(dialogs)}")

    for row in rows:
        if row["dataset"] == MATHVISION and not row["image_url"]:
            raise ValueError(f"MathVision row without image: {row['id']}")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--app-root", type=Path, default=None)
    parser.add_argument("--math-dir", type=Path, default=None, help="Math/MR folder with the dataset JSON files.")
    parser.add_argument("--private-dir", type=Path, default=None, help="Private output folder (default: ../data next to the app).")
    parser.add_argument("--block-count", type=int, default=40,
                        help="Blocks of annotation dialogues; also the number of chained subsets.")
    parser.add_argument("--control-pairs-per-block", type=int, default=1,
                        help="Control pairs per block (each subset gets those of its two blocks).")
    parser.add_argument("--seed", type=int, default=20261103)
    parser.add_argument("--training-dialogs", nargs="+", default=None, help="Override the random training selection.")
    parser.add_argument("--testing-dialogs", nargs="+", default=None, help="Override the random testing selection.")
    parser.add_argument("--mathvision-explanations-csv", type=Path, default=None,
                        help="Curated MathVision train/test labels and explanations.")
    parser.add_argument("--orcamath-explanations-csv", type=Path, default=None,
                        help="Curated OrcaMath training labels and explanations.")
    parser.add_argument("--mathvision-metadata", type=Path, default=None)
    parser.add_argument("--output-csv", type=Path, default=None)
    parser.add_argument("--manifest-output", type=Path, default=None)
    parser.add_argument("--local-output-csv", type=Path, default=None)
    parser.add_argument("--gold-output", type=Path, default=None)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    app_root = args.app_root or resolve_app_root(Path.cwd())
    math_dir = args.math_dir or app_root.parents[1]
    private_dir = args.private_dir or app_root.parent / "data"
    data_dir = app_root / "my-annotation-task" / "data"
    image_dir = app_root / "my-annotation-task" / "images" / "mathvision"

    mathvision_pilot = math_dir / "MathVision" / "MathVision_pilot.json"
    mathvision_main = math_dir / "MathVision" / "MathVision_verified_100.json"
    orcamath_pilot = math_dir / "OrcaMathVerified100" / "OrcaMath_pilot.json"
    orcamath_main = math_dir / "OrcaMathVerified100" / "OrcaMath_Verified_100.json"
    pilot_sources = [(MATHVISION, mathvision_pilot), (ORCAMATH, orcamath_pilot)]
    main_sources = [(MATHVISION, mathvision_main), (ORCAMATH, orcamath_main)]

    metadata_path = args.mathvision_metadata or app_root / "tools" / "mathvision_metadata.json"
    output_csv = args.output_csv or data_dir / "prolific_potato_ready.csv"
    manifest_output = args.manifest_output or data_dir / "prolific_subset_manifest.json"
    local_output_csv = args.local_output_csv or private_dir / "prolific_potato_ready_local.csv"
    gold_output = args.gold_output or private_dir / "gold_annotations.json"

    if args.block_count < 3:
        raise ValueError("--block-count must be >= 3 so neighbouring subsets differ")
    if args.control_pairs_per_block < 0:
        raise ValueError("--control-pairs-per-block must be >= 0")
    if not metadata_path.exists():
        raise FileNotFoundError(f"{metadata_path} not found; run tools/fetch_mathvision_images.py first")

    sources = SourceData(read_json(metadata_path), image_dir)
    pilot_dialogs = {
        clean_id_part(dialog["conversation_id"]): (dataset, path, dialog)
        for dataset, path in pilot_sources
        for dialog in read_json(path)
    }

    mathvision_csv = args.mathvision_explanations_csv or math_dir / "MathVision" / MATHVISION_EXPLANATIONS_CSV
    orcamath_csv = args.orcamath_explanations_csv or math_dir / "OrcaMathVerified100" / ORCAMATH_EXPLANATIONS_CSV
    explanations, label_overrides = load_curated_csv(mathvision_csv, MATHVISION, pilot_dialogs, sources)
    orcamath_explanations, orcamath_labels = load_curated_csv(orcamath_csv, ORCAMATH, pilot_dialogs, sources)
    explanations.update(orcamath_explanations)
    label_overrides.update(orcamath_labels)

    if args.training_dialogs and args.testing_dialogs:
        training_dialogs, testing_dialogs = args.training_dialogs, args.testing_dialogs
    else:
        orcamath_candidates = [
            dialog_id for dialog_id, (dataset, _, dialog) in pilot_dialogs.items()
            if dataset == ORCAMATH and all(
                labels_complete(labels_from_annotation(response.get("annotation")))
                for response in (dialog.get("anno_llm_responses") or {}).values()
            )
        ]
        mathvision_candidates = [d for d in label_overrides if pilot_dialogs[d][0] == MATHVISION]
        training_dialogs, testing_dialogs = choose_pretest_dialogs(
            mathvision_candidates, list(orcamath_labels), orcamath_candidates, args.seed
        )
    print(f"Training dialogues: {training_dialogs}")
    print(f"Testing dialogues: {testing_dialogs}")
    blocks = block_ids(args.block_count)
    subsets = chained_subsets(blocks)

    training_rows, training_gold, missing_explanations = expand_pretest_dialogs(
        training_dialogs, "training", pilot_dialogs, sources, explanations, label_overrides
    )
    testing_rows, testing_gold, _ = expand_pretest_dialogs(
        testing_dialogs, "testing", pilot_dialogs, sources, explanations, label_overrides
    )
    annotation_rows = expand_annotation_dialogs(main_sources, blocks, sources, args.seed)
    control_rows, control_gold, excluded_controls = expand_control_pairs(
        pilot_sources,
        blocks,
        exclude_dialogs=set(training_dialogs) | set(testing_dialogs),
        control_pairs_per_subset=args.control_pairs_per_block,
        sources=sources,
    )

    rows = [*training_rows, *testing_rows, *annotation_rows, *control_rows]
    validate(rows, subsets, training_dialogs, testing_dialogs)
    gold_items = {**training_gold, **testing_gold, **control_gold}
    gold_payload = build_gold_payload(gold_items, rows)
    manifest = build_subset_manifest(rows, blocks, subsets, excluded_controls)

    write_csv(output_csv, rows)
    write_json(manifest_output, manifest)
    write_csv(local_output_csv, rows_with_training_feedback(rows, gold_items))
    write_json(gold_output, gold_payload)

    print(f"Wrote {len(rows)} public rows to {output_csv}")
    print(f"Wrote subset manifest to {manifest_output}")
    print(f"Wrote private local rows with training feedback to {local_output_csv}")
    print(f"Wrote private gold annotations to {gold_output}")
    print(json.dumps(manifest["global_counts"], indent=2, sort_keys=True))
    print(f"Subsets: {manifest['subset_count']}")
    for subset in manifest["subsets"]:
        print(
            f"  {subset['subset_id']} = {' + '.join(subset['blocks'])}: dialogues {subset['annotation_dialogs_by_dataset']}, "
            f"control pairs {subset['control_pairs_by_dataset']}, "
            f"visible items {subset['estimated_visible_instances']}"
        )
    print(f"Excluded control entries: {len(excluded_controls)}")
    if missing_explanations:
        print(f"WARNING: {len(missing_explanations)} training items lack explanations for some dimensions")


if __name__ == "__main__":
    main()