#!/usr/bin/env python3
"""Prepare Potato annotation data from the math annotator Excel workbook.
This script intentionally uses only the Python standard library so it can run
in a fresh environment without openpyxl/pandas.
"""
from __future__ import annotations
import argparse
import csv
import html
import json
import re
import sys
import textwrap
import zipfile
from collections import defaultdict
from pathlib import Path
from xml.etree import ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
DEFAULT_INPUT = ROOT / "annotated_data" / "math_annotator_train&test_sets_simple_2q_train_2q_test.xlsx"
DEFAULT_OUTPUT_DIR = Path(__file__).resolve().parents[1] / "my-annotation-task" / "data"
SHEET_TO_SPLIT = {
"math_annotator_training_set": "train",
"math_annotator_testing_set": "test",
}
DISPLAY_COLUMNS = ["dialog_context", "correct_solution", "tutor_response"]
DIMENSIONS = [
"Content Correctness",
"Learner-State Assessment",
"Issue Localization",
"Disclosure Appropriateness",
"Providing Guidance",
"Coherence",
"Actionability",
"Clarity",
"Conciseness",
"Humanness",
]
VALID_LABELS = {"Yes", "To some extent", "No"}
NS = {
"a": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
}
def column_index(cell_ref: str) -> int:
match = re.match(r"([A-Z]+)", cell_ref or "A")
if not match:
return 0
index = 0
for char in match.group(1):
index = index * 26 + (ord(char) - ord("A") + 1)
return index - 1
def load_shared_strings(archive: zipfile.ZipFile) -> list[str]:
if "xl/sharedStrings.xml" not in archive.namelist():
return []
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
strings: list[str] = []
for string_item in root.findall("a:si", NS):
strings.append("".join(node.text or "" for node in string_item.findall(".//a:t", NS)))
return strings
def get_cell_text(cell: ET.Element, shared_strings: list[str]) -> str:
cell_type = cell.attrib.get("t")
value_node = cell.find("a:v", NS)
if cell_type == "s" and value_node is not None and value_node.text:
return shared_strings[int(value_node.text)]
if cell_type == "inlineStr":
return "".join(node.text or "" for node in cell.findall(".//a:t", NS))
if value_node is not None:
return value_node.text or ""
return ""
def resolve_sheet_path(target: str) -> str:
target = target.lstrip("/")
if target.startswith("xl/"):
return target
return f"xl/{target}"
def read_workbook(path: Path) -> dict[str, list[list[str]]]:
with zipfile.ZipFile(path) as archive:
shared_strings = load_shared_strings(archive)
workbook_root = ET.fromstring(archive.read("xl/workbook.xml"))
rels_root = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
relationship_targets = {
rel.attrib["Id"]: rel.attrib["Target"]
for rel in rels_root
}
sheets: dict[str, list[list[str]]] = {}
for sheet in workbook_root.find("a:sheets", NS):
sheet_name = sheet.attrib["name"]
rel_id = sheet.attrib[f"{{{NS['r']}}}id"]
sheet_path = resolve_sheet_path(relationship_targets[rel_id])
sheet_root = ET.fromstring(archive.read(sheet_path))
rows: list[list[str]] = []
for row in sheet_root.findall(".//a:sheetData/a:row", NS):
values_by_col = {
column_index(cell.attrib.get("r", "A")): get_cell_text(cell, shared_strings)
for cell in row.findall("a:c", NS)
}
if values_by_col:
width = max(values_by_col) + 1
rows.append([values_by_col.get(col, "") for col in range(width)])
else:
rows.append([])
sheets[sheet_name] = rows
return sheets
def normalize_rows(raw_rows: list[list[str]]) -> list[dict[str, str]]:
nonempty_rows = [row for row in raw_rows if any(str(value).strip() for value in row)]
if not nonempty_rows:
return []
header = [str(value).strip() for value in nonempty_rows[0]]
rows: list[dict[str, str]] = []
for raw_row in nonempty_rows[1:]:
padded = raw_row + [""] * (len(header) - len(raw_row))
rows.append({header[index]: str(padded[index]).strip() for index in range(len(header))})
return rows
def slugify(value: str) -> str:
value = value.lower().strip()
value = re.sub(r"[^a-z0-9]+", "_", value)
return value.strip("_") or "item"
def escape_text_node(text: str) -> str:
"""Escape HTML text content without turning quotes into visible entities."""
return html.escape(html.unescape(text), quote=False)
def inline_format(text: str) -> str:
escaped = escape_text_node(text)
escaped = re.sub(r"`([^`]+)`", r"\1", escaped)
escaped = re.sub(r"\*\*([^*]+)\*\*", r"\1", escaped)
escaped = re.sub(
r"(?m)^(Tutor|Student):",
lambda match: f"{match.group(1)}:",
escaped,
)
return escaped
def rich_text(text: str) -> str:
text = (text or "").strip()
if not text:
return "
No content provided.
" parts = re.split(r"(```(?:[a-zA-Z0-9_+-]+)?\n.*?\n```)", text, flags=re.DOTALL) rendered: list[str] = [] for part in parts: if not part: continue fence_match = re.match(r"```(?:[a-zA-Z0-9_+-]+)?\n(.*?)\n```", part, flags=re.DOTALL) if fence_match: code = escape_text_node(fence_match.group(1).strip("\n")) rendered.append(f'{code}')
continue
paragraphs = [paragraph.strip() for paragraph in re.split(r"\n\s*\n", part) if paragraph.strip()]
for paragraph in paragraphs:
paragraph_html = inline_format(paragraph).replace("\n", "{paragraph_html}
") return "\n".join(rendered) def section_html(title: str, body: str, *, extra_class: str = "") -> str: class_name = "potato-text-section" if extra_class: class_name = f"{class_name} {extra_class}" return ( f'