sphragis / scripts /build_dataset.py
Urdatorn's picture
Publish metre inspection columns first
76be066
Raw
History Blame Contribute Delete
104 kB
#!/usr/bin/env python3
"""Build the Sphragis sentence and Sphragis Metre datasets from frozen sources.
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
from grc_utils import vowel
try:
from scripts.conllu_units import load_conllu_units
from scripts.dataset_variants import (
fields_first,
make_dataset_variants,
variant_schema,
)
from scripts.metre_units import load_metre_units, load_syllable_units
from scripts.metrical_lines import cropped_public_metrical_line, load_public_metrical_lines
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 conllu_units import load_conllu_units
from dataset_variants import fields_first, make_dataset_variants, variant_schema
from metre_units import load_metre_units, load_syllable_units
from metrical_lines import cropped_public_metrical_line, load_public_metrical_lines
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"]},
}
# Files predating Hypotactic's embedded data-author/data-work metadata are
# identified here from their stable upstream filenames. Received or disputed
# corpora remain explicit so the normal conservative authorship policy can
# exclude them rather than silently inventing labels.
HYPOTACTIC_FILE_METADATA = {
"HHAphrodite": ("Homer/Anon", "Homeric Hymn to Aphrodite"),
"HHApollo": ("Homer/Anon", "Homeric Hymn to Apollo"),
"HHDemeter": ("Homer/Anon", "Homeric Hymn to Demeter"),
"HHermes": ("Homer/Anon", "Homeric Hymn to Hermes"),
"HHymns": ("Homer/Anon", "The Homeric Hymns"),
"aratus": ("Aratus", "Phaenomena"),
"batmumach": ("Pseudo-Homer", "Batrachomyomachia"),
"cleanthes": ("Cleanthes", "Hymn to Zeus"),
"colluthus": ("Colluthus", "Rape of Helen"),
"lycophron": ("Lycophron", "Alexandra"),
"persians": ("Aeschylus", "Persians"),
"prometheus": ("Aeschylus", "Prometheus Bound"),
"scutum": ("Hesiod", "Shield of Heracles"),
"seven": ("Aeschylus", "Seven Against Thebes"),
"theognis": ("Theognis", "Theognidea"),
"theogony": ("Hesiod", "Theogony"),
"tryph": ("Tryphiodorus", "Sack of Troy"),
"worksanddays": ("Hesiod", "Works and Days"),
}
HYPOTACTIC_CANONICAL_WORK_IDS = {
("Aeschylus", "Persians"): "tlg0085.tlg002",
("Aeschylus", "Prometheus Bound"): "tlg0085.tlg003",
("Aeschylus", "Seven Against Thebes"): "tlg0085.tlg004",
("Hesiod", "Theogony"): "tlg0020.tlg001",
("Hesiod", "Works and Days"): "tlg0020.tlg002",
("Hesiod", "Shield of Heracles"): "tlg0020.tlg003",
("Homeric-Iliad", "Iliad"): "tlg0012.tlg001",
("Homeric-Odyssey", "Odyssey"): "tlg0012.tlg002",
}
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 crop_conllu_to_normalized_span(conllu: str, start: int, end: int) -> str:
"""Return a valid dependency tree containing only tokens inside a span."""
token_rows = []
for line in conllu.splitlines():
if not line or line.startswith("#"):
continue
columns = line.split("\t")
if len(columns) != 10 or not re.fullmatch(r"\d+", columns[0]):
raise ValueError("verse CoNLL-U must contain only integer token rows")
token_rows.append(columns)
if not token_rows:
raise ValueError("cannot crop empty CoNLL-U")
sentence_length = sum(len(normalize(row[1])) for row in token_rows)
if not 0 <= start < end <= sentence_length:
raise ValueError(f"invalid CoNLL-U crop {start}:{end}/{sentence_length}")
selected = []
cursor = 0
for row in token_rows:
token_length = len(normalize(row[1]))
token_start, token_end = cursor, cursor + token_length
cursor = token_end
if token_length:
overlaps = max(start, token_start) < min(end, token_end)
if overlaps and (token_start < start or token_end > end):
raise ValueError(
"metrical line boundary cuts through a syntax token: "
f"{start}:{end} versus {token_start}:{token_end} ({row[1]})"
)
if overlaps:
selected.append(row)
elif start <= token_start < end:
selected.append(row)
if not selected:
raise ValueError("CoNLL-U crop selected no tokens")
by_id = {int(row[0]): row for row in token_rows}
selected_ids = {int(row[0]) for row in selected}
def selected_ancestor(token_id: int) -> int:
head = int(by_id[token_id][6])
visited = {token_id}
while head and head not in selected_ids:
if head in visited or head not in by_id:
return 0
visited.add(head)
head = int(by_id[head][6])
return head
resolved = {int(row[0]): selected_ancestor(int(row[0])) for row in selected}
root_candidates = [
int(row[0]) for row in selected
if resolved[int(row[0])] == 0 and row[3] != "PUNCT"
]
primary_root = root_candidates[0] if root_candidates else next(
(int(row[0]) for row in selected if row[3] != "PUNCT"),
int(selected[0][0]),
)
id_map = {int(row[0]): new_id for new_id, row in enumerate(selected, 1)}
output_rows = []
for row in selected:
row = list(row)
old_id = int(row[0])
old_head = int(row[6])
ancestor = resolved[old_id]
if old_id == primary_root:
new_head = 0
relation = "root"
elif ancestor in selected_ids and ancestor != old_id:
new_head = id_map[ancestor]
relation = row[7] if row[7] != "root" else "dep"
else:
new_head = id_map[primary_root]
relation = "punct" if row[3] == "PUNCT" else "dep"
misc_items = [] if row[9] == "_" else row[9].split("|")
expected_head = id_map[old_head] if old_head in id_map else None
if new_head != expected_head and "HeadRepair=Yes" not in misc_items:
misc_items.append("HeadRepair=Yes")
row[0] = str(id_map[old_id])
row[6] = str(new_head)
row[7] = relation
row[8] = "_"
row[9] = "|".join(sorted(set(misc_items))) or "_"
output_rows.append(row)
text = smart_text(row[1] for row in output_rows)
if normalize(text) != "".join(normalize(row[1]) for row in output_rows):
raise ValueError("cropped CoNLL-U text reconstruction changed token content")
rendered = [f"# text = {text}"] + ["\t".join(row) for row in output_rows]
return "\n".join(rendered) + "\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 author == "Homer/Anon":
return None, "anonymous_or_received_homeric_hymn"
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.word_syllable_start = None
self.previous_word = None
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": [],
}
self.previous_word = None
elif self.line is not None and tag == "span" and "word" in classes:
self.word_depth = self.depth
self.word_text = []
self.word_syllable_start = len(self.line["syllables"])
if self.line is not None and tag == "span" and "syll" in classes:
quantity = (
"long" if "long" in classes or "diastole" 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", "caesura", "hiatus"}
),
}
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:
if self.syllable["text"].strip():
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()
has_syllable = (
self.word_syllable_start is not None
and len(self.line["syllables"]) > self.word_syllable_start
)
if word and has_syllable:
current_last_syllable = len(self.line["syllables"]) - 1
if self.previous_word is not None and self.previous_word[1] is not None:
previous_text, previous_last_syllable = self.previous_word
if vowel(previous_text[-1]) and vowel(word[0]):
features = set(
self.line["syllables"][previous_last_syllable]["features"]
)
features.add("hiatus")
self.line["syllables"][previous_last_syllable]["features"] = sorted(
features
)
features = set(self.line["syllables"][current_last_syllable]["features"])
features.add("caesura")
self.line["syllables"][current_last_syllable]["features"] = sorted(features)
self.previous_word = (word, current_last_syllable)
elif word:
self.previous_word = (word, None)
if word:
self.line["words"].append(word)
self.word_depth = None
self.word_text = []
self.word_syllable_start = None
if self.line_depth == self.depth and tag == "div":
if self.line["syllables"]:
self.line["syllables"][-1]["features"] = [
feature
for feature in self.line["syllables"][-1]["features"]
if feature not in {"caesura", "hiatus"}
]
self.line["tokens"] = self.line.pop("words")
self.line["text"] = " ".join(self.line["tokens"])
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.line["line_sequence"] = str(len(self.lines) + 1)
self.lines.append(self.line)
self.line = None
self.line_depth = None
self.previous_word = 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"(?:apollonius|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, *, all_files: bool = False) -> dict[str, list[dict]]:
html_root = root / "hypotactic_htmls_greek"
needed = (
sorted(path.stem for path in html_root.glob("*.html"))
if all_files
else 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 hypotactic_author_work(stem: str, line: dict) -> tuple[str, str, str]:
"""Return curated upstream author/work labels and a stable work ID."""
if re.fullmatch(r"apollonius\d+", stem):
author, work = "Apollonius Rhodius", "Argonautica"
elif re.fullmatch(r"iliad\d+", stem):
author, work = "Homer", "Iliad"
elif re.fullmatch(r"odyssey\d+", stem):
author, work = "Homer", "Odyssey"
else:
author = line.get("hypotactic_author", "").strip()
work = line.get("hypotactic_work", "").strip()
fallback = HYPOTACTIC_FILE_METADATA.get(stem)
if fallback and stem in {"persians", "seven"}:
author, work = fallback
if fallback:
author = author or fallback[0]
work = work or fallback[1]
if not work:
work = {
"Moschus": "Poems", "Semonides": "Fragments",
"Solon": "Fragments", "Tyrtaeus": "Elegies",
}.get(author, stem)
author = canonical_author(author)
if author == "Homer" and work in {"Iliad", "Odyssey"}:
author = f"Homeric-{work}"
work_id = HYPOTACTIC_CANONICAL_WORK_IDS.get(
(author, work), f"hypotactic:{slug(author)}:{slug(work)}",
)
return author, work, work_id
def hypotactic_line_key(line: dict) -> tuple[str, str, str, str, str]:
return (
line["hypotactic_file"], line["poem_sequence"], line["book"],
line["number"], line["line_sequence"],
)
def curated_hypotactic_line(stem: str, line: dict) -> tuple[dict | None, str | None]:
if not any("GREEK" in unicodedata.name(char, "") for char in line["text"]):
return None, "no_greek_letters"
author, work, work_id = hypotactic_author_work(stem, line)
curated_author, reason = authorship_decision(Sentence(
source="hypotactic", source_file=f"{stem}.html",
source_sentence_id=":".join(hypotactic_line_key(line)),
author=author, work=work, work_id=work_id, text=line["text"], conllu="",
genre="verse",
))
if reason:
return None, reason
return {
"author": curated_author, "work": work, "work_id": work_id,
"text": line["text"], "tokens": line["tokens"],
}, None
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']}:{line['line_sequence']}"
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 = []
local_sentence_start, local_sentence_end = sentence_bounds[
sentence_index:sentence_index + 2
]
for index in overlapping_indices:
line = component_lines[index]
local_line_start, local_line_end = line_bounds[index:index + 2]
published_lines.append(cropped_public_metrical_line(
line,
max(local_sentence_start, local_line_start) - local_line_start,
min(local_sentence_end, local_line_end) - local_line_start,
))
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_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]
local_line_start, local_line_end = line_bounds[line_index:line_index + 2]
cropped_conllu = []
for index in overlapping_indices:
local_sentence_start, local_sentence_end = sentence_bounds[index:index + 2]
cropped_conllu.append(crop_conllu_to_normalized_span(
component_sentences[index].conllu,
max(local_line_start, local_sentence_start) - local_sentence_start,
min(local_line_end, local_sentence_end) - local_sentence_start,
))
line_conllu = "\n\n".join(
unit.strip() for unit in cropped_conllu
) + "\n\n"
conllu_forms = [
columns[1]
for unit in cropped_conllu
for raw in unit.splitlines()
if raw and not raw.startswith("#")
for columns in [raw.split("\t")]
if re.fullmatch(r"\d+", columns[0])
]
assert normalize("".join(conllu_forms)) == line["normalized"]
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": line_conllu,
"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
STOICHEIA_MODEL_ID = "Ericu950/Stoicheia-tagger-parser"
STOICHEIA_MODEL_REVISION = "cd8ae1658c364874c3b6f4df37bd1d46313e3cea"
def load_stoicheia_predictions(path: Path) -> dict[tuple[str, ...], dict]:
predictions = {}
with path.open(encoding="utf-8") as handle:
for number, raw in enumerate(handle, 1):
try:
row = json.loads(raw)
except json.JSONDecodeError as error:
raise ValueError(f"invalid Stoicheia JSONL line {number}") from error
key = tuple(row["key"])
if key in predictions:
raise ValueError(f"duplicate Stoicheia prediction key: {key}")
if row["model"] != STOICHEIA_MODEL_ID:
raise ValueError(f"unexpected Stoicheia model at line {number}")
if row["model_revision"] != STOICHEIA_MODEL_REVISION:
raise ValueError(f"unexpected Stoicheia revision at line {number}")
if row.get("context_parsing") != "sentence_then_crop_v1":
raise ValueError(
f"Stoicheia cache was not parsed as reconstructed sentences at line {number}"
)
context_ids = row.get("context_sentence_ids", [])
context_counts = row.get("context_sentence_line_counts", [])
context_forced = row.get("context_forced_splits", [])
if not context_ids or not (
len(context_ids) == len(context_counts) == len(context_forced)
):
raise ValueError(f"invalid Stoicheia context metadata at line {number}")
predictions[key] = row
return predictions
def stoicheia_source_record() -> dict:
return {
"source": "stoicheia_tagger_parser",
"source_file": STOICHEIA_MODEL_ID,
"source_sentence_id": "",
"url": f"https://huggingface.co/{STOICHEIA_MODEL_ID}",
"revision": STOICHEIA_MODEL_REVISION,
"license": "Apache-2.0",
"annotation_provenance": (
"automatic lemma, POS, morphology, and dependency prediction on "
"punctuation-delimited sentences reconstructed across consecutive "
"metrical lines; sentence trees cropped back to line boundaries"
),
"syntax_scheme": "Stoicheia AGDT heads converted to Universal Dependencies",
}
def predicted_metre_rows(
all_hypotactic: dict[str, list[dict]],
predictions: dict[tuple[str, ...], dict],
gold_rows: list[dict],
revisions: dict[str, str],
) -> tuple[list[dict], dict]:
"""Fill lines without a gold tree with pinned Stoicheia predictions."""
lines_by_key = {
hypotactic_line_key(line): line
for lines in all_hypotactic.values()
for line in lines
}
eligible = {}
excluded = Counter()
for stem, lines in all_hypotactic.items():
for line in lines:
curated, reason = curated_hypotactic_line(stem, line)
if reason:
excluded[reason] += 1
else:
eligible[hypotactic_line_key(line)] = curated
if set(predictions) != set(eligible):
missing = set(eligible) - set(predictions)
extra = set(predictions) - set(eligible)
raise ValueError(
f"Stoicheia cache is incomplete or stale: missing={len(missing)} extra={len(extra)}"
)
gold_keys = {
(row["hypotactic_file"], row["poem_sequence"], row["book"], row["line_number"])
for row in gold_rows
}
output = []
excluded_disputed = 0
for key, prediction in sorted(predictions.items()):
if key[:4] in gold_keys:
continue
line = lines_by_key.get(key)
if line is None:
raise ValueError(f"Stoicheia prediction has no Hypotactic line: {key}")
if normalize(prediction["text"]) != line["normalized"]:
raise ValueError(f"Stoicheia prediction text drifted from Hypotactic: {key}")
author = eligible[key]["author"]
work = eligible[key]["work"]
work_id = eligible[key]["work_id"]
if (prediction["author"], prediction["work"]) != (author, work):
raise ValueError(f"Stoicheia prediction authorship drifted: {key}")
line_number = numeric_line_number(line["number"])
if line_number is not None and any(
start <= line_number <= end
for start, end in DISPUTED_VERSE_PASSAGES.get((author, work), ())
):
excluded_disputed += 1
continue
hyp_record = hypotactic_source_records([line], revisions)[0]
model_record = stoicheia_source_record()
records = [hyp_record, model_record]
output.append({
"id": "vm-" + stable_id(work_id, *key),
"parent_sentence_ids": [],
"author": author,
"work": work,
"work_id": work_id,
"genre": "verse_metre",
"text": line["text"],
"conllu": prediction["conllu"],
"cts_urn": "",
"passage": line["number"],
"alignment_component_id": None,
"component_line_index": None,
"book": line["book"],
"poem_sequence": line["poem_sequence"],
"line_number": line["number"],
"metre": line["metre"] or "unspecified",
"syllables": json.dumps(line["syllables"], ensure_ascii=False),
"hypotactic_file": line["hypotactic_file"],
"treebank_source": "stoicheia_tagger_parser",
"syntax_annotation": "predicted",
"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(),
})
for row in gold_rows:
row["syntax_annotation"] = "gold"
context_sentence_ids = {
sentence_id
for prediction in predictions.values()
for sentence_id in prediction.get("context_sentence_ids", [])
}
multiline_sentence_ids = {
sentence_id
for prediction in predictions.values()
for sentence_id, line_count in zip(
prediction.get("context_sentence_ids", []),
prediction.get("context_sentence_line_counts", []),
)
if line_count > 1
}
forced_context_sentence_ids = {
sentence_id
for prediction in predictions.values()
for sentence_id, forced in zip(
prediction.get("context_sentence_ids", []),
prediction.get("context_forced_splits", []),
)
if forced
}
return output, {
"model": STOICHEIA_MODEL_ID,
"model_revision": STOICHEIA_MODEL_REVISION,
"inference_unit": "punctuation-delimited sentence across consecutive metrical lines",
"publication_unit": "metrical line cropped from its inferred sentence tree",
"sentence_boundary_policy": "terminal period, question mark, or exclamation mark; context-window fallback only at line boundaries",
"context_sentences": len(context_sentence_ids),
"context_sentences_spanning_multiple_lines": len(multiline_sentence_ids),
"context_window_forced_splits": len(forced_context_sentence_ids),
"predictions_in_cache": len(predictions),
"hypotactic_lines_total": len(lines_by_key),
"hypotactic_lines_excluded_before_parsing": sum(excluded.values()),
"hypotactic_lines_excluded_by_reason": dict(sorted(excluded.items())),
"gold_lines": len(gold_rows),
"gold_keys": len(gold_keys),
"predicted_lines_added": len(output),
"predictions_superseded_by_gold": sum(key[:4] in gold_keys for key in predictions),
"predicted_disputed_lines_excluded": excluded_disputed,
"predicted_head_repair_tokens": sum(
line.endswith("\tHeadRepair=Yes")
for row in output
for line in row["conllu"].splitlines()
),
"predicted_tokens": sum(
bool(line) and not line.startswith("#")
for row in output
for line in row["conllu"].splitlines()
),
}
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_sentences(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": "s-" + stable_id(chosen.source, chosen.source_file, chosen.source_sentence_id),
"author": chosen.author, "work": chosen.work, "work_id": chosen.work_id,
"genre": chosen.genre, "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_publication(
rows_by_config: dict[str, list[dict]], publication: str,
) -> dict:
"""Validate final repository-level rows after the publication split."""
expected_configs = (
tuple(f"sentence_{suffix}" for suffix in ("1", "10", "50", "100"))
if publication == "sentence"
else tuple(f"verse_{suffix}" for suffix in ("1", "10", "50", "100"))
)
assert set(rows_by_config) == set(expected_configs)
report = {}
for config in expected_configs:
rows = rows_by_config[config]
suffix = config.rsplit("_", 1)[1]
target = int(suffix)
ids = [row["id"] for row in rows]
assert len(ids) == len(set(ids))
if publication == "sentence":
assert {row["genre"] for row in rows} == {"prose", "verse"}
else:
assert all("genre" not in row for row in rows)
for row in rows:
expected_units = 1 if suffix == "1" else target
text_units = load_text_units(row["text"])
assert len(text_units) == expected_units
assert len(load_conllu_units(row["conllu"])) == expected_units
if publication == "metre":
metre_units = load_metre_units(row["metre"])
syllable_units = load_syllable_units(row["syllables"])
assert len(metre_units) == expected_units
assert len(syllable_units) == expected_units
if suffix != "1":
assert row["chunk_size"] == target
assert row["chunk_target_size"] == target
assert len(row["constituent_ids"]) == target
if publication == "sentence":
forbidden = {
"metre", "metrical_lines", "syllables", "scansion",
"alignment_component_id", "component_sentence_index",
"component_line_index", "parent_sentence_ids", "hypotactic_file",
"book", "poem_sequence", "line_number",
}
assert not (forbidden & set(row))
assert all(
record["source"] != "hypotactic"
for record in json.loads(row["source_records"])
)
report[config] = {
"rows": len(rows),
"authors": len({row["author"] for row in rows}),
"splits": dict(Counter(row["split"] for row in rows)),
}
if publication == "sentence":
report[config]["genres"] = sorted({row["genre"] for row in rows})
atomic = rows_by_config[expected_configs[0]]
if publication == "metre":
authors = {row["author"] for row in atomic}
feature_authors = defaultdict(set)
for row in atomic:
for line in load_syllable_units(row["syllables"]):
for syllable in line["syllables"]:
for feature in syllable["features"]:
feature_authors[feature].add(row["author"])
assert feature_authors["caesura"] == authors
assert feature_authors["hiatus"] == authors
for config in expected_configs[1:]:
for split in ("train", "validation", "test"):
expected_ids = {row["id"] for row in atomic if row["split"] == split}
represented_ids = [
row_id
for row in rows_by_config[config]
if row["split"] == split
for row_id in row["constituent_ids"]
]
assert len(represented_ids) == len(set(represented_ids))
assert set(represented_ids) == expected_ids
report["checks"] = {
"expected_configurations": True,
"identical_source_rows_across_task_sizes": True,
"fixed_exact_chunks_all_splits": True,
"nested_text_and_conllu_cardinality": True,
}
report["checks"][
"genre_annotations_preserved"
if publication == "sentence"
else "redundant_genre_column_omitted"
] = True
if publication == "metre":
report["checks"]["derived_boundary_feature_author_coverage"] = True
report["checks"]["derived_line_features_exact"] = True
return report
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"]:
if row["alignment_component_id"] is not None:
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)
conllu_units = load_conllu_units(row["conllu"])
assert len(conllu_units) == row.get("chunk_size", 1)
if base_config == "verse_metre":
metre_units = load_metre_units(row["metre"])
syllable_units = load_syllable_units(row["syllables"])
assert len(metre_units) == len(text_units)
assert len(syllable_units) == len(text_units)
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"] == 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 normalize("".join(line["text"] for line in lines)) == normalize(
"".join(load_text_units(row["text"]))
)
assert normalize("".join(
syllable["text"]
for line in lines
for syllable in line["syllables"]
)) == normalize("".join(load_text_units(row["text"])))
for row in rows:
row_text_units = load_text_units(row["text"])
for conllu_index, conllu in enumerate(load_conllu_units(row["conllu"])):
comments = [
line for line in 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 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(conllu.encode("utf-8")).digest()
if digest in checked_conllu:
continue
try:
load_conllu(io.StringIO(conllu))
except UDError as error:
raise AssertionError(
f"Malformed CoNLL-U in {config}, row {row['id']}: {error}"
) from error
checked_conllu.add(digest)
if base_config == "verse_metre":
forms = [
line.split("\t")[1]
for line in conllu.splitlines()
if line and not line.startswith("#")
]
assert normalize("".join(forms)) == normalize(
row_text_units[conllu_index]
)
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
expected_conllu_units = [
unit
for item in constituents
for unit in load_conllu_units(item["conllu"])
]
assert load_conllu_units(row["conllu"]) == expected_conllu_units
if base_config == "verse_metre":
expected_metres = [
metre
for item in constituents
for metre in load_metre_units(item["metre"])
]
expected_syllables = [
line
for item in constituents
for line in load_syllable_units(item["syllables"])
]
assert load_metre_units(row["metre"]) == expected_metres
assert load_syllable_units(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,
"fixed_exact_chunks_all_splits": 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,
"json_list_conllu_fields": True,
"json_list_metre_fields": True,
"line_objects_with_derived_metrical_features": True,
"derived_boundary_features_not_line_final": True,
"sentence_local_metrical_annotations": True,
"line_local_verse_metre_conllu": 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"))
parser.add_argument("--metre-output", type=Path, required=True)
parser.add_argument("--metre-metadata", type=Path, required=True)
parser.add_argument("--stoicheia-conllu", type=Path, required=True)
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, ud_perseus_verse = parse_ud(
"ud_perseus", args.sources / "perseus", revisions,
)
proiel_prose, proiel_verse = parse_ud(
"ud_proiel", args.sources / "proiel", revisions,
)
ptnk_prose, ptnk_verse = parse_ud(
"ud_ptnk", args.sources / "ptnk", revisions,
)
gorman_prose, gorman_verse = 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, harrington_verse = parse_native_collection(
"harrington",
(args.sources / "harrington" / "public" / "xml" / "CITE_TREEBANK_XML" / "perseus" / "grctb").rglob("*.xml"),
revisions, harrington_meta,
)
sentence_input = (
agdt_prose + agdt_verse
+ ud_perseus_prose + ud_perseus_verse
+ proiel_prose + proiel_verse
+ ptnk_prose + ptnk_verse
+ gorman_prose + gorman_verse
+ pedalion_prose + pedalion_verse
+ harrington_prose + harrington_verse
)
sentence_input_inventory = {
"rows_by_source": dict(sorted(Counter(row.source for row in sentence_input).items())),
"rows_by_genre": dict(sorted(Counter(row.genre for row in sentence_input).items())),
"total_rows": len(sentence_input),
}
sentence_input, sentence_curation = curate_sentences(sentence_input)
sentences, dedup_stats = deduplicate_sentences(sentence_input)
assign_splits(sentences)
hyp = load_hypotactic(args.sources / "hypotactic", all_files=True)
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,
)
stoicheia_predictions = load_stoicheia_predictions(args.stoicheia_conllu)
predicted_metre, stoicheia_stats = predicted_metre_rows(
hyp, stoicheia_predictions, verse_metre, revisions,
)
verse_metre.extend(predicted_metre)
assign_splits(verse_sentence)
assign_splits(verse_metre)
validate_source_verse_alignment({
"verse_sentence": verse_sentence, "verse_metre": verse_metre,
})
sentence_rows, sentence_variant_report = make_dataset_variants(
{"sentence": sentences}
)
metre_rows, metre_variant_report = make_dataset_variants(
{"verse_metre": verse_metre}
)
sentence_validation = validate_publication(sentence_rows, "sentence")
metre_validation = validate_publication(metre_rows, "metre")
sentence_stats = {}
sentence_schema = pa.Table.from_pylist(sentences).schema
for config, rows in sentence_rows.items():
schema = (
sentence_schema
if config.endswith("_1")
else variant_schema(sentence_schema)
)
sentence_stats[config] = write_parquet(rows, args.output, config, schema)
metre_stats = {}
metre_schema = pa.Table.from_pylist(verse_metre).schema
metre_schema = metre_schema.remove(metre_schema.get_field_index("genre"))
metre_schema = fields_first(metre_schema, ("syllables", "conllu"))
for config, rows in metre_rows.items():
schema = (
metre_schema
if config.endswith("_1")
else variant_schema(metre_schema)
)
metre_stats[config] = write_parquet(
rows, args.metre_output, config, schema
)
all_source_revisions = {
key: {**SOURCE_INFO[key], "revision": revision}
for key, revision in revisions.items()
}
all_source_revisions["stoicheia_tagger_parser"] = {
"url": f"https://huggingface.co/{STOICHEIA_MODEL_ID}",
"license": "Apache-2.0",
"annotation": "automatic morphosyntactic and dependency annotation",
"scheme": "Stoicheia AGDT heads converted to Universal Dependencies",
"revision": STOICHEIA_MODEL_REVISION,
}
sentence_source_revisions = {
key: value for key, value in all_source_revisions.items()
if key not in {"hypotactic", "stoicheia_tagger_parser"}
}
sentence_report = {
"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."
),
"treebank_source_inventory": sentence_input_inventory,
"treebank_sentence_input": sentence_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": "fixed exact 10-row chunks in every split",
"_50": "fixed exact 50-row chunks in every split",
"_100": "fixed exact 100-row chunks in every split",
},
"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": (
"chunk training identically to validation and test; augmentation is model-side"
),
},
},
"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.",
},
}
atomic_syllable_lines = [
line
for row in metre_rows["verse_1"]
for line in load_syllable_units(row["syllables"])
]
published_line_feature_names = sorted({
feature
for line in atomic_syllable_lines
for feature in line["features"]
})
metre_report = {
"authorship_curation": {
"policy": sentence_report["authorship_curation"]["policy"],
"verse_input": verse_curation,
"disputed_verse_passages": passage_curation,
},
"splitting": sentence_report["splitting"],
"alignment": alignment_stats,
"automatic_syntax": stoicheia_stats,
"metrical_representation": {
"unit_alignment": (
"text, conllu, metre, and syllables are JSON lists aligned by "
"constituent metrical-line index"
),
"syllable_nesting": (
"outer list is lines; each line has features and syllables"
),
"line_features": {
"dense": ["hiatus", "longa", "brevia", "morae"],
"sparse": [
"isochronic-caesura-t", "isosyllabic-caesura-s",
],
"time_values": {"long": 1, "short": 0.5, "elided": 0},
"published_feature_names": published_line_feature_names,
},
"caesura_source": (
"final syllable of every non-line-final Hypotactic word span"
),
"hiatus_source": (
"adjacent Hypotactic words whose edge characters both satisfy "
"grc_utils.vowel; attached to the first word's final syllable"
),
"published_caesura_features": sum(
"caesura" in syllable["features"]
for row in metre_rows["verse_1"]
for line in load_syllable_units(row["syllables"])
for syllable in line["syllables"]
),
"published_lines_with_caesura": sum(
any(
"caesura" in syllable["features"]
for syllable in line["syllables"]
)
for row in metre_rows["verse_1"]
for line in load_syllable_units(row["syllables"])
),
"published_hiatus_features": sum(
"hiatus" in syllable["features"]
for row in metre_rows["verse_1"]
for line in load_syllable_units(row["syllables"])
for syllable in line["syllables"]
),
"published_lines_with_hiatus": sum(
any(
"hiatus" in syllable["features"]
for syllable in line["syllables"]
)
for row in metre_rows["verse_1"]
for line in load_syllable_units(row["syllables"])
),
"published_syllable_text_mismatches": sum(
normalize("".join(
syllable["text"] for syllable in line["syllables"]
))
!= normalize(text)
for row in metre_rows["verse_1"]
for text, line in zip(
load_text_units(row["text"]),
load_syllable_units(row["syllables"]),
)
),
},
"excluded": sentence_report["excluded"],
}
publications = (
(
args.metadata,
"sentence",
sentence_rows,
sentence_stats,
sentence_validation,
sentence_source_revisions,
sentence_report,
sentence_variant_report,
),
(
args.metre_metadata,
"metre",
metre_rows,
metre_stats,
metre_validation,
all_source_revisions,
metre_report,
metre_variant_report,
),
)
for (
metadata_root, publication, publication_rows, stats, validation,
publication_sources, build_report, variant_report,
) in publications:
metadata_root.mkdir(parents=True, exist_ok=True)
(metadata_root / "source_revisions.json").write_text(
json.dumps(publication_sources, indent=2, ensure_ascii=False) + "\n"
)
(metadata_root / "dataset_variants.json").write_text(
json.dumps(
variant_report,
indent=2,
ensure_ascii=False,
sort_keys=True,
) + "\n"
)
(metadata_root / "build_report.json").write_text(
json.dumps({
**build_report,
"publication": publication,
"data_files": stats,
"validation": validation,
}, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
)
print(json.dumps({
"sentence": sentence_validation,
"metre": metre_validation,
}, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()