#!/usr/bin/env python3 """Build the Sphregis beta dataset from frozen Ancient Greek treebanks. The build is deliberately source-driven: source repositories are not vendored in the dataset repository. Pass their checkout root with ``--sources``. Every published row records the exact upstream commit used by the build. """ from __future__ import annotations import argparse import hashlib import html import io import json import random import re import subprocess import unicodedata import xml.etree.ElementTree as ET from collections import Counter, defaultdict from dataclasses import dataclass, field from html.parser import HTMLParser from pathlib import Path from typing import Iterable import edlib import pyarrow as pa import pyarrow.parquet as pq try: from scripts.dataset_variants import make_dataset_variants, variant_schema from scripts.metrical_lines import load_public_metrical_lines, public_metrical_line from scripts.text_units import load_text_units from scripts.vendor.conll18_ud_eval import UDError, load_conllu except ModuleNotFoundError: # Direct execution from the scripts directory. from dataset_variants import make_dataset_variants, variant_schema from metrical_lines import load_public_metrical_lines, public_metrical_line from text_units import load_text_units from vendor.conll18_ud_eval import UDError, load_conllu RANDOM_SEED = 776 SAFE_CONLLU_MISC_KEYS = {"NativeRel", "NativeHead", "HeadRepair", "SpaceAfter"} SOURCE_INFO = { "agdt": { "directory": "treebank_data", "url": "https://github.com/PerseusDL/treebank_data", "license": "CC-BY-SA-3.0-US", "annotation": "manual syntax; Morpheus-assisted morphology; normalized in AGDT 2.1", "scheme": "AGDT/ALDT", }, "ud_perseus": { "directory": "perseus", "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-Perseus", "license": "CC-BY-NC-SA-2.5", "annotation": "UD conversion of manually annotated AGDT syntax", "scheme": "Universal Dependencies 2", }, "ud_proiel": { "directory": "proiel", "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-PROIEL", "license": "CC-BY-NC-SA-3.0", "annotation": "UD conversion of manually annotated PROIEL data", "scheme": "Universal Dependencies 2", }, "ud_ptnk": { "directory": "ptnk", "url": "https://github.com/UniversalDependencies/UD_Ancient_Greek-PTNK", "license": "CC-BY-SA-4.0", "annotation": "cross-lingual projection with automatic and manual correction", "scheme": "Universal Dependencies 2", }, "gorman": { "directory": "gorman", "url": "https://github.com/vgorman1/Greek-Dependency-Trees", # The README says NC; the bundled license text omits NC. Use the # conservative interpretation until the maintainer resolves it. "license": "CC-BY-NC-SA-4.0 (conservative; upstream files conflict)", "annotation": "hand annotated, or hand corrected after preparsing", "scheme": "AGDT/Arethusa", }, "pedalion": { "directory": "pedalion", "url": "https://github.com/perseids-publications/pedalion-trees", "license": "CC-BY-SA-4.0", "annotation": "human corrected after automatic preparsing; beta annotations", "scheme": "AGDT/Arethusa", }, "harrington": { "directory": "harrington", "url": "https://github.com/perseids-publications/harrington-trees", "license": "CC-BY-SA-4.0", "annotation": "student annotation edited by J. Matthew Harrington", "scheme": "Harrington/Arethusa", }, "hypotactic": { "directory": "hypotactic", "url": "https://github.com/Urdatorn/hypotactic", "license": "CC-BY-4.0", "annotation": "human metrical annotation by David Chamberlain", "scheme": "Hypotactic scansion HTML", }, } AGDT_WORKS = { "tlg0003.tlg001": ("Thucydides", "Histories, Book 1", "prose"), "tlg0007.tlg004": ("Plutarch", "Lycurgus", "prose"), "tlg0007.tlg015": ("Plutarch", "Alcibiades", "prose"), "tlg0008.tlg001": ("Athenaeus", "Deipnosophists, Books 12–13", "prose"), "tlg0011.tlg001": ("Sophocles", "Trachiniae", "verse"), "tlg0011.tlg002": ("Sophocles", "Antigone", "verse"), "tlg0011.tlg003": ("Sophocles", "Ajax", "verse"), "tlg0011.tlg004": ("Sophocles", "Oedipus Tyrannus", "verse"), "tlg0011.tlg005": ("Sophocles", "Electra", "verse"), "tlg0012.tlg001": ("Homer", "Iliad", "verse"), "tlg0012.tlg002": ("Homer", "Odyssey", "verse"), "tlg0013.tlg002": ("Pseudo-Homer", "Hymn to Demeter", "verse"), "tlg0016.tlg001": ("Herodotus", "Histories, Book 1", "prose"), "tlg0020.tlg001": ("Hesiod", "Theogony", "verse"), "tlg0020.tlg002": ("Hesiod", "Works and Days", "verse"), "tlg0020.tlg003": ("Hesiod", "Shield of Heracles", "verse"), "tlg0059.tlg001": ("Plato", "Euthyphro", "prose"), "tlg0060.tlg001": ("Diodorus Siculus", "Library, Book 11", "prose"), "tlg0085.tlg001": ("Aeschylus", "Suppliants", "verse"), "tlg0085.tlg002": ("Aeschylus", "Persians", "verse"), "tlg0085.tlg003": ("Aeschylus", "Prometheus Bound", "verse"), "tlg0085.tlg004": ("Aeschylus", "Seven Against Thebes", "verse"), "tlg0085.tlg005": ("Aeschylus", "Agamemnon", "verse"), "tlg0085.tlg006": ("Aeschylus", "Libation Bearers", "verse"), "tlg0085.tlg007": ("Aeschylus", "Eumenides", "verse"), "tlg0096.tlg002": ("Aesop", "Fables 1–50", "prose"), "tlg0540.tlg001": ("Lysias", "On the Murder of Eratosthenes", "prose"), "tlg0540.tlg014": ("Lysias", "Against Alcibiades 1", "prose"), "tlg0540.tlg015": ("Lysias", "Against Alcibiades 2", "prose"), "tlg0540.tlg023": ("Lysias", "Against Pancleon", "prose"), "tlg0543.tlg001": ("Polybius", "Histories, Book 1", "prose"), "tlg0548.tlg001": ("Pseudo-Apollodorus", "Library 1.1.1–1.4.1", "prose"), } # Hypotactic file stems aligned to human treebanks. Booked works expand below. VERSE_LINKS = { "tlg0012.tlg001": {"files": [f"iliad{i}" for i in range(1, 25)]}, "tlg0012.tlg002": {"files": [f"odyssey{i}" for i in range(1, 25)]}, "tlg0013.tlg002": {"files": ["HHDemeter"]}, "tlg0020.tlg001": {"files": ["theogony"]}, "tlg0020.tlg002": {"files": ["worksanddays"]}, "tlg0020.tlg003": {"files": ["scutum"]}, "tlg0085.tlg002": {"files": ["persians"]}, "tlg0085.tlg003": {"files": ["prometheus"]}, "tlg0085.tlg004": {"files": ["seven"]}, "pedalion:batracho.xml": {"files": ["batmumach"]}, "pedalion:semonides.xml": {"files": ["semonides"]}, "pedalion:theoc.xml": {"files": ["theoc1", "theoc2", "theoc3", "theoc4"]}, } PEDALION_VERSE = { "achar.xml", "thesmo.xml", "euripides_medea.xml", "ez.xml", "batracho.xml", "menander_dyskolos.xml", "sappho.xml", "semonides.xml", "theoc.xml", "mimn.xml", } PEDALION_EXCLUDE = { "papyri.xml", "example-sentences.xml", "external_examplesentences.xml", "chilia-sentences.xml", } GORMAN_AUTHOR_PATTERNS = [ (r"^Aeschines", "Aeschines"), (r"^Andocides", "Andocides"), (r"^[Aa]ntiphon", "Antiphon"), (r"^Appian", "Appian"), (r"^Aristotle", "Aristotle"), (r"^[Dd]em", "Demosthenes"), (r"^Isaeus", "Isaeus"), (r"^Isocrates", "Isocrates"), (r"^[Ll]ysias", "Lysias"), (r"^[Pp]lato", "Plato"), (r"^[Pp]lut", "Plutarch"), (r"^[Pp]olybius", "Polybius"), (r"^[Xx]en", "Xenophon"), (r"^[Aa]then", "Athenaeus"), (r"^[Dd]iod", "Diodorus Siculus"), (r"^[Dd]ion hal", "Dionysius of Halicarnassus"), (r"^[Hh]dt", "Herodotus"), (r"^[Jj]osephus", "Josephus"), (r"^[Tt]huc", "Thucydides"), (r"^ps xen", "Pseudo-Xenophon"), ] NT_BOOKS = { "MATT": ("Matthew (traditional)", "Gospel of Matthew"), "MARK": ("Mark (traditional)", "Gospel of Mark"), "LUKE": ("Luke (traditional)", "Gospel of Luke"), "ACTS": ("Luke (traditional)", "Acts"), "JOHN": ("John (traditional)", "Gospel of John"), "ROM": ("Paul (traditional)", "Romans"), "GAL": ("Paul", "Galatians"), "EPH": ("Paul (traditional)", "Ephesians"), "PHIL": ("Paul", "Philippians"), "COL": ("Paul (traditional)", "Colossians"), "TIT": ("Paul (traditional)", "Titus"), "PHILEM": ("Paul", "Philemon"), "HEB": ("Anonymous", "Hebrews"), "JAS": ("James (traditional)", "James"), "JUDE": ("Jude (traditional)", "Jude"), "REV": ("John of Patmos", "Revelation"), } # Sphregis is intended to provide conservative ground truth for authorship # attribution. Received corpora with anonymous, pseudonymous, mediated, or # substantially disputed authorship are kept out of the benchmark rather than # being presented as known-author training data. EXCLUDED_AUTHOR_WORKS = { ("Aeschylus", "Prometheus Bound"): "disputed_aeschylean_authorship", ("Aesop", "Fables"): "traditional_aesopic_collection", ("Aesop", "Fables 1–50"): "traditional_aesopic_collection", ("Antiphon", "antiphon 1 bu2"): "disputed_antiphontic_authorship", ("Antiphon", "antiphon 2 bu2"): "disputed_antiphontic_authorship", ("Chion", "Letters"): "pseudonymous_epistolary_novel", ("Epictetus", "Dissertationes ab Arriano digestae"): "mediated_by_arrian", ("First Council of Nicea", "Nicene Creed 325 CE"): "corporate_authorship", ("Hesiod", "Shield of Heracles"): "pseudo_hesiodic", ("Isocrates", "Letters"): "disputed_isocratean_letters", ("John of Patmos", "Revelation"): "author_identity_not_secure", ("Plato", "Cleitophon"): "disputed_platonic_authorship", ("Xenophon", "xen cyr 8.8 bu1"): "disputed_cyropaedia_epilogue", } EXCLUDED_WORK_IDS = { "tlg0028.tlg001": "disputed_antiphontic_authorship", "tlg0028.tlg002": "disputed_antiphontic_authorship", "tlg0540.tlg014": "disputed_lysian_authorship", "tlg0540.tlg015": "disputed_lysian_authorship", } EXCLUDED_DEMOSTHENIC_SPEECHS = {7, 17, 46, 47, 49, 50, 52, 53, 59} # Only these portions of Seven Against Thebes are excluded. Removing complete # alignment components below preserves exhaustive sentence/line coverage. DISPUTED_VERSE_PASSAGES = { ("Aeschylus", "Seven Against Thebes"): ((861, 874), (1005, 1078)), } POS_MAP = { "n": "NOUN", "v": "VERB", "a": "ADJ", "d": "ADV", "c": "SCONJ", "r": "ADP", "p": "PRON", "l": "DET", "g": "PART", "b": "CCONJ", "m": "NUM", "i": "INTJ", "u": "PUNCT", "e": "X", "x": "X", "-": "X", "t": "VERB", "q": "ADV", } UPOS_TO_AGDT_POS = { "ADJ": "a", "ADP": "r", "ADV": "d", "AUX": "v", "CCONJ": "b", "DET": "l", "INTJ": "i", "NOUN": "n", "NUM": "m", "PART": "g", "PRON": "p", "PROPN": "n", "PUNCT": "u", "SCONJ": "c", "SYM": "x", "VERB": "v", "X": "x", } UD_TO_AGDT_FEATURE = { "Person": {"1": "1", "2": "2", "3": "3"}, "Number": {"Sing": "s", "Plur": "p", "Dual": "d"}, "Mood": {"Ind": "i", "Sub": "s", "Opt": "o", "Imp": "m"}, "Voice": {"Act": "a", "Mid": "m", "Pass": "p"}, "Gender": {"Masc": "m", "Fem": "f", "Neut": "n", "Com": "c"}, "Case": {"Nom": "n", "Gen": "g", "Dat": "d", "Acc": "a", "Voc": "v", "Loc": "l"}, "Degree": {"Cmp": "c", "Sup": "s", "Pos": "p"}, } UD_V2_RELATIONS = { "acl", "advcl", "advmod", "amod", "appos", "aux", "case", "cc", "ccomp", "clf", "compound", "conj", "cop", "csubj", "dep", "det", "discourse", "dislocated", "expl", "fixed", "flat", "goeswith", "iobj", "list", "mark", "nmod", "nsubj", "nummod", "obj", "obl", "orphan", "parataxis", "punct", "reparandum", "root", "vocative", "xcomp", } FEATURE_MAPS = [ ("Person", {"1": "1", "2": "2", "3": "3"}), ("Number", {"s": "Sing", "p": "Plur", "d": "Dual"}), ("Tense", {"p": "Pres", "i": "Past", "r": "Past", "l": "Past", "t": "Past", "f": "Fut", "a": "Past"}), ("Mood", {"i": "Ind", "s": "Sub", "o": "Opt", "m": "Imp", "n": "Inf", "p": "Part", "g": "Ger"}), ("Voice", {"a": "Act", "m": "Mid", "p": "Pass", "e": "Mid"}), ("Gender", {"m": "Masc", "f": "Fem", "n": "Neut", "c": "Com"}), ("Case", {"n": "Nom", "g": "Gen", "d": "Dat", "a": "Acc", "v": "Voc", "l": "Loc"}), ("Degree", {"c": "Cmp", "s": "Sup", "p": "Pos"}), ] def canonical_xpos(upos: str, xpos: str, feats: str) -> str: """Return one consistent nine-position Ancient Greek XPOS tag. Valid AGDT/Perseus positional tags retain their more precise native tense and mood distinctions. Other source-specific XPOS schemes (notably the two-character PROIEL tags) are converted from the universal UPOS and FEATS columns. Missing distinctions are represented by ``-`` rather than by interpreting characters from an incompatible tag system. """ xpos = xpos or "_" if re.fullmatch(r"[a-z][a-z0-9-]{0,9}", xpos): return xpos.ljust(9, "-")[:9] tag = ["-"] * 9 tag[0] = UPOS_TO_AGDT_POS.get(upos, "x") parsed = {} if feats and feats != "_": for item in feats.split("|"): if "=" in item: name, value = item.split("=", 1) parsed[name] = value.split(",", 1)[0] positions = { "Person": 1, "Number": 2, "Tense": 3, "Mood": 4, "Voice": 5, "Gender": 6, "Case": 7, "Degree": 8, } for name, position in positions.items(): value = parsed.get(name) if name == "Tense": if value == "Pres": tag[position] = "p" elif value == "Fut": tag[position] = "f" elif value == "Past": tag[position] = "i" if parsed.get("Aspect") == "Imp" else "a" elif value in UD_TO_AGDT_FEATURE.get(name, {}): tag[position] = UD_TO_AGDT_FEATURE[name][value] verb_form = parsed.get("VerbForm") if verb_form == "Inf": tag[4] = "n" elif verb_form == "Part": tag[4] = "p" return "".join(tag) def canonicalize_conllu_xpos(conllu: str) -> str: """Normalize XPOS and retain only the non-identifying text comment.""" lines = [] for line in conllu.splitlines(): if line.startswith("#") and not line.startswith("# text = "): continue if not line or line.startswith("# text = "): lines.append(line) continue columns = line.split("\t") if len(columns) == 10: misc = [ item for item in columns[9].split("|") if item != "_" and item.split("=", 1)[0] in SAFE_CONLLU_MISC_KEYS ] columns[9] = "|".join(misc) or "_" if re.fullmatch(r"\d+", columns[0]): columns[4] = canonical_xpos(columns[3], columns[4], columns[5]) line = "\t".join(columns) lines.append(line) return "\n".join(lines).rstrip("\n") + "\n\n" def canonical_native_deprel(relation: str, child_upos: str, head: int) -> str: """Conservatively map an AGDT/Arethusa relation to UD v2. The native value remains losslessly available in MISC as ``NativeRel``. Coordination/apposition suffixes and obvious grammatical functions are mapped explicitly; opaque or annotation-specific categories fall back to the universal ``dep`` relation rather than being presented as UD subtypes. """ if head == 0: return "root" if child_upos == "PUNCT": return "punct" cleaned = re.sub(r"[^A-Z0-9]+", "_", (relation or "").upper()).strip("_") parts = [part for part in cleaned.split("_") if part] if "CO" in parts or cleaned.endswith("CO"): return "conj" if "APOS" in parts or cleaned == "APOS": return "appos" if cleaned.startswith(("SBJ", "N_SUBJ", "A_SUBJ")): return "csubj" if child_upos in {"VERB", "AUX"} else "nsubj" if cleaned.startswith(("OBJ", "A_DO", "A_INTOBJ", "G_OBJEC", "NOM_")): return "ccomp" if child_upos in {"VERB", "AUX"} else "obj" if cleaned.startswith("ATR"): return { "ADJ": "amod", "DET": "det", "NUM": "nummod", "VERB": "acl", "AUX": "acl", "ADV": "advmod", }.get(child_upos, "nmod") if cleaned.startswith(("ADV", "CP_")): if child_upos in {"VERB", "AUX"}: return "advcl" if child_upos in {"NOUN", "PROPN", "PRON", "NUM"}: return "obl" return "advmod" if cleaned.startswith(("G_", "D_", "A_ORIENT", "A_EXTENT", "A_RESPECT")): return "obl" if cleaned.startswith(("OCOMP", "INF_COMP", "INF_EXPL")): return "ccomp" if child_upos in {"VERB", "AUX"} else "xcomp" if cleaned.startswith(("PNOM", "PRED", "N_PRED", "A_PRED", "D_PRED", "ATV")): return "xcomp" if cleaned.startswith("ADJ_RC"): return "acl" if cleaned.startswith("AUXP"): return "case" if cleaned.startswith("AUXC"): return "cc" if child_upos == "CCONJ" else "mark" if cleaned.startswith("AUXY") or cleaned in {"INTRJ", "SP_SUPPL"}: return "discourse" if cleaned.startswith("AUXZ"): return "advmod" if cleaned.startswith("AUXV"): return "aux" if cleaned.startswith(("COORD", "CO")): return "conj" if cleaned.startswith(("EXD", "XSEG")): return "dislocated" if cleaned.startswith("PARENTH"): return "parataxis" if cleaned.startswith(("MWE", "RELATION_NOT_RECOGNIZED_MWE")): return "fixed" if cleaned.startswith("GAP"): return "orphan" if cleaned.startswith("V_VOC"): return "vocative" return "dep" @dataclass class Sentence: source: str source_file: str source_sentence_id: str author: str work: str work_id: str text: str conllu: str cts_urn: str = "" passage: str = "" genre: str = "prose" native_cites: list[str] = field(default_factory=list) priority: int = 50 source_records: list[dict] = field(default_factory=list) @property def normalized(self) -> str: return normalize(self.text) def normalize(text: str) -> str: text = text.lower().replace("ς", "σ") text = "".join( char for char in unicodedata.normalize("NFD", text) if unicodedata.category(char) != "Mn" ) return "".join(char for char in text if char.isalpha()) def slug(text: str) -> str: value = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower() value = re.sub(r"[^a-z0-9]+", "-", value).strip("-") return value or "unknown" def canonical_author(author: str) -> str: return { "Aesopus": "Aesop", "Anon.": "Anonymous (Septuagint)", "Lucianus": "Lucian", "Pseudo-Lucianus": "Pseudo-Lucian", "(Pseudo-Homer)": "Pseudo-Homer", "Ezechiël": "Ezechiel", }.get(author.strip(), author.strip() or "Unknown") def demosthenic_speech_number(work: str) -> int | None: match = re.match(r"^dem(?:osthenes)?[ _]+(\d+)", work, re.I) return int(match.group(1)) if match else None def authorship_decision(sentence: Sentence) -> tuple[str | None, str | None]: """Return a curated author and, if excluded, a machine-readable reason.""" author = canonical_author(sentence.author) work = sentence.work.strip() # Romans is part of the normally undisputed Pauline core; its upstream # "traditional" qualifier is therefore a metadata inconsistency. if author == "Paul (traditional)" and work == "Romans": author = "Paul" # The Homeric epics remain useful corpus labels, but not claims about one # biographical author shared by both poems. if author == "Homer" and work in {"Iliad", "Odyssey"}: author = f"Homeric-{work}" lowered_author = author.casefold() if lowered_author.startswith("unknown"): return None, "unknown_author" if lowered_author.startswith("anonymous"): return None, "anonymous_author" if lowered_author.startswith("pseudo-") or lowered_author.startswith("(pseudo-"): return None, "pseudonymous_author_label" if "(traditional)" in lowered_author: return None, "traditional_author_label" if re.search(r"\bfragments?\b", work, re.I): return None, "fragmentary_work_label" reason = EXCLUDED_AUTHOR_WORKS.get((author, work)) if reason: return None, reason reason = EXCLUDED_WORK_IDS.get(sentence.work_id) if reason: return None, reason if author == "Demosthenes" and demosthenic_speech_number(work) in EXCLUDED_DEMOSTHENIC_SPEECHS: return None, "pseudo_or_disputed_demosthenic_speech" return author, None def curate_sentences(rows: list[Sentence]) -> tuple[list[Sentence], dict]: retained = [] excluded = Counter() excluded_works = Counter() relabeled = Counter() for sentence in rows: original_author = sentence.author author, reason = authorship_decision(sentence) if reason: excluded[reason] += 1 excluded_works[(original_author, sentence.work, sentence.work_id)] += 1 continue assert author is not None if author != original_author: relabeled[(original_author, author, sentence.work)] += 1 sentence.author = author retained.append(sentence) return retained, { "input_rows": len(rows), "retained_rows": len(retained), "excluded_rows": len(rows) - len(retained), "excluded_by_reason": dict(sorted(excluded.items())), "excluded_works": [ {"author": author, "work": work, "work_id": work_id, "rows": count} for (author, work, work_id), count in sorted(excluded_works.items()) ], "relabeled": [ {"from": old, "to": new, "work": work, "rows": count} for (old, new, work), count in sorted(relabeled.items()) ], } def stable_id(*parts: str, length: int = 20) -> str: return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:length] def git_revision(path: Path) -> str: return subprocess.check_output(["git", "-C", str(path), "rev-parse", "HEAD"], text=True).strip() def source_record(source: str, revisions: dict[str, str], source_file: str, sentence_id: str) -> dict: info = SOURCE_INFO[source] return { "source": source, "source_file": source_file, "source_sentence_id": sentence_id, "url": info["url"], "revision": revisions[source], "license": info["license"], "annotation_provenance": info["annotation"], "syntax_scheme": info["scheme"], } def infer_cts(value: str) -> str: match = re.search(r"urn:cts:[^\s]+", value or "") if not match: return "" return match.group(0).removesuffix(".tb") def cts_key(value: str) -> str: match = re.search(r"(tlg\d+\.tlg\d+)", value) return match.group(1) if match else "" def morph_features(postag: str) -> str: tag = (postag or "---------").ljust(9, "-")[:9] values = [] for index, (name, mapping) in enumerate(FEATURE_MAPS, 1): if tag[index] in mapping: values.append(f"{name}={mapping[tag[index]]}") return "|".join(sorted(values)) or "_" def misc_field(values: dict[str, str]) -> str: fields = [] for key, value in values.items(): if value: clean = str(value).replace("|", ",").replace(" ", "_") fields.append(f"{key}={clean}") return "|".join(fields) or "_" def smart_text(forms: Iterable[str]) -> str: result = "" no_space_before = set(",.;··:!?;)]}»”") no_space_after = set("([{«“") for form in forms: if not result: result = form elif form and form[0] in no_space_before: result += form elif result[-1] in no_space_after: result += form else: result += " " + form return result def xml_sentence_to_conllu(sentence: ET.Element, metadata: dict[str, str]) -> tuple[str, str, list[str]]: words = list(sentence.findall("word")) real = [ word for word in words if not word.get("artificial") and (word.get("form") or "").strip() not in {"", "[0]", "_"} ] id_map = {word.get("id", ""): index for index, word in enumerate(real, 1)} by_old_id = {word.get("id", ""): word for word in words} def resolved_head(word: ET.Element) -> int: head = word.get("head", "0") seen = set() while head not in id_map and head not in {"", "0", None} and head not in seen: seen.add(head) parent = by_old_id.get(head) head = parent.get("head", "0") if parent is not None else "0" return id_map.get(head, 0) forms = [word.get("form", "_") for word in real] text = smart_text(forms) lines = [ f"# text = {text}", ] initial_heads = [resolved_head(word) for word in real] root_candidates = [ index for index, (word, head) in enumerate(zip(real, initial_heads), 1) if head == 0 and not word.get("postag", "").startswith("u") ] primary_root = root_candidates[0] if root_candidates else 1 final_heads = list(initial_heads) for index, head in enumerate(final_heads, 1): if index == primary_root: final_heads[index - 1] = 0 elif head in {0, index}: final_heads[index - 1] = primary_root # A few beta trees contain cycles. Break each cycle at one node while # retaining all other original heads; record provenance still points back # to the source tree for audit. for token_id in range(1, len(final_heads) + 1): trail = [] cursor = token_id while cursor: if cursor in trail: cycle = trail[trail.index(cursor):] break_id = min(cycle) final_heads[break_id - 1] = 0 if break_id == primary_root else primary_root break trail.append(cursor) cursor = final_heads[cursor - 1] cites = [] for new_id, word in enumerate(real, 1): postag = word.get("postag", "---------") head = final_heads[new_id - 1] relation = word.get("relation", "dep") upos = POS_MAP.get(postag[:1].lower(), "X") dep = canonical_native_deprel(relation, upos, head) cite = word.get("cite", "") or word.get("ref", "") if cite: cites.append(cite) row = [ str(new_id), word.get("form", "_"), word.get("lemma", "_"), upos, canonical_xpos(upos, postag, morph_features(postag)), morph_features(postag), str(head), dep, "_", misc_field({ "NativeRel": relation, "NativeHead": word.get("head", ""), "HeadRepair": "Yes" if head != initial_heads[new_id - 1] else "", }), ] lines.append("\t".join(row)) return text, "\n".join(lines) + "\n\n", cites def parse_agdt(root: Path, revisions: dict[str, str]) -> tuple[list[Sentence], list[Sentence]]: prose, verse = [], [] text_root = root / "v2.1" / "Greek" / "texts" for path in sorted(text_root.glob("*.xml")): tree = ET.parse(path) xml_root = tree.getroot() key = cts_key(xml_root.get("cts", "") or path.name) if key not in AGDT_WORKS: continue author, work, genre = AGDT_WORKS[key] cts = infer_cts(xml_root.get("cts", "")) or f"urn:cts:greekLit:{key}" for index, sent in enumerate(xml_root.iter("sentence"), 1): sid = sent.get("id", str(index)) passage = sent.get("subdoc", "") text, conllu, cites = xml_sentence_to_conllu(sent, { "sent_id": f"agdt:{key}:{sid}", "source": path.name, "cts": cts, "passage": passage, }) if not normalize(text): continue row = Sentence( source="agdt", source_file=path.name, source_sentence_id=sid, author=author, work=work, work_id=key, text=text, conllu=conllu, cts_urn=cts, passage=passage, genre=genre, native_cites=cites, priority=10, ) row.source_records = [source_record("agdt", revisions, path.name, sid)] (verse if genre == "verse" else prose).append(row) return prose, verse def conllu_blocks(path: Path) -> Iterable[dict]: for raw in path.read_text(encoding="utf8").strip().split("\n\n"): comments = {} token_rows = [] for line in raw.splitlines(): if line.startswith("# ") and " = " in line: key, value = line[2:].split(" = ", 1) comments[key] = value elif line and not line.startswith("#"): fields = line.split("\t") if len(fields) == 10: token_rows.append(fields) if token_rows: yield {"comments": comments, "tokens": token_rows, "conllu": raw + "\n"} def ud_identity(source: str, block: dict) -> tuple[str, str, str, str, str]: comments, tokens = block["comments"], block["tokens"] sent_id = comments.get("sent_id", "") if source == "ud_perseus": doc = sent_id.split("@", 1)[0] key = cts_key(doc) author, work, genre = AGDT_WORKS.get(key, ("Unknown", doc, "prose")) return author, work, key or doc, genre, infer_cts(doc) refs = [row[9] for row in tokens] if source == "ud_ptnk": joined = "|".join(refs) book = "Ruth" if "Septuagint-Ruth" in joined else "Genesis" return "Anonymous (Septuagint)", book, f"septuagint-{book.lower()}", "prose", "" # PROIEL: Herodotus refs are numeric; New Testament refs carry a book prefix. for misc in refs: match = re.search(r"(?:^|\|)Ref=([A-Z]+)_", misc) if match: code = match.group(1) author, work = NT_BOOKS.get(code, (f"Unknown ({code})", code)) return author, work, f"proiel-{code.lower()}", "prose", "" return "Herodotus", "Histories (PROIEL selections)", "tlg0016.tlg001", "prose", "urn:cts:greekLit:tlg0016.tlg001" def parse_ud(source: str, root: Path, revisions: dict[str, str]) -> tuple[list[Sentence], list[Sentence]]: prose, verse = [], [] for path in sorted(root.glob("*.conllu")): for block in conllu_blocks(path): comments = block["comments"] author, work, work_id, genre, cts = ud_identity(source, block) sid = comments.get("sent_id", stable_id(block["conllu"])) text = comments.get("text") or smart_text( row[1] for row in block["tokens"] if re.fullmatch(r"\d+", row[0]) ) if not normalize(text): continue cites = [] for token in block["tokens"]: match = re.search(r"(?:^|\|)Ref=([^|]+)", token[9]) if match: cites.append(match.group(1)) row = Sentence( source=source, source_file=path.name, source_sentence_id=sid, author=author, work=work, work_id=work_id, text=text, conllu=canonicalize_conllu_xpos(block["conllu"]), cts_urn=cts, passage=comments.get("source", ""), genre=genre, native_cites=cites, priority=0, ) row.source_records = [source_record(source, revisions, path.name, sid)] (verse if genre == "verse" else prose).append(row) return prose, verse def gorman_author(filename: str) -> str: for pattern, author in GORMAN_AUTHOR_PATTERNS: if re.search(pattern, filename, re.I if pattern.startswith("^") else 0): return author return "Unknown" def parse_native_collection( source: str, files: Iterable[Path], revisions: dict[str, str], metadata: dict[str, tuple[str, str]] | None = None, verse_files: set[str] | None = None, ) -> tuple[list[Sentence], list[Sentence]]: prose, verse = [], [] metadata = metadata or {} verse_files = verse_files or set() for path in sorted(files): try: tree = ET.parse(path) except ET.ParseError: continue xml_root = tree.getroot() if xml_root.get("{http://www.w3.org/XML/1998/namespace}lang") == "lat": continue first = next(xml_root.iter("sentence"), None) if first is None: continue if source == "gorman": author, work = gorman_author(path.name), path.stem else: author, work = metadata.get(path.name, (first.get("Author", "") or "Unknown", path.stem)) author = canonical_author(author) genre = "verse" if path.name in verse_files else "prose" doc = first.get("document_id", "") cts = infer_cts(doc) work_id = cts_key(doc) or f"{source}:{slug(author)}:{slug(work)}" for index, sent in enumerate(xml_root.iter("sentence"), 1): sid = sent.get("id", str(index)) passage = sent.get("subdoc", "") text, conllu, cites = xml_sentence_to_conllu(sent, { "sent_id": f"{source}:{slug(path.stem)}:{sid}", "source": path.name, "cts": cts, "passage": passage, }) if not normalize(text): continue row = Sentence( source=source, source_file=path.name, source_sentence_id=sid, author=author, work=work, work_id=work_id, text=text, conllu=conllu, cts_urn=cts, passage=passage, genre=genre, native_cites=cites, priority={"gorman": 5, "harrington": 15, "pedalion": 20}.get(source, 20), ) row.source_records = [source_record(source, revisions, path.name, sid)] (verse if genre == "verse" else prose).append(row) return prose, verse def publication_metadata(config_path: Path) -> dict[str, tuple[str, str]]: config = json.loads(config_path.read_text()) result = {} def visit(value): if isinstance(value, dict): if "author" in value and "work" in value: for section in value.get("sections", []): xml = section.get("xml", "") if xml: result[Path(xml).name] = (value["author"], value["work"]) for child in value.values(): visit(child) elif isinstance(value, list): for child in value: visit(child) visit(config) return result class HypotacticParser(HTMLParser): def __init__(self, stem: str): super().__init__(convert_charrefs=True) self.stem = stem self.container = {} self.poem = {} self.poem_depth = None self.poem_counter = 0 self.depth = 0 self.line_depth = None self.line = None self.word_depth = None self.word_text = [] self.syll_depth = None self.syllable = None self.lines = [] def handle_starttag(self, tag, attrs): self.depth += 1 attrs = dict(attrs) classes = set(attrs.get("class", "").split()) if tag == "div" and self.line is None and "line" not in classes: for key in ("data-author", "data-work", "data-book", "data-metre"): if key in attrs and key not in self.container: self.container[key] = attrs[key] if tag == "div" and "poem" in classes: self.poem_counter += 1 book = attrs.get("data-book", "") poem_number = attrs.get("data-number", "") if not any(char.isdigit() for char in book): book = poem_number or book self.poem_depth = self.depth self.poem = { "data-author": attrs.get("data-author", self.container.get("data-author", "")), "data-work": attrs.get("data-work", self.container.get("data-work", "")), "data-book": book, "data-metre": attrs.get("data-metre", self.container.get("data-metre", "")), "sequence": str(self.poem_counter), } if tag == "div" and "line" in classes: self.line_depth = self.depth self.line = { "number": attrs.get("data-number", ""), "metre": attrs.get("data-metre", self.poem.get("data-metre", self.container.get("data-metre", ""))), "speaker": attrs.get("data-speaker", ""), "words": [], "syllables": [], } elif self.line is not None and tag == "span" and "word" in classes: self.word_depth = self.depth self.word_text = [] if self.line is not None and tag == "span" and "syll" in classes: quantity = "long" if "long" in classes else "short" if "short" in classes else "anceps" if "anceps" in classes else "unknown" self.syll_depth = self.depth self.syllable = { "text": "", "quantity": quantity, "features": sorted(classes - {"syll", "long", "short", "anceps"}), } def handle_data(self, data): if self.word_depth is not None: self.word_text.append(data) if self.syllable is not None: self.syllable["text"] += data def handle_endtag(self, tag): if self.syll_depth == self.depth and self.syllable is not None: self.line["syllables"].append(self.syllable) self.syllable = None self.syll_depth = None if self.word_depth == self.depth and tag == "span": word = "".join(self.word_text).strip() if word: self.line["words"].append(word) self.word_depth = None self.word_text = [] if self.line_depth == self.depth and tag == "div": self.line["text"] = " ".join(self.line.pop("words")) symbols = {"long": "–", "short": "⏑", "anceps": "×", "unknown": "?"} self.line["scansion"] = "".join(symbols[s["quantity"]] for s in self.line["syllables"]) self.line["hypotactic_file"] = self.stem + ".html" self.line.update({ "hypotactic_author": self.poem.get("data-author", self.container.get("data-author", "")), "hypotactic_work": self.poem.get("data-work", self.container.get("data-work", "")), "book": self.poem.get("data-book", self.container.get("data-book", "")), "poem_sequence": self.poem.get("sequence", "1"), }) if self.line["text"] and self.line["number"]: self.lines.append(self.line) self.line = None self.line_depth = None if self.poem_depth == self.depth and tag == "div": self.poem = {} self.poem_depth = None self.depth -= 1 def parse_hypotactic_file(path: Path) -> list[dict]: parser = HypotacticParser(path.stem) parser.feed(path.read_text(encoding="utf8")) # Older files do not carry book metadata; recover it from their stem. book_match = re.match(r"(?:iliad|odyssey|dionysiaca|qsmyrnaeus)(\d+)$", path.stem) for line in parser.lines: if not line["book"] and book_match: line["book"] = book_match.group(1) line["normalized"] = normalize(line["text"]) return parser.lines def load_hypotactic(root: Path) -> dict[str, list[dict]]: html_root = root / "hypotactic_htmls_greek" needed = sorted({stem for link in VERSE_LINKS.values() for stem in link["files"]}) return {stem: parse_hypotactic_file(html_root / f"{stem}.html") for stem in needed} def verse_sentence_order_key(sentence: Sentence) -> tuple: references = [] for cite in sentence.native_cites: match = re.search(r":(\d+)(?:\.(\d+))?$", cite) if match: references.append((int(match.group(1)), int(match.group(2) or 0))) if references: return 0, min(references) numbers = tuple(int(value) for value in re.findall(r"\d+", sentence.source_sentence_id)) return 1, numbers or (10**9,) def cumulative_boundaries(items: list, text_key) -> list[int]: boundaries = [0] for item in items: boundaries.append(boundaries[-1] + len(text_key(item))) return boundaries def exact_alignment_components( sentences: list[Sentence], lines: list[dict], ) -> tuple[list[tuple[int, int, int, int]], dict]: sentence_stream = "".join(sentence.normalized for sentence in sentences) line_stream = "".join(line["normalized"] for line in lines) sentence_boundaries = cumulative_boundaries(sentences, lambda item: item.normalized) line_boundaries = cumulative_boundaries(lines, lambda item: item["normalized"]) sentence_at = {position: index for index, position in enumerate(sentence_boundaries)} line_at = {position: index for index, position in enumerate(line_boundaries)} result = edlib.align(sentence_stream, line_stream, mode="HW", task="path") if result["cigar"] is None or not result["locations"]: return [], {"edit_distance": result["editDistance"]} sentence_position = 0 line_position = result["locations"][0][0] last_joint_boundary = ( (sentence_position, line_position) if sentence_position in sentence_at and line_position in line_at else None ) exact_since_joint = True components = [] for length, operation in re.findall(r"(\d+)([=XID])", result["cigar"]): for _ in range(int(length)): if operation in "=X": sentence_position += 1 line_position += 1 elif operation == "I": sentence_position += 1 else: # D advances only the Hypotactic stream in edlib's CIGAR. line_position += 1 if operation != "=": exact_since_joint = False if sentence_position in sentence_at and line_position in line_at: if exact_since_joint and last_joint_boundary is not None: previous_sentence, previous_line = last_joint_boundary if sentence_position > previous_sentence and line_position > previous_line: component = ( sentence_at[previous_sentence], sentence_at[sentence_position], line_at[previous_line], line_at[line_position], ) sentence_text = "".join( sentence.normalized for sentence in sentences[component[0]:component[1]] ) line_text = "".join( line["normalized"] for line in lines[component[2]:component[3]] ) assert sentence_text == line_text components.append(component) last_joint_boundary = (sentence_position, line_position) exact_since_joint = True return components, { "edit_distance": result["editDistance"], "target_start": result["locations"][0][0], "target_end": result["locations"][0][1], "normalized_sentence_chars": len(sentence_stream), "normalized_line_chars": len(line_stream), } def unique_source_records(records: Iterable[dict]) -> list[dict]: output = [] seen = set() for record in records: key = (record["source"], record["source_file"], record["source_sentence_id"]) if key not in seen: seen.add(key) output.append(record) return output def hypotactic_source_records(lines: list[dict], revisions: dict[str, str]) -> list[dict]: by_file = defaultdict(list) for line in lines: by_file[line["hypotactic_file"]].append(line) return [ source_record( "hypotactic", revisions, source_file, ",".join( f"{line['poem_sequence']}:{line['book']}:{line['number']}" for line in file_lines ), ) for source_file, file_lines in sorted(by_file.items()) ] def line_identity(work_id: str, line: dict) -> tuple[str, ...]: return ( work_id, line["hypotactic_file"], line["poem_sequence"], line["book"], line["number"], ) def align_verse_blocks( verse_sentences: list[Sentence], hyp: dict[str, list[dict]], revisions: dict[str, str], ) -> tuple[list[dict], list[dict], dict]: sentence_rows, metre_rows = [], [] alignment_stats = {} grouped_sentences = defaultdict(list) for sentence in verse_sentences: link_key = f"pedalion:{sentence.source_file}" if sentence.source == "pedalion" else sentence.work_id if link_key in VERSE_LINKS: grouped_sentences[link_key].append(sentence) for link_key, link in VERSE_LINKS.items(): sentences = sorted(grouped_sentences[link_key], key=verse_sentence_order_key) lines = [line for stem in link["files"] for line in hyp[stem]] if not sentences: alignment_stats[link_key] = { "sentences": 0, "lines": len(lines), "alignment_components": 0, "matched_sentences": 0, "matched_lines": 0, "excluded_sentences": 0, "excluded_lines": len(lines), "cross_boundary_sentences": 0, "cross_boundary_lines": 0, "excluded_by_authorship_curation": True, } continue components, stats = exact_alignment_components(sentences, lines) matched_sentence_indices = set() matched_line_indices = set() cross_boundary_lines = 0 cross_boundary_sentences = 0 for sentence_start, sentence_end, line_start, line_end in components: component_sentences = sentences[sentence_start:sentence_end] component_lines = lines[line_start:line_end] sentence_bounds = cumulative_boundaries(component_sentences, lambda item: item.normalized) line_bounds = cumulative_boundaries(component_lines, lambda item: item["normalized"]) component_id = "va-" + stable_id( link_key, component_sentences[0].source_file, component_sentences[0].source_sentence_id, component_sentences[-1].source_sentence_id, *line_identity(component_sentences[0].work_id, component_lines[0]), *line_identity(component_sentences[0].work_id, component_lines[-1]), ) sentence_ids = [ "vs-" + stable_id(sentence.source, sentence.source_file, sentence.source_sentence_id) for sentence in component_sentences ] line_ids = [ "vm-" + stable_id(*line_identity(component_sentences[0].work_id, line)) for line in component_lines ] sentence_to_lines = [] for sentence_index in range(len(component_sentences)): start, end = sentence_bounds[sentence_index:sentence_index + 2] overlaps = [ line_index for line_index in range(len(component_lines)) if max(start, line_bounds[line_index]) < min(end, line_bounds[line_index + 1]) ] assert overlaps sentence_to_lines.append(overlaps) if len(overlaps) > 1: cross_boundary_sentences += 1 line_to_sentences = [] for line_index in range(len(component_lines)): start, end = line_bounds[line_index:line_index + 2] overlaps = [ sentence_index for sentence_index in range(len(component_sentences)) if max(start, sentence_bounds[sentence_index]) < min(end, sentence_bounds[sentence_index + 1]) ] assert overlaps line_to_sentences.append(overlaps) if len(overlaps) > 1: cross_boundary_lines += 1 for sentence_index, sentence in enumerate(component_sentences): overlapping_indices = sentence_to_lines[sentence_index] overlapping_lines = [component_lines[index] for index in overlapping_indices] published_lines = [] for index in overlapping_indices: line = component_lines[index] published_lines.append(public_metrical_line(line)) records = unique_source_records( list(sentence.source_records) + hypotactic_source_records(overlapping_lines, revisions) ) sentence_rows.append({ "id": sentence_ids[sentence_index], "author": sentence.author, "work": sentence.work, "work_id": sentence.work_id, "genre": "verse_sentence", "text": sentence.text, "conllu": sentence.conllu, "cts_urn": sentence.cts_urn, "passage": sentence.passage, "alignment_component_id": component_id, "component_sentence_index": sentence_index, "metre": sorted({line["metre"] for line in overlapping_lines}), "metrical_line_ids": [line_ids[index] for index in overlapping_indices], "metrical_lines": json.dumps(published_lines, ensure_ascii=False), "treebank_source": sentence.source, "source_records": json.dumps(records, ensure_ascii=False, sort_keys=True), "licenses": sorted({record["license"] for record in records}), "dedup_key": hashlib.sha256(sentence.normalized.encode()).hexdigest(), }) for line_index, line in enumerate(component_lines): overlapping_indices = line_to_sentences[line_index] parents = [component_sentences[index] for index in overlapping_indices] parent_ids = [sentence_ids[index] for index in overlapping_indices] records = unique_source_records( [record for parent in parents for record in parent.source_records] + hypotactic_source_records([line], revisions) ) metre_rows.append({ "id": line_ids[line_index], "parent_sentence_ids": parent_ids, "author": parents[0].author, "work": parents[0].work, "work_id": parents[0].work_id, "genre": "verse_metre", "text": line["text"], "conllu": "\n\n".join(parent.conllu.strip() for parent in parents) + "\n\n", "cts_urn": parents[0].cts_urn, "passage": " | ".join(dict.fromkeys(parent.passage for parent in parents if parent.passage)), "alignment_component_id": component_id, "component_line_index": line_index, "book": line["book"], "poem_sequence": line["poem_sequence"], "line_number": line["number"], "metre": line["metre"], "syllables": json.dumps(line["syllables"], ensure_ascii=False), "hypotactic_file": line["hypotactic_file"], "treebank_source": parents[0].source, "source_records": json.dumps(records, ensure_ascii=False, sort_keys=True), "licenses": sorted({record["license"] for record in records}), "dedup_key": hashlib.sha256(line["normalized"].encode()).hexdigest(), }) matched_sentence_indices.update(range(sentence_start, sentence_end)) matched_line_indices.update(range(line_start, line_end)) alignment_stats[link_key] = { **stats, "sentences": len(sentences), "lines": len(lines), "alignment_components": len(components), "matched_sentences": len(matched_sentence_indices), "matched_lines": len(matched_line_indices), "excluded_sentences": len(sentences) - len(matched_sentence_indices), "excluded_lines": len(lines) - len(matched_line_indices), "cross_boundary_sentences": cross_boundary_sentences, "cross_boundary_lines": cross_boundary_lines, } return sentence_rows, metre_rows, alignment_stats def numeric_line_number(value: str) -> int | None: match = re.match(r"^(\d+)", str(value)) return int(match.group(1)) if match else None def exclude_disputed_verse_components( sentence_rows: list[dict], metre_rows: list[dict], ) -> tuple[list[dict], list[dict], dict]: """Remove complete aligned components touching a disputed verse passage.""" excluded_components = set() matched_ranges = Counter() for row in metre_rows: ranges = DISPUTED_VERSE_PASSAGES.get((row["author"], row["work"]), ()) line_number = numeric_line_number(row["line_number"]) if line_number is None: continue for start, end in ranges: if start <= line_number <= end: excluded_components.add(row["alignment_component_id"]) matched_ranges[(row["author"], row["work"], start, end)] += 1 break retained_sentences = [ row for row in sentence_rows if row["alignment_component_id"] not in excluded_components ] retained_lines = [ row for row in metre_rows if row["alignment_component_id"] not in excluded_components ] return retained_sentences, retained_lines, { "excluded_components": len(excluded_components), "excluded_sentence_rows": len(sentence_rows) - len(retained_sentences), "excluded_metre_rows": len(metre_rows) - len(retained_lines), "matched_ranges": [ {"author": author, "work": work, "start": start, "end": end, "matched_lines": count} for (author, work, start, end), count in sorted(matched_ranges.items()) ], } def deduplicate_prose(rows: list[Sentence]) -> tuple[list[dict], dict]: groups = defaultdict(list) for row in rows: if row.normalized: groups[hashlib.sha256(row.normalized.encode()).hexdigest()].append(row) output = [] duplicate_groups = 0 duplicate_rows = 0 conflicting_author_groups = 0 conflicting_author_rows = 0 conflict_examples = [] for key, members in groups.items(): authors = {canonical_author(member.author) for member in members} if len(authors) > 1: conflicting_author_groups += 1 conflicting_author_rows += len(members) if len(conflict_examples) < 25: conflict_examples.append({ "dedup_key": key, "authors": sorted(authors), "normalized_length": len(members[0].normalized), "sources": sorted({member.source for member in members}), }) continue members.sort(key=lambda row: (row.priority, row.source, row.source_file, row.source_sentence_id)) chosen = members[0] source_records = [] seen = set() for member in members: for record in member.source_records: record_key = (record["source"], record["source_file"], record["source_sentence_id"]) if record_key not in seen: seen.add(record_key) source_records.append(record) if len(members) > 1: duplicate_groups += 1 duplicate_rows += len(members) - 1 output.append({ "id": "p-" + stable_id(chosen.source, chosen.source_file, chosen.source_sentence_id), "author": chosen.author, "work": chosen.work, "work_id": chosen.work_id, "genre": "prose", "text": chosen.text, "conllu": chosen.conllu, "cts_urn": chosen.cts_urn, "passage": chosen.passage, "treebank_source": chosen.source, "source_records": json.dumps(source_records, ensure_ascii=False, sort_keys=True), "licenses": sorted({record["license"] for record in source_records}), "dedup_key": key, }) output.sort(key=lambda row: row["id"]) return output, { "input_rows": len(rows), "output_rows": len(output), "duplicate_groups": duplicate_groups, "removed_exact_duplicates": duplicate_rows, "conflicting_author_groups_removed": conflicting_author_groups, "conflicting_author_rows_removed": conflicting_author_rows, "conflict_examples": conflict_examples, } def split_counts(n: int) -> dict[str, int]: if n < 3: n_val = n_test = 0 elif n < 10: n_val = n_test = 1 else: n_val = max(1, round(n * 0.1)) n_test = max(1, round(n * 0.1)) return {"train": n - n_val - n_test, "validation": n_val, "test": n_test} def split_labels(n: int) -> list[str]: counts = split_counts(n) return [split for split in ("train", "validation", "test") for _ in range(counts[split])] def assign_splits(rows: list[dict]) -> None: groups = defaultdict(list) for row in rows: groups[(row["author"], row["work_id"])].append(row) rng = random.Random(RANDOM_SEED) for group in sorted(groups): group_rows = sorted(groups[group], key=lambda row: row["id"]) rng.shuffle(group_rows) for row, split in zip(group_rows, split_labels(len(group_rows))): row["split"] = split def write_parquet( rows: list[dict], output_root: Path, config: str, schema: pa.Schema | None = None, ) -> dict: stats = {} config_root = output_root / config config_root.mkdir(parents=True, exist_ok=True) for split in ("train", "validation", "test"): split_rows = [row for row in rows if row["split"] == split] table = pa.Table.from_pylist(split_rows, schema=schema) path = config_root / f"{split}-00000-of-00001.parquet" pq.write_table(table, path, compression="zstd", compression_level=9) stats[split] = len(split_rows) return stats def validate_source_verse_alignment(rows_by_base_config: dict[str, list[dict]]) -> None: """Validate exact syntax/metre coverage before task-level row selection.""" components = defaultdict(lambda: {"sentences": [], "lines": []}) for row in rows_by_base_config["verse_sentence"]: components[row["alignment_component_id"]]["sentences"].append(row) for row in rows_by_base_config["verse_metre"]: components[row["alignment_component_id"]]["lines"].append(row) for component in components.values(): sentences = sorted( component["sentences"], key=lambda row: row["component_sentence_index"], ) lines = sorted(component["lines"], key=lambda row: row["component_line_index"]) assert sentences and lines assert "".join(normalize(row["text"]) for row in sentences) == "".join( normalize(row["text"]) for row in lines ) def validate(rows_by_config: dict[str, list[dict]]) -> dict: report = {} checked_conllu = set() for config, rows in rows_by_config.items(): ids = [row["id"] for row in rows] dedup = [row["dedup_key"] for row in rows] assert len(ids) == len(set(ids)), f"duplicate ids in {config}" base_config = config.rsplit("_", 1)[0] assert all(row["genre"] == base_config for row in rows) assert all(row["text"] and row["author"] and row["work"] for row in rows) for row in rows: text_units = load_text_units(row["text"]) assert len(text_units) == row.get("chunk_size", 1) assert all(row["split"] in {"train", "validation", "test"} for row in rows) suffix = config.rsplit("_", 1)[1] if suffix != "1": target = int(suffix) assert all( row["chunk_size"] == (1 if row["split"] == "train" else target) for row in rows ) assert all(row["chunk_target_size"] == target for row in rows) assert all(len(row["constituent_ids"]) == row["chunk_size"] for row in rows) if base_config == "prose": assert len(dedup) == len(set(dedup)), "prose exact-text deduplication failed" elif base_config == "verse_sentence": for row in rows: lines = load_public_metrical_lines(row["metrical_lines"]) assert len(lines) == len(row["metrical_line_ids"]) for row in rows: comments = [ line for line in row["conllu"].splitlines() if line.startswith("#") ] assert all(line.startswith("# text = ") for line in comments), ( f"Identifying CoNLL-U comment in {config}, row {row['id']}: {comments}" ) for line in row["conllu"].splitlines(): if not line or line.startswith("#"): continue columns = line.split("\t") assert len(columns) == 10 misc_keys = { item.split("=", 1)[0] for item in columns[9].split("|") if item != "_" } assert misc_keys <= SAFE_CONLLU_MISC_KEYS, ( f"Identifying CoNLL-U MISC field in {config}, " f"row {row['id']}: {misc_keys}" ) digest = hashlib.sha256(row["conllu"].encode("utf-8")).digest() if digest in checked_conllu: continue try: load_conllu(io.StringIO(row["conllu"])) except UDError as error: raise AssertionError( f"Malformed CoNLL-U in {config}, row {row['id']}: {error}" ) from error checked_conllu.add(digest) report[config] = { "rows": len(rows), "authors": len({row["author"] for row in rows}), "works": len({row["work_id"] for row in rows}), "sources": dict(Counter(row["treebank_source"] for row in rows)), "splits": dict(Counter(row["split"] for row in rows)), } for base_config in ("prose", "verse_sentence", "verse_metre"): atomic = rows_by_config[f"{base_config}_1"] atomic_by_id = {row["id"]: row for row in atomic} for target in (10, 100): variant = rows_by_config[f"{base_config}_{target}"] for split in ("train", "validation", "test"): expected_ids = { row["id"] for row in atomic if row["split"] == split } represented_ids = [ constituent_id for row in variant if row["split"] == split for constituent_id in row["constituent_ids"] ] assert len(represented_ids) == len(set(represented_ids)) assert set(represented_ids) == expected_ids for row in variant: if row["split"] != split or row["chunk_size"] == 1: continue constituents = [ atomic_by_id[row_id] for row_id in row["constituent_ids"] ] expected_text_units = [ unit for item in constituents for unit in load_text_units(item["text"]) ] assert load_text_units(row["text"]) == expected_text_units if base_config == "verse_metre": expected_syllables = [ syllable for item in constituents for syllable in json.loads(item["syllables"]) ] assert json.loads(row["syllables"]) == expected_syllables report["checks"] = { "unique_ids": True, "prose_exact_text_unique": True, "source_verse_component_exact_coverage": True, "identical_source_rows_across_task_sizes": True, "complete_chunk_text_and_syllable_aggregation": True, "scansion_column_absent": True, "fixed_exact_evaluation_chunks": True, "official_conll18_loader": True, "unique_conllu_documents_checked": len(checked_conllu), "identifier_free_conllu_comments": True, "identifier_free_conllu_misc": True, "privacy_safe_metrical_lines": True, "json_list_text_fields": True, } return report def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--sources", type=Path, required=True) parser.add_argument("--output", type=Path, default=Path("data")) parser.add_argument("--metadata", type=Path, default=Path("metadata")) args = parser.parse_args() revisions = { key: git_revision(args.sources / info["directory"]) for key, info in SOURCE_INFO.items() } agdt_prose, agdt_verse = parse_agdt(args.sources / "treebank_data", revisions) ud_perseus_prose, _ = parse_ud("ud_perseus", args.sources / "perseus", revisions) proiel_prose, _ = parse_ud("ud_proiel", args.sources / "proiel", revisions) ptnk_prose, _ = parse_ud("ud_ptnk", args.sources / "ptnk", revisions) gorman_prose, _ = parse_native_collection( "gorman", (args.sources / "gorman" / "xml versions").glob("*.xml"), revisions, ) pedalion_meta = publication_metadata(args.sources / "pedalion" / "src" / "config.json") # The Pedalion card groups these three files under "diverse authors"; # restore the file-level attributions encoded in the XML. pedalion_meta.update({ "semonides.xml": ("Semonides", "Typology of Women"), "theoc.xml": ("Theocritus", "Fragments"), "mimn.xml": ("Mimnermus", "Fragments"), }) pedalion_files = [ path for path in (args.sources / "pedalion" / "public" / "xml").glob("*.xml") if path.name not in PEDALION_EXCLUDE ] pedalion_prose, pedalion_verse = parse_native_collection( "pedalion", pedalion_files, revisions, pedalion_meta, PEDALION_VERSE, ) harrington_meta = publication_metadata(args.sources / "harrington" / "src" / "config.json") harrington_prose, _ = parse_native_collection( "harrington", (args.sources / "harrington" / "public" / "xml" / "CITE_TREEBANK_XML" / "perseus" / "grctb").rglob("*.xml"), revisions, harrington_meta, ) prose_input = ( ud_perseus_prose + proiel_prose + ptnk_prose + agdt_prose + gorman_prose + pedalion_prose + harrington_prose ) prose_input, prose_curation = curate_sentences(prose_input) prose, dedup_stats = deduplicate_prose(prose_input) assign_splits(prose) hyp = load_hypotactic(args.sources / "hypotactic") verse_input, verse_curation = curate_sentences(agdt_verse + pedalion_verse) verse_sentence, verse_metre, alignment_stats = align_verse_blocks( verse_input, hyp, revisions, ) verse_sentence, verse_metre, passage_curation = exclude_disputed_verse_components( verse_sentence, verse_metre, ) assign_splits(verse_sentence) assign_splits(verse_metre) rows_by_base_config = { "prose": prose, "verse_sentence": verse_sentence, "verse_metre": verse_metre, } validate_source_verse_alignment(rows_by_base_config) rows_by_config, variant_report = make_dataset_variants(rows_by_base_config) validation = validate(rows_by_config) base_schemas = { config: pa.Table.from_pylist(rows).schema for config, rows in rows_by_base_config.items() } data_stats = {} for config, rows in rows_by_config.items(): base_config = config.rsplit("_", 1)[0] schema = None if config.endswith("_1") else variant_schema(base_schemas[base_config]) data_stats[config] = write_parquet(rows, args.output, config, schema) args.metadata.mkdir(parents=True, exist_ok=True) (args.metadata / "source_revisions.json").write_text( json.dumps({ key: {**SOURCE_INFO[key], "revision": revision} for key, revision in revisions.items() }, indent=2, ensure_ascii=False) + "\n" ) (args.metadata / "dataset_variants.json").write_text( json.dumps( variant_report, indent=2, ensure_ascii=False, sort_keys=True, ) + "\n" ) (args.metadata / "build_report.json").write_text(json.dumps({ "data_files": data_stats, "authorship_curation": { "policy": ( "Conservative known-author benchmark: anonymous, unknown, pseudonymous, " "traditional, fragmentary, mediated, corporate, and substantially disputed " "attributions are excluded; Homeric epics use separate corpus labels." ), "prose_input": prose_curation, "verse_input": verse_curation, "disputed_verse_passages": passage_curation, }, "deduplication": dedup_stats, "splitting": { "seed": RANDOM_SEED, "strategy": "independent row-level 80/10/10 stratification by author and work", "variants": { "_1": "shared 100-task-eligible atomic rows", "_10": "shared atomic training rows; fixed exact 10-row evaluation chunks", "_100": "shared atomic training rows; fixed exact 100-row evaluation chunks", }, "evaluation_chunking": { "seed": RANDOM_SEED, "remainder_policy": ( "discard n modulo 100 rows per author and split by stable hash once; " "reuse the retained atomic rows in every task size" ), "ordering": "natural passage or line order within canonical work ID", "work_policy": ( "emit complete single-work chunks first, then combine residual work tails" ), "training_policy": ( "retain 100-task-eligible-author training rows as atomic units in all tasks" ), }, }, "alignment": alignment_stats, "validation": validation, "excluded": { "aphthonius": "No redistribution license is specified upstream.", "pedalion_mixed": sorted(PEDALION_EXCLUDE), "harrington_grctb_805": "File declares xml:lang=lat and contains Cicero despite its grctb path.", }, }, indent=2, ensure_ascii=False, sort_keys=True) + "\n") print(json.dumps(validation, indent=2, ensure_ascii=False)) if __name__ == "__main__": main()