Datasets:
Tasks:
Text Classification
Formats:
parquet
Languages:
Ancient Greek (to 1453)
Size:
100K - 1M
ArXiv:
License:
Download scripts/tracks.py from Urdatorn/sphragis: direct link, hf CLI and curl.
- Browser
- Download file 42.6 kB
-
https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/tracks.py
- Command line
-
hf download hf://datasets/Urdatorn/sphragis/scripts/tracks.py
-
curl -L -o tracks.py https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/tracks.py
42.6 kB
| """Track construction for the remade Sphragis benchmark. | |
| Everything the 2026-09 remake changed about *which rows evaluate which claim* | |
| lives here, so that the build script's parsing and normalisation stay as they | |
| were and the new decisions can be read and tested on their own: | |
| * passage-level near-duplicate removal, because sentence-level exact | |
| deduplication left the same passage in train and test whenever two projects | |
| segmented or spelled it differently; | |
| * a canonical work identifier, because the file names the projects use split | |
| one work into many "works" and name one work in several ways; | |
| * a four-way split (train, validation, validation2, test), the second | |
| validation split being reserved for choosing combination models; | |
| * the work-held-out track, in which every author's test data is whole works | |
| absent from training, held out within an annotation project so that changing | |
| the work does not also change the annotator; | |
| * the period-and-genre-matched tracks; | |
| * the uniform machine syntax layer, keyed by sentence text and carrying the | |
| human lemma. | |
| """ | |
| from __future__ import annotations | |
| import difflib | |
| import json | |
| import random | |
| import re | |
| import unicodedata | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Callable, Iterable | |
| try: | |
| from scripts.syntax_normalization import normalize_cc_heads | |
| except ModuleNotFoundError: # Direct execution from the scripts directory. | |
| from syntax_normalization import normalize_cc_heads | |
| RANDOM_SEED = 917 | |
| SPLITS = ("train", "validation", "validation2", "test") | |
| SPLIT_FRACTIONS = {"validation": 0.10, "validation2": 0.05, "test": 0.10} | |
| # Mirrors the priorities the parsers assign: a sentence that two projects | |
| # annotated is published from the lower number. | |
| SOURCE_PRIORITY = { | |
| "ud_perseus": 0, "ud_proiel": 0, "ud_ptnk": 0, | |
| "gorman": 5, "agdt": 10, "harrington": 15, "pedalion": 20, | |
| } | |
| NEAR_DUPLICATE_SHINGLE = 4 | |
| # Same author, two projects: half of either sentence's word 4-grams inside the | |
| # other, and at least three shared 4-grams, i.e. six running words. | |
| NEAR_DUPLICATE_CONTAINMENT = 0.5 | |
| NEAR_DUPLICATE_MINIMUM_SHARED = 3 | |
| # Different authors: a quotation, not a stock phrase. Four shared 4-grams are | |
| # seven running words, and the shorter sentence must be almost entirely shared. | |
| CROSS_AUTHOR_CONTAINMENT = 0.8 | |
| CROSS_AUTHOR_MINIMUM_SHARED = 4 | |
| WORK_HELD_OUT_MINIMUM_TEST_ROWS = 50 | |
| WORK_HELD_OUT_MAXIMUM_FRACTION = 0.5 | |
| WORK_HELD_OUT_TARGET_FRACTION = 0.10 | |
| # A second whole work, when the author has one to spare, is held out for model | |
| # selection, so that validation and test are both out-of-work. It must leave | |
| # the test work a training work of its own project, and the row minima below | |
| # are those of dataset_variants.ELIGIBILITY_MINIMUM. | |
| WORK_HELD_OUT_VALIDATION_TARGET_FRACTION = 0.15 | |
| WORK_HELD_OUT_VALIDATION_MINIMUM_ROWS = 60 | |
| WORK_HELD_OUT_MINIMUM_TRAIN_ROWS = 100 | |
| WORK_HELD_OUT_MINIMUM_VALIDATION_ROWS = 50 | |
| WORK_HELD_OUT_MINIMUM_VALIDATION2_ROWS = 10 | |
| GENRE_TRACKS = { | |
| "tragedians": ("Aeschylus", "Sophocles", "Euripides"), | |
| "attic_orators": ("Aeschines", "Antiphon", "Demosthenes", "Lysias"), | |
| "imperial_historians": ( | |
| "Appian", "Diodorus Siculus", "Dionysius of Halicarnassus", "Josephus", | |
| "Plutarch", | |
| ), | |
| # Two of the three labels are corpora, not authors: the benchmark keeps | |
| # the Iliad and the Odyssey apart because their common authorship is not | |
| # secure, so the track is named for what it holds, archaic epic, rather | |
| # than for a metre that would suggest three poets. | |
| "archaic_epic": ("Hesiod", "Homeric-Iliad", "Homeric-Odyssey"), | |
| } | |
| # The literary genre of every work the work-held-out tracks can hold out, so | |
| # that an author whose held-out work has no same-genre rival on the track is | |
| # reported as a genre floor rather than as attribution. Keyed by canonical | |
| # work; authors of one work fall back to AUTHOR_GENRES. | |
| WORK_GENRES = { | |
| **{f"tlg0085.tlg{n:03d}": "tragedy" for n in (1, 2, 4, 5, 6, 7)}, | |
| **{f"tlg0011.tlg{n:03d}": "tragedy" for n in (1, 2, 3, 4, 5)}, | |
| "pedalion:euripides:medea": "tragedy", | |
| "pedalion:aristophanes:acharnians": "comedy", | |
| "pedalion:aristophanes:thesmophoriazusae": "comedy", | |
| "pedalion:menander:dyskolos": "comedy", | |
| "tlg0012.tlg001": "epic", "tlg0012.tlg002": "epic", | |
| "tlg0020.tlg001": "epic", "tlg0020.tlg002": "epic", | |
| "tlg0026.tlg001": "oratory", | |
| "tlg0028.tlg005": "oratory", "tlg0028.tlg006": "oratory", | |
| **{f"tlg0014.tlg{n:03d}": "oratory" for n in (1, 4, 18, 27, 36, 37, 39, 41, 42, 45, 51, 54, 57)}, | |
| **{f"tlg0540.tlg{n:03d}": "oratory" for n in (1, 12, 13, 19, 23, 24)}, | |
| "tlg0059.tlg001": "dialogue", "tlg0059.tlg002": "dialogue", "tlg0059.tlg003": "dialogue", | |
| "tlg0032.tlg001": "historiography", "tlg0032.tlg002": "dialogue", | |
| "tlg0032.tlg004": "dialogue", "tlg0032.tlg006": "historiography", | |
| "tlg0032.tlg007": "historiography", "tlg0032.tlg008": "dialogue", | |
| "tlg0007.tlg004": "biography", "tlg0007.tlg015": "biography", | |
| "tlg0007.tlg086": "epideictic", "tlg0007.tlg087": "epideictic", | |
| "pedalion:lucian:judicium-vocalium": "epideictic", | |
| "pedalion:lucian:prometheus": "dialogue", | |
| "pedalion:lucian:symposium": "dialogue", | |
| "tlg0062.tlg012": "novel", | |
| "proiel-rom": "epistle", "proiel-gal": "epistle", | |
| "proiel-phil": "epistle", "proiel-philem": "epistle", | |
| "tlg0016.tlg001": "historiography", "tlg0003.tlg001": "historiography", | |
| "tlg0543.tlg001": "historiography", "tlg0060.tlg001": "historiography", | |
| "tlg0081.tlg001": "historiography", "tlg0526.tlg004": "historiography", | |
| "tlg0551.tlg017": "historiography", "tlg0086.tlg035": "philosophy", | |
| "tlg0008.tlg001": "miscellany", | |
| } | |
| AUTHOR_GENRES = { | |
| "Procopius": "historiography", "Sextus Empiricus": "philosophy", | |
| "Aristotle": "philosophy", "Athenaeus": "miscellany", "Euripides": "tragedy", | |
| "Menander": "comedy", "Aristophanes": "comedy", "Paul": "epistle", | |
| } | |
| def work_genre(row: dict) -> str: | |
| work = row.get("canonical_work") or row.get("work_id") or "" | |
| return WORK_GENRES.get(work) or AUTHOR_GENRES.get(row["author"], "unknown") | |
| #: The Hypotactic label of the metre the two metre tracks are cut to. | |
| HEXAMETER = "hexameter" | |
| #: A track of the metre publication is not built: Hypotactic scans no Sophocles | |
| #: and no Euripides, so a tragedians track there would carry the single label | |
| #: Aeschylus. | |
| METRE_TRACKS_NOT_BUILT = { | |
| "tragedians": ( | |
| "the scanned corpus holds one tragedian, Aeschylus, so the track would " | |
| "have a single label" | |
| ), | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Text normalisation for duplicate detection | |
| # -------------------------------------------------------------------------- | |
| def normalize_token(token: str) -> str: | |
| """Greek letters only, lowercased, final sigma folded, no diacritics. | |
| ``str.isalpha`` is true for U+02BC MODIFIER LETTER APOSTROPHE, which Gorman's | |
| files use for elision, so it used to survive into the dedup key while the | |
| combining mark AGDT and UD use was stripped, and the same sentence hashed | |
| differently in different projects. Modifier letters are dropped here. | |
| """ | |
| token = token.lower().replace("ς", "σ") | |
| token = "".join( | |
| char for char in unicodedata.normalize("NFD", token) | |
| if unicodedata.category(char) != "Mn" | |
| ) | |
| # After NFD every Greek letter sits in the basic block, so the range test | |
| # also drops Latin gap markers, digits and modifier letters such as U+02BC. | |
| return "".join( | |
| char for char in token | |
| if "\u0370" <= char <= "\u03ff" and char.isalpha() and not ("\u03da" <= char <= "\u03e1") | |
| ) | |
| def normalize(text: str) -> str: | |
| return "".join(normalize_token(token) for token in text.split()) | |
| def shingle_tokens(text: str) -> list[str]: | |
| return [token for token in (normalize_token(t) for t in text.split()) if token] | |
| # Word tokens may contain only Greek letters and combining marks. The archaic | |
| # numeral letters (stigma, digamma, koppa, sampi) are excluded: they occur as | |
| # numerals and sigla, and the parser's tokeniser drops them, which would leave | |
| # the text and the machine tree out of step. | |
| REPRESENTABLE = re.compile(r"^(?:[\u0370-\u03d9\u03e2-\u03ff\u1f00-\u1fff\u0300-\u036f])+$") | |
| def is_representable_token(token: str) -> bool: | |
| return bool(REPRESENTABLE.match(unicodedata.normalize("NFC", token))) | |
| def remove_unrepresentable_rows(rows: list[dict], *, example_limit: int = 20) -> tuple[list[dict], dict]: | |
| """Exclude sentences whose words carry characters that are not Greek. | |
| After editorial punctuation is removed, a word token that still contains a | |
| Latin letter, a digit, an angle sign or an archaic numeral letter is a | |
| corrupt or editorially marked transcription (Pedalion writes damaged | |
| letters as ``g`` and digits inside the word). Such a sentence is not the | |
| author's text as transmitted and is excluded, with counts per author and | |
| project reported. | |
| """ | |
| try: | |
| from scripts.model_facing import lower_greek, punctuationless_text | |
| except ModuleNotFoundError: # Direct execution from the scripts directory. | |
| from model_facing import lower_greek, punctuationless_text | |
| kept: list[dict] = [] | |
| removed: Counter[tuple[str, str]] = Counter() | |
| examples: list[dict] = [] | |
| for row in rows: | |
| text = row["text"] if isinstance(row["text"], str) else " ".join(row["text"]) | |
| words = punctuationless_text(lower_greek(text)).split() | |
| bad = [word for word in words if not is_representable_token(word)] | |
| if not words or bad: | |
| removed[(row["author"], row["treebank_source"])] += 1 | |
| if len(examples) < example_limit: | |
| examples.append({ | |
| "author": row["author"], "source": row["treebank_source"], | |
| "tokens": bad[:5], "text": text[:80], | |
| }) | |
| continue | |
| kept.append(row) | |
| return kept, { | |
| "policy": ( | |
| "a sentence is excluded when, after punctuation removal, any word token " | |
| "contains a character other than a Greek letter or combining mark, or " | |
| "when no word token remains" | |
| ), | |
| "input_rows": len(rows), | |
| "output_rows": len(kept), | |
| "removed_rows": sum(removed.values()), | |
| "removed_by_author_and_source": { | |
| f"{author} ({source})": count for (author, source), count in sorted(removed.items()) | |
| }, | |
| "examples": examples, | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Canonical works | |
| # -------------------------------------------------------------------------- | |
| TLG_WORK = re.compile(r"^tlg\d{4}\.tlg\d{3}$") | |
| #: Project-specific work identifiers that name a work another project also | |
| #: contributes under its TLG identifier. | |
| CANONICAL_WORKS = { | |
| "pedalion:plato:crito": "tlg0059.tlg003", | |
| "pedalion:xenophon:memorabilia": "tlg0032.tlg002", | |
| "pedalion:lysias:on-the-refusal-of-a-pension": "tlg0540.tlg024", | |
| } | |
| CANONICAL_WORK_PATTERNS: list[tuple[re.Pattern[str], Callable[[re.Match[str]], str]]] = [ | |
| ( | |
| re.compile(r"^gorman:demosthenes:dem(?:osthenes)?-(\d+)-"), | |
| lambda match: f"tlg0014.tlg{int(match.group(1)):03d}", | |
| ), | |
| (re.compile(r"^gorman:xenophon:xen-cyr-"), lambda match: "tlg0032.tlg007"), | |
| ] | |
| def canonical_work(work_id: str) -> str: | |
| """The work a row belongs to, independent of which file or project holds it.""" | |
| if TLG_WORK.match(work_id): | |
| return work_id | |
| if work_id in CANONICAL_WORKS: | |
| return CANONICAL_WORKS[work_id] | |
| for pattern, resolve in CANONICAL_WORK_PATTERNS: | |
| match = pattern.match(work_id) | |
| if match: | |
| return resolve(match) | |
| return work_id | |
| def assign_canonical_works(rows: list[dict]) -> dict: | |
| counts: Counter[tuple[str, str]] = Counter() | |
| for row in rows: | |
| row["canonical_work"] = canonical_work(row["work_id"]) | |
| counts[(row["author"], row["canonical_work"])] += 1 | |
| merged = Counter() | |
| by_canonical: dict[tuple[str, str], set[str]] = defaultdict(set) | |
| for row in rows: | |
| by_canonical[(row["author"], row["canonical_work"])].add(row["work_id"]) | |
| for (author, work), ids in by_canonical.items(): | |
| if len(ids) > 1: | |
| merged[author] += 1 | |
| return { | |
| "works_per_author": { | |
| author: sum(1 for (a, _work) in counts if a == author) | |
| for author in sorted({a for a, _work in counts}) | |
| }, | |
| "authors_with_merged_file_works": dict(sorted(merged.items())), | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Passage-level near-duplicate removal | |
| # -------------------------------------------------------------------------- | |
| def _natural_key(value) -> tuple: | |
| text = "" if value is None else str(value) | |
| return tuple( | |
| (0, int(part)) if part.isdigit() else (1, part.casefold()) | |
| for part in re.split(r"(\d+)", text) if part | |
| ) | |
| def document_order_key(row: dict) -> tuple: | |
| records = row.get("source_records") or [] | |
| sentence_id = records[0].get("source_sentence_id", "") if records else "" | |
| return (_natural_key(row.get("passage")), _natural_key(sentence_id), row["id"]) | |
| def _source_file(row: dict) -> str: | |
| records = row.get("source_records") or [] | |
| return records[0].get("source_file", "") if records else "" | |
| def remove_near_duplicate_passages( | |
| rows: list[dict], | |
| *, | |
| shingle: int = NEAR_DUPLICATE_SHINGLE, | |
| containment: float = NEAR_DUPLICATE_CONTAINMENT, | |
| minimum_shared: int = NEAR_DUPLICATE_MINIMUM_SHARED, | |
| cross_author_containment: float = CROSS_AUTHOR_CONTAINMENT, | |
| cross_author_minimum_shared: int = CROSS_AUTHOR_MINIMUM_SHARED, | |
| example_limit: int = 30, | |
| ) -> tuple[list[dict], dict]: | |
| """Drop sentences that near-verbatim repeat a sentence held elsewhere. | |
| Two sentences of one author are near-duplicates when at least | |
| ``containment`` of the word ``shingle``-grams of either one occur in the | |
| other and at least ``minimum_shared`` do. That catches what exact | |
| deduplication missed: the same passage annotated by two projects with | |
| different sentence boundaries, crasis or tokenisation (Diodorus 11 in Gorman | |
| and UD Perseus; Herodotus 1 in PROIEL and UD Perseus). Across authors the | |
| bar is higher, ``cross_author_containment`` and | |
| ``cross_author_minimum_shared``, so that a quotation is caught but a stock | |
| phrase such as ὦ ἄνδρες δικασταί or a five-word epic formula is not. | |
| Decisions: | |
| * different author labels: every member is removed, as exact cross-author | |
| duplicates already were, because the text carries no label information; | |
| * same author, different projects: the passage is kept in one project only, | |
| the one with the better source priority (ties go to the project that | |
| contributes more of that author), and the other project's overlapping | |
| sentences are removed; a sentence of that project sitting between two | |
| removed neighbours in document order is removed with them, because a | |
| segmentation mismatch leaves such fragments behind; | |
| * same author, same project: kept. Formulaic self-repetition is the | |
| author's own text and is reported rather than removed. | |
| """ | |
| tokens = [shingle_tokens(row["text"]) for row in rows] | |
| shingles: list[set[tuple[str, ...]]] = [] | |
| for words in tokens: | |
| if len(words) >= shingle: | |
| shingles.append({tuple(words[i:i + shingle]) for i in range(len(words) - shingle + 1)}) | |
| else: | |
| shingles.append(set()) | |
| index: dict[tuple[str, ...], list[int]] = defaultdict(list) | |
| for position, grams in enumerate(shingles): | |
| for gram in grams: | |
| index[gram].append(position) | |
| author_source_rows: Counter[tuple[str, str]] = Counter( | |
| (row["author"], row["treebank_source"]) for row in rows | |
| ) | |
| def rank(position: int) -> tuple: | |
| row = rows[position] | |
| return ( | |
| SOURCE_PRIORITY.get(row["treebank_source"], 50), | |
| -author_source_rows[(row["author"], row["treebank_source"])], | |
| row["treebank_source"], | |
| ) | |
| pairs: set[tuple[int, int]] = set() | |
| for position, grams in enumerate(shingles): | |
| if not grams: | |
| continue | |
| hits: Counter[int] = Counter() | |
| for gram in grams: | |
| for other in index[gram]: | |
| if other != position: | |
| hits[other] += 1 | |
| for other, shared in hits.items(): | |
| same_author = rows[position]["author"] == rows[other]["author"] | |
| if same_author: | |
| enough = shared >= minimum_shared and shared / len(grams) >= containment | |
| else: | |
| enough = ( | |
| shared >= cross_author_minimum_shared | |
| and shared / len(grams) >= cross_author_containment | |
| ) | |
| if enough: | |
| pairs.add((min(position, other), max(position, other))) | |
| removed: dict[int, str] = {} | |
| self_repetition_pairs = 0 | |
| examples: list[dict] = [] | |
| pair_sources: Counter[tuple[str, str, str]] = Counter() | |
| for first, second in sorted(pairs): | |
| a, b = rows[first], rows[second] | |
| if a["author"] != b["author"]: | |
| for position in (first, second): | |
| removed.setdefault(position, "cross_author") | |
| reason = "cross_author" | |
| elif a["treebank_source"] == b["treebank_source"]: | |
| self_repetition_pairs += 1 | |
| continue | |
| else: | |
| keep, drop = (first, second) if rank(first) <= rank(second) else (second, first) | |
| removed.setdefault(drop, "cross_source") | |
| pair_sources[(a["author"], rows[keep]["treebank_source"], rows[drop]["treebank_source"])] += 1 | |
| reason = "cross_source" | |
| if len(examples) < example_limit: | |
| examples.append({ | |
| "reason": reason, | |
| "authors": sorted({a["author"], b["author"]}), | |
| "sources": [a["treebank_source"], b["treebank_source"]], | |
| "texts": [a["text"][:90], b["text"][:90]], | |
| }) | |
| # Passage fill: a surviving sentence between two removed neighbours of the | |
| # same document is a segmentation fragment of the same passage. | |
| documents: dict[tuple[str, str, str], list[int]] = defaultdict(list) | |
| for position, row in enumerate(rows): | |
| documents[(row["author"], row["treebank_source"], _source_file(row))].append(position) | |
| filled = 0 | |
| for positions in documents.values(): | |
| ordered = sorted(positions, key=lambda p: document_order_key(rows[p])) | |
| for i in range(1, len(ordered) - 1): | |
| middle = ordered[i] | |
| if middle in removed: | |
| continue | |
| before, after = ordered[i - 1], ordered[i + 1] | |
| if removed.get(before) == "cross_source" and removed.get(after) == "cross_source": | |
| removed[middle] = "passage_fill" | |
| filled += 1 | |
| kept = [row for position, row in enumerate(rows) if position not in removed] | |
| by_reason = Counter(removed.values()) | |
| by_author: dict[str, Counter] = defaultdict(Counter) | |
| for position, reason in removed.items(): | |
| by_author[rows[position]["author"]][reason] += 1 | |
| return kept, { | |
| "policy": ( | |
| f"word {shingle}-gram containment >= {containment} in either direction; " | |
| "cross-author near-duplicates removed entirely; same-author cross-project " | |
| "near-duplicates kept in the higher-priority project only, with single " | |
| "surviving sentences between two removed neighbours removed as passage " | |
| "fragments; same-project repetition kept" | |
| ), | |
| "shingle": shingle, | |
| "containment": containment, | |
| "minimum_shared_shingles": minimum_shared, | |
| "cross_author_containment": cross_author_containment, | |
| "cross_author_minimum_shared_shingles": cross_author_minimum_shared, | |
| "input_rows": len(rows), | |
| "output_rows": len(kept), | |
| "removed_rows": len(removed), | |
| "removed_by_reason": dict(by_reason), | |
| "removed_by_author": { | |
| author: dict(counter) for author, counter in sorted(by_author.items()) | |
| }, | |
| "cross_source_pairs_by_kept_and_dropped_project": { | |
| f"{author}: kept {kept_source}, dropped {dropped_source}": count | |
| for (author, kept_source, dropped_source), count in sorted(pair_sources.items()) | |
| }, | |
| "passage_fill_rows": filled, | |
| "same_project_repetition_pairs_kept": self_repetition_pairs, | |
| "examples": examples, | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Splits | |
| # -------------------------------------------------------------------------- | |
| def split_counts(n: int) -> dict[str, int]: | |
| if n < 3: | |
| return {"train": n, "validation": 0, "validation2": 0, "test": 0} | |
| validation = max(1, round(n * SPLIT_FRACTIONS["validation"])) | |
| test = max(1, round(n * SPLIT_FRACTIONS["test"])) | |
| validation2 = round(n * SPLIT_FRACTIONS["validation2"]) if n >= 10 else 0 | |
| return { | |
| "train": n - validation - validation2 - test, | |
| "validation": validation, | |
| "validation2": validation2, | |
| "test": test, | |
| } | |
| def split_labels(n: int) -> list[str]: | |
| counts = split_counts(n) | |
| return [split for split in SPLITS for _ in range(counts[split])] | |
| def split_group_key(row: dict) -> tuple[str, str]: | |
| return (row["author"], row.get("canonical_work") or row["work_id"]) | |
| def assign_splits(rows: list[dict], *, seed: int = RANDOM_SEED) -> None: | |
| """Independent stratification inside every (author, canonical work) group.""" | |
| groups: dict[tuple[str, str], list[dict]] = defaultdict(list) | |
| for row in rows: | |
| groups[split_group_key(row)].append(row) | |
| rng = 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 | |
| # -------------------------------------------------------------------------- | |
| # Work-held-out track | |
| # -------------------------------------------------------------------------- | |
| def work_held_out_rows( | |
| rows: list[dict], *, seed: int = RANDOM_SEED, authors: Iterable[str] | None = None, | |
| ) -> tuple[list[dict], dict]: | |
| """Hold out whole works as test data, inside an annotation project. | |
| For each author the candidate works are those with at least | |
| ``WORK_HELD_OUT_MINIMUM_TEST_ROWS`` sentences, at most | |
| ``WORK_HELD_OUT_MAXIMUM_FRACTION`` of the author's sentences, and annotated | |
| by a project that also annotates another work of the author, so that the | |
| test work differs from training in text but not in annotator. The | |
| candidate closest to ``WORK_HELD_OUT_TARGET_FRACTION`` of the author's rows | |
| is the test work. | |
| A second whole work is then held out for selection when one qualifies: | |
| at least ``WORK_HELD_OUT_VALIDATION_MINIMUM_ROWS`` rows, at most half of | |
| the author, closest to ``WORK_HELD_OUT_VALIDATION_TARGET_FRACTION``, and | |
| leaving the training works at least ``WORK_HELD_OUT_MINIMUM_TRAIN_ROWS`` | |
| rows and a project shared with the test work. Its rows become | |
| ``validation`` and ``validation2``, so model selection is out-of-work too. | |
| Without such a work, validation and validation2 are random sentences of | |
| the training works, as in the second edition, and the row says so in | |
| ``held_out_validation_work`` being null. | |
| Every row also carries ``held_out_genre``, the literary genre of the | |
| author's test work, and ``held_out_group``: ``rival`` when another | |
| retained author of the track has a work of that genre, ``singleton`` | |
| otherwise. The singletons measure genre identification, not attribution, | |
| and the leaderboard reports the two halves apart. | |
| """ | |
| if authors is not None: | |
| wanted = set(authors) | |
| rows = [row for row in rows if row["author"] in wanted] | |
| by_author: dict[str, dict[str, list[dict]]] = defaultdict(lambda: defaultdict(list)) | |
| for row in rows: | |
| by_author[row["author"]][row.get("canonical_work") or row["work_id"]].append(row) | |
| selected: list[dict] = [] | |
| decisions: dict[str, dict] = {} | |
| rejected: dict[str, dict] = {} | |
| for author in sorted(by_author): | |
| works = by_author[author] | |
| total = sum(len(work_rows) for work_rows in works.values()) | |
| sources_by_work = { | |
| work: Counter(row["treebank_source"] for row in work_rows) | |
| for work, work_rows in works.items() | |
| } | |
| if len(works) < 2: | |
| rejected[author] = {"reason": "only one work", "rows": total} | |
| continue | |
| candidates = [] | |
| for work, work_rows in works.items(): | |
| size = len(work_rows) | |
| if size < WORK_HELD_OUT_MINIMUM_TEST_ROWS or size > WORK_HELD_OUT_MAXIMUM_FRACTION * total: | |
| continue | |
| other_sources = { | |
| source for other, counter in sources_by_work.items() if other != work | |
| for source in counter | |
| } | |
| shared = set(sources_by_work[work]) & other_sources | |
| if not shared: | |
| continue | |
| candidates.append((abs(size - WORK_HELD_OUT_TARGET_FRACTION * total), work, size, sorted(shared))) | |
| if not candidates: | |
| rejected[author] = { | |
| "reason": ( | |
| "no work between the minimum and maximum size whose project also " | |
| "annotates another work of the author" | |
| ), | |
| "works": { | |
| work: {"rows": len(work_rows), "sources": dict(sources_by_work[work])} | |
| for work, work_rows in sorted(works.items()) | |
| }, | |
| } | |
| continue | |
| candidates.sort() | |
| _distance, held_out, held_out_size, shared_sources = candidates[0] | |
| held_out_rows = works[held_out] | |
| title = Counter(row["work"] for row in held_out_rows).most_common(1)[0][0] | |
| # The selection work: whole, out-of-work, and never the test work. | |
| validation_candidates = [] | |
| for work, work_rows in works.items(): | |
| size = len(work_rows) | |
| if work == held_out or size < WORK_HELD_OUT_VALIDATION_MINIMUM_ROWS: | |
| continue | |
| if size > WORK_HELD_OUT_MAXIMUM_FRACTION * total: | |
| continue | |
| training = [other for other in works if other not in (work, held_out)] | |
| training_rows = sum(len(works[other]) for other in training) | |
| training_sources = { | |
| source for other in training for source in sources_by_work[other] | |
| } | |
| if training_rows < WORK_HELD_OUT_MINIMUM_TRAIN_ROWS: | |
| continue | |
| if not (set(sources_by_work[held_out]) & training_sources): | |
| continue | |
| validation_candidates.append(( | |
| abs(size - WORK_HELD_OUT_VALIDATION_TARGET_FRACTION * total), work, size, | |
| )) | |
| validation_work = validation_title = None | |
| assignment: dict[str, str] = {} | |
| if validation_candidates: | |
| validation_candidates.sort() | |
| _distance, validation_work, validation_size = validation_candidates[0] | |
| validation_title = Counter( | |
| row["work"] for row in works[validation_work] | |
| ).most_common(1)[0][0] | |
| validation_rows = sorted(works[validation_work], key=lambda row: row["id"]) | |
| rng = random.Random(f"{seed}:work-held-out-validation:{author}") | |
| rng.shuffle(validation_rows) | |
| n_validation2 = max( | |
| WORK_HELD_OUT_MINIMUM_VALIDATION2_ROWS, | |
| min(round(validation_size / 3), validation_size - WORK_HELD_OUT_MINIMUM_VALIDATION_ROWS), | |
| ) | |
| for row in validation_rows[:n_validation2]: | |
| assignment[row["id"]] = "validation2" | |
| for row in validation_rows[n_validation2:]: | |
| assignment[row["id"]] = "validation" | |
| n_validation = validation_size - n_validation2 | |
| remaining = sorted( | |
| ( | |
| row for work, work_rows in works.items() | |
| if work not in (held_out, validation_work) for row in work_rows | |
| ), | |
| key=lambda row: row["id"], | |
| ) | |
| selection_policy = "whole work held out" | |
| else: | |
| remaining = sorted( | |
| (row for work, work_rows in works.items() if work != held_out for row in work_rows), | |
| key=lambda row: row["id"], | |
| ) | |
| rng = random.Random(f"{seed}:work-held-out:{author}") | |
| rng.shuffle(remaining) | |
| n_validation = round(total * SPLIT_FRACTIONS["validation"]) | |
| n_validation2 = round(total * SPLIT_FRACTIONS["validation2"]) | |
| for row in remaining[:n_validation]: | |
| assignment[row["id"]] = "validation" | |
| for row in remaining[n_validation:n_validation + n_validation2]: | |
| assignment[row["id"]] = "validation2" | |
| selection_policy = "random sentences of the training works" | |
| extra = { | |
| "held_out_work": held_out, "held_out_work_title": title, | |
| "held_out_validation_work": validation_work, | |
| "held_out_validation_work_title": validation_title, | |
| "held_out_genre": work_genre(held_out_rows[0]), | |
| } | |
| for row in remaining: | |
| selected.append({**row, "split": assignment.get(row["id"], "train"), **extra}) | |
| if validation_work is not None: | |
| for row in works[validation_work]: | |
| selected.append({**row, "split": assignment[row["id"]], **extra}) | |
| for row in held_out_rows: | |
| selected.append({**row, "split": "test", **extra}) | |
| decisions[author] = { | |
| "held_out_work": held_out, | |
| "held_out_work_title": title, | |
| "held_out_work_sources": dict(sources_by_work[held_out]), | |
| "held_out_genre": extra["held_out_genre"], | |
| "shared_sources_with_training": shared_sources, | |
| "validation_work": validation_work, | |
| "validation_work_title": validation_title, | |
| "selection_policy": selection_policy, | |
| "training_works": sorted( | |
| work for work in works if work not in (held_out, validation_work) | |
| ), | |
| "rows": { | |
| "train": sum(1 for row in remaining if assignment.get(row["id"], "train") == "train"), | |
| "validation": n_validation, | |
| "validation2": n_validation2, | |
| "test": held_out_size, | |
| }, | |
| } | |
| # Rivals: another retained author of the track writes the held-out genre. | |
| genres_by_author: dict[str, set[str]] = defaultdict(set) | |
| for row in selected: | |
| genres_by_author[row["author"]].add(work_genre(row)) | |
| for author, decision in decisions.items(): | |
| genre = decision["held_out_genre"] | |
| rivals = sorted( | |
| other for other, genres in genres_by_author.items() | |
| if other != author and genre in genres | |
| ) | |
| decision["rivals"] = rivals | |
| decision["group"] = "rival" if rivals else "singleton" | |
| for row in selected: | |
| row["held_out_group"] = decisions[row["author"]]["group"] | |
| selected.sort(key=lambda row: row["id"]) | |
| return selected, { | |
| "policy": ( | |
| "hold out one whole work per author as test data, chosen among works of " | |
| f"{WORK_HELD_OUT_MINIMUM_TEST_ROWS}+ rows and at most " | |
| f"{WORK_HELD_OUT_MAXIMUM_FRACTION:.0%} of the author, annotated by a project " | |
| "that also annotates another work of the author, closest to " | |
| f"{WORK_HELD_OUT_TARGET_FRACTION:.0%} of the author's rows; a second whole " | |
| f"work of {WORK_HELD_OUT_VALIDATION_MINIMUM_ROWS}+ rows closest to " | |
| f"{WORK_HELD_OUT_VALIDATION_TARGET_FRACTION:.0%} is held out as validation " | |
| "and validation2 when the training works keep " | |
| f"{WORK_HELD_OUT_MINIMUM_TRAIN_ROWS}+ rows and the test work's project; " | |
| "otherwise validation and validation2 are random sentences of the " | |
| "training works" | |
| ), | |
| "groups": ( | |
| "rival: another retained author of the track has a work of the held-out " | |
| "work's genre; singleton: none has, so the cell measures genre " | |
| "identification" | |
| ), | |
| "seed": seed, | |
| "retained_authors": sorted(decisions), | |
| "rival_authors": sorted(a for a, d in decisions.items() if d["group"] == "rival"), | |
| "singleton_authors": sorted(a for a, d in decisions.items() if d["group"] == "singleton"), | |
| "author_decisions": decisions, | |
| "excluded_authors": rejected, | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Period-and-genre-matched tracks | |
| # -------------------------------------------------------------------------- | |
| def genre_track_rows(rows: list[dict], authors: Iterable[str]) -> list[dict]: | |
| wanted = set(authors) | |
| return [row for row in rows if row["author"] in wanted] | |
| def genre_work_held_out_rows( | |
| rows: list[dict], *, seed: int = RANDOM_SEED, | |
| ) -> tuple[dict[str, list[dict]], dict]: | |
| """A work-held-out version of every matched track that can have one. | |
| The matched tracks answer how far genre and period carry attribution; their | |
| work-held-out versions answer how far topic does, since every label there | |
| is tested on a work it never trained on, and they hold one annotation | |
| project only, so that the annotator is matched as well. A track is built | |
| when at least two of its authors have a qualifying held-out work in that | |
| project; the others are reported with the reason (Euripides, Appian, the | |
| Homeric corpora and most imperial historians are single works). | |
| """ | |
| built: dict[str, list[dict]] = {} | |
| report: dict[str, dict] = {} | |
| for track, authors in GENRE_TRACKS.items(): | |
| wanted = set(authors) | |
| track_rows = [row for row in rows if row["author"] in wanted] | |
| # One annotator as well as one genre and one period: the track keeps | |
| # the project that annotates most of its rows and nothing else, so | |
| # that a label cannot be read off the mix of projects behind it (the | |
| # first build of this track let a markup-only floor reach 89 macro-F1 | |
| # on the tragedians because Sophocles alone had UD Perseus rows). | |
| project, _count = Counter(row["treebank_source"] for row in track_rows).most_common(1)[0] \ | |
| if track_rows else (None, 0) | |
| project_rows = [row for row in track_rows if row["treebank_source"] == project] | |
| selected, decisions = work_held_out_rows(project_rows, seed=seed, authors=authors) | |
| name = f"{track}_work_held_out" | |
| decisions["project"] = project | |
| decisions["rows_of_other_projects_dropped"] = dict(Counter( | |
| row["treebank_source"] for row in track_rows if row["treebank_source"] != project | |
| )) | |
| if len(decisions["retained_authors"]) >= 2: | |
| built[name] = selected | |
| report[name] = {"built": True, **decisions} | |
| else: | |
| report[name] = { | |
| "built": False, | |
| "reason": ( | |
| f"{len(decisions['retained_authors'])} of the track's authors have " | |
| f"a work of the track's project ({project}) that can be held out; " | |
| "a track needs two" | |
| ), | |
| **decisions, | |
| } | |
| return built, report | |
| def metre_track_rows(rows: list[dict]) -> dict[str, list[dict]]: | |
| """The metre publication's matched tracks, by internal base configuration. | |
| ``verse_hexameter`` is the three archaic poets of the sentence publication's | |
| ``archaic_epic`` track, so both publications put the same question to the same | |
| labels and their scores may be read against each other. ``verse_hexameter_all`` | |
| is instead every hexameter line in the corpus, fourteen poets from Homer to | |
| Nonnus: it matches the genre across eight centuries rather than matching the | |
| period, and it is the only track here on which the metre itself carries no | |
| information about the author, since Callimachus' elegiac couplets, | |
| Theognis' pentameters, Theocritus' lyric and the whole of Aeschylus, Pindar | |
| and Lycophron leave it. | |
| """ | |
| return { | |
| "verse_hexameter": genre_track_rows(rows, GENRE_TRACKS["archaic_epic"]), | |
| "verse_hexameter_all": [row for row in rows if row["metre"] == HEXAMETER], | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Uniform machine syntax layer | |
| # -------------------------------------------------------------------------- | |
| MACHINE_TOKEN_FIELDS = ("id", "form", "lemma", "upos", "feats", "head", "deprel") | |
| def load_machine_parses(path: Path) -> dict[str, list[dict]]: | |
| parses: dict[str, list[dict]] = {} | |
| with Path(path).open(encoding="utf-8") as stream: | |
| for line in stream: | |
| if line.strip(): | |
| record = json.loads(line) | |
| parses[record["text"]] = record["conllu"] | |
| if not parses: | |
| raise ValueError(f"{path} holds no parses") | |
| return parses | |
| def _transfer_lemmas(human: list[dict], machine: list[dict], stats: Counter) -> list[dict]: | |
| """Give every machine token the human lemma of the same word. | |
| Lemmas are the one layer of the human annotation that is not convention- | |
| bound, so the machine layer carries them rather than the parser's own. Both | |
| layers tokenise the published text on whitespace, so alignment is by | |
| position whenever the forms agree and by longest common subsequence of | |
| forms otherwise; a machine token with no human counterpart keeps its form | |
| as lemma and is counted. | |
| """ | |
| output = [] | |
| if len(human) == len(machine) and all(h["form"] == m["form"] for h, m in zip(human, machine)): | |
| pairs = list(zip(machine, human)) | |
| stats["tokens_aligned_by_position"] += len(pairs) | |
| else: | |
| matcher = difflib.SequenceMatcher( | |
| a=[m["form"] for m in machine], b=[h["form"] for h in human], autojunk=False, | |
| ) | |
| partner: dict[int, dict] = {} | |
| for tag, i1, i2, j1, j2 in matcher.get_opcodes(): | |
| if tag == "equal": | |
| for offset in range(i2 - i1): | |
| partner[i1 + offset] = human[j1 + offset] | |
| pairs = [(m, partner.get(i)) for i, m in enumerate(machine)] | |
| stats["tokens_aligned_by_sequence"] += sum(1 for _m, h in pairs if h is not None) | |
| stats["tokens_without_human_lemma"] += sum(1 for _m, h in pairs if h is None) | |
| for m, h in pairs: | |
| token = {field: m.get(field) for field in MACHINE_TOKEN_FIELDS} | |
| # A human lemma can be empty where the source project gave none; the | |
| # CoNLL-U placeholder keeps the two layers' conventions identical. | |
| token["lemma"] = (h["lemma"] or "_") if h is not None else m["form"] | |
| if token["feats"] in ("", "_"): | |
| token["feats"] = None | |
| output.append(token) | |
| # The parser learned both of its training treebanks' cc conventions; the | |
| # published layer follows the one the human layer is reduced to. | |
| heads = normalize_cc_heads( | |
| [t["id"] for t in output], [t["head"] for t in output], [t["deprel"] for t in output], | |
| ) | |
| for token, head in zip(output, heads): | |
| stats["cc_heads_normalized"] += token["head"] != head | |
| token["head"] = head | |
| return output | |
| #: Open-class tags whose tokens the content-masked text replaces. Stamatatos' | |
| #: text distortion masks content words so that what remains is the author's | |
| #: function words and the shape of the sentence; here the parser's uniform | |
| #: UPOS decides what is content, so the masking is the same for every author. | |
| #: ADV is kept: the negations οὐ and μή are adverbs in UD, and they are style. | |
| DISTORTED_UPOS = frozenset({"NOUN", "PROPN", "ADJ", "VERB"}) | |
| def distorted_text(tokens: list[dict]) -> str: | |
| """The content-masked text of one machine-parsed sentence.""" | |
| return " ".join( | |
| token["upos"] if token["upos"] in DISTORTED_UPOS else token["form"] | |
| for token in tokens | |
| ) | |
| def check_machine_sentence(tokens: list[dict], where: str) -> None: | |
| ids = [token["id"] for token in tokens] | |
| assert ids == list(range(1, len(ids) + 1)), f"{where}: machine token ids are not contiguous" | |
| heads = [token["head"] for token in tokens] | |
| assert heads.count(0) == 1, f"{where}: machine tree has {heads.count(0)} roots" | |
| assert all(0 <= head <= len(ids) for head in heads), f"{where}: machine head outside sentence" | |
| def attach_machine_conllu(rows: list[dict], parses: dict[str, list[dict]]) -> dict: | |
| """Add ``conllu_machine`` beside the finalized human ``conllu`` of every row.""" | |
| stats: Counter = Counter() | |
| missing: list[str] = [] | |
| for row in rows: | |
| units = row["text"] if isinstance(row["text"], list) else [row["text"]] | |
| human_units = row["conllu"] | |
| assert len(units) == len(human_units), f"row {row['id']}: text/conllu unit mismatch" | |
| machine_units = [] | |
| distorted_units = [] | |
| for unit_text, human_unit in zip(units, human_units): | |
| tokens = parses.get(unit_text) | |
| if tokens is None: | |
| missing.append(unit_text) | |
| continue | |
| flat_human = [token for sentence in human_unit for token in sentence] | |
| machine = _transfer_lemmas(flat_human, tokens, stats) | |
| check_machine_sentence(machine, f"row {row['id']}") | |
| machine_units.append([machine]) | |
| distorted_units.append(distorted_text(machine)) | |
| stats["units"] += 1 | |
| row["conllu_machine"] = machine_units | |
| row["text_distorted"] = distorted_units | |
| stats["rows"] += 1 | |
| if missing: | |
| stats["missing_units"] = len(missing) | |
| raise MissingMachineParses(sorted(set(missing)), dict(stats)) | |
| return dict(stats) | |
| class MissingMachineParses(RuntimeError): | |
| def __init__(self, texts: list[str], stats: dict): | |
| super().__init__(f"{len(texts)} distinct text units have no machine parse") | |
| self.texts = texts | |
| self.stats = stats | |