#!/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"(? 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'
\\[{escaped}\\]
' return f'\\({escaped}\\)' 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"{m.group(1)}", escaped) marked = re.sub(r"\*\*(.+?)\*\*", lambda m: f"{m.group(1)}", marked) marked = re.sub(r"(?{m.group(1)}", marked) marked = re.sub(r"(?{m.group(1)}", 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("" + "".join(f"<{tag}>{inline_markup(cell, segments)}" for cell in cells) + "") return '' + "".join(rows) + "
" 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("

" + "
".join(inline_markup(line, segments) for line in paragraph) + "

") 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"
  • {item}
  • " for item in list_items) + f"") 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'
    '
                    f"{html.escape(code.strip(chr(10)), quote=False)}
    " ) 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"{inline_markup(heading.group(2), segments)}") index += 1 continue if RULE_RE.match(line): flush_all() parts.append("
    ") 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] += "
    " + inline_markup(stripped, segments) index += 1 continue flush_list() paragraph.append(stripped) index += 1 flush_all() return '
    ' + "\n".join(parts) + "
    " 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'
    {html.escape(INSTRUCTION_TEXT)} ' f'See ' f"{html.escape(GUIDELINES_LINK_TEXT)}.
    " ) def utterance_html(label: str, body: str, speaker_class: str) -> str: return ( '
    ' f'
    {html.escape(label)}
    ' f"{body}" "
    " ) def image_html(image_url: str) -> str: return ( '
    ' f'' f'Problem image' "" '
    Problem image (click to enlarge)
    ' "
    " ) 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 = ['

    Dialogue

    '] 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 = [ '
    ', '

    Reference solution

    ', rich_html(row["correct_solution"]), "
    ", ] if row["failure_reason"]: side_sections += [ '
    ', '

    Failure reason

    ', rich_html(row["failure_reason"]), "
    ", ] return "\n".join( [ make_instruction_html(), '
    ', '
    ', "\n".join(dialog_parts), "
    ", '
    ', *side_sections, "
    ", "
    ", ] ) 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()