Datasets:
Tasks:
Text Classification
Formats:
parquet
Languages:
Ancient Greek (to 1453)
Size:
100K - 1M
ArXiv:
License:
Download scripts/validate_publication.py from Urdatorn/sphragis: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/validate_publication.py
- Command line
-
hf download hf://datasets/Urdatorn/sphragis/scripts/validate_publication.py
-
curl -L -o validate_publication.py https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/validate_publication.py
13.1 kB
| #!/usr/bin/env python3 | |
| """Independently validate one final Sphragis publication.""" | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import re | |
| import unicodedata | |
| import pyarrow.parquet as pq | |
| try: | |
| from scripts.conllu_units import load_conllu_units, render_conllu | |
| from scripts.metre_units import load_metre_units, load_syllable_units | |
| from scripts.text_units import load_text_units | |
| from scripts.syntax_normalization import ( | |
| is_editorial_punctuation, | |
| is_universal_deprel, | |
| syntax_text_normalize, | |
| ) | |
| from scripts.model_facing import ( | |
| check_model_facing_conllu, | |
| lower_greek, | |
| ) | |
| from scripts.vendor.conll18_ud_eval import UDError, load_conllu | |
| from scripts.tracks import HEXAMETER, SPLITS, check_machine_sentence | |
| from scripts.dataset_variants import ( | |
| METRE_BASE_CONFIGS, | |
| PUBLIC_CONFIG_PREFIX, | |
| SENTENCE_BASE_CONFIGS, | |
| track_of_config, | |
| ) | |
| except ModuleNotFoundError: | |
| from conllu_units import load_conllu_units, render_conllu | |
| from metre_units import load_metre_units, load_syllable_units | |
| from text_units import load_text_units | |
| from syntax_normalization import ( | |
| is_editorial_punctuation, | |
| is_universal_deprel, | |
| syntax_text_normalize, | |
| ) | |
| from model_facing import ( | |
| check_model_facing_conllu, | |
| lower_greek, | |
| ) | |
| from vendor.conll18_ud_eval import UDError, load_conllu | |
| from tracks import HEXAMETER, SPLITS, check_machine_sentence | |
| from dataset_variants import ( | |
| METRE_BASE_CONFIGS, | |
| PUBLIC_CONFIG_PREFIX, | |
| SENTENCE_BASE_CONFIGS, | |
| track_of_config, | |
| ) | |
| def check_work_held_out(config: str, rows: list[dict]) -> None: | |
| """Assert every author's test data is whole works unseen in training, | |
| annotated by a project that also annotates that author's training works.""" | |
| works: dict[str, dict[str, set[str]]] = {} | |
| sources: dict[str, dict[str, set[str]]] = {} | |
| held_out: dict[str, set[str]] = {} | |
| for row in rows: | |
| provenance = row.get("constituent_provenance") | |
| if provenance: | |
| row_works = {record["canonical_work"] for record in provenance} | |
| row_sources = {record["treebank_source"] for record in provenance} | |
| else: | |
| row_works = {row["canonical_work"]} | |
| row_sources = {row["treebank_source"]} | |
| works.setdefault(row["author"], {}).setdefault(row["split"], set()).update(row_works) | |
| sources.setdefault(row["author"], {}).setdefault(row["split"], set()).update(row_sources) | |
| held_out.setdefault(row["author"], set()).add(row["held_out_work"]) | |
| for author, by_split in sorted(works.items()): | |
| assert len(held_out[author]) == 1, (config, author, held_out[author]) | |
| work = next(iter(held_out[author])) | |
| assert by_split.get("test") == {work}, (config, author, sorted(by_split.get("test", ())), work) | |
| for split in ("train", "validation", "validation2"): | |
| assert work not in by_split.get(split, set()), (config, author, split, work) | |
| assert by_split.get("train"), (config, author) | |
| assert sources[author]["test"] & sources[author]["train"], ( | |
| config, author, sorted(sources[author]["test"]), sorted(sources[author]["train"]), | |
| ) | |
| def normalize(value: str) -> str: | |
| return "".join( | |
| character | |
| for character in unicodedata.normalize( | |
| "NFD", value.lower().replace("ς", "σ") | |
| ) | |
| if unicodedata.category(character) != "Mn" and character.isalpha() | |
| ) | |
| def configs(publication: str) -> tuple[str, ...]: | |
| suffixes = (1, 5, 10) | |
| if publication == "sentence": | |
| return tuple( | |
| f"{base}_{suffix}" for base in SENTENCE_BASE_CONFIGS for suffix in suffixes | |
| ) | |
| return tuple( | |
| f"{PUBLIC_CONFIG_PREFIX[base]}_{suffix}" | |
| for base in METRE_BASE_CONFIGS | |
| for suffix in suffixes | |
| ) | |
| def read_config(root: Path, config: str) -> list[dict]: | |
| rows = [] | |
| schema = None | |
| for split in SPLITS: | |
| path = root / config / f"{split}-00000-of-00001.parquet" | |
| parquet = pq.ParquetFile(path) | |
| schema = parquet.schema_arrow if schema is None else schema | |
| assert parquet.schema_arrow == schema | |
| split_rows = parquet.read(use_threads=False).to_pylist() | |
| assert all(row["split"] == split for row in split_rows) | |
| rows.extend(split_rows) | |
| return rows | |
| def validate_conllu(config: str, row: dict, checked: set[bytes], column: str = "conllu") -> None: | |
| text_units = load_text_units(row["text"]) | |
| native_units = row["native_syntax"] | |
| conllu_units = load_conllu_units(row[column]) | |
| assert len(native_units) == len(conllu_units) | |
| assert len(text_units) == len(conllu_units) | |
| for index, unit in enumerate(conllu_units): | |
| where = f"{config}, row {row['id']}" | |
| check_model_facing_conllu(unit, where) | |
| forms = "".join(token["form"] for sentence in unit for token in sentence) | |
| assert syntax_text_normalize(forms) == syntax_text_normalize(text_units[index]) | |
| for record in native_units[index]: | |
| sentence = unit[record["sentence"]] | |
| assert 1 <= record["token"] <= len(sentence), (config, row["id"], record) | |
| # The published structure has to render back to CoNLL-U the official | |
| # shared-task parser accepts. | |
| rendered = render_conllu(unit) | |
| digest = hashlib.sha256(rendered.encode("utf-8")).digest() | |
| if digest in checked: | |
| continue | |
| try: | |
| load_conllu(io.StringIO(rendered)) | |
| except UDError as error: | |
| raise AssertionError( | |
| f"Malformed CoNLL-U in {config}, row {row['id']}: {error}" | |
| ) from error | |
| checked.add(digest) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--data", type=Path, required=True) | |
| parser.add_argument( | |
| "--publication", choices=("sentence", "metre"), required=True, | |
| ) | |
| args = parser.parse_args() | |
| expected_configs = configs(args.publication) | |
| actual_configs = {path.name for path in args.data.iterdir() if path.is_dir()} | |
| assert actual_configs == set(expected_configs) | |
| rows_by_config = { | |
| config: read_config(args.data, config) for config in expected_configs | |
| } | |
| checked_conllu: set[bytes] = set() | |
| conllu_column = "conllu_human" if args.publication == "sentence" else "conllu" | |
| for config, rows in rows_by_config.items(): | |
| suffix = int(config.rsplit("_", 1)[1]) | |
| if args.publication == "sentence": | |
| assert {row["genre"] for row in rows} <= {"prose", "verse"} | |
| else: | |
| assert all("genre" not in row for row in rows) | |
| assert {row["syntax_annotation"] for row in rows} == {"predicted"} | |
| assert {row["treebank_source"] for row in rows} == { | |
| "stoicheia_tagger_parser" | |
| } | |
| if args.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(rows[0])) | |
| ids = [row["id"] for row in rows] | |
| assert len(ids) == len(set(ids)) | |
| for row in rows: | |
| text_units = load_text_units(row["text"]) | |
| assert len(text_units) == suffix | |
| assert len(load_conllu_units(row[conllu_column])) == suffix | |
| if args.publication == "sentence": | |
| assert "conllu" not in row | |
| machine_units = load_conllu_units(row["conllu_machine"]) | |
| assert len(machine_units) == suffix | |
| for unit in machine_units: | |
| for sentence in unit: | |
| check_machine_sentence(sentence, f"{config}, row {row['id']}") | |
| assert all(token["lemma"] is not None for token in sentence) | |
| if suffix != 1: | |
| assert row["chunk_size"] == suffix | |
| assert row["chunk_target_size"] == suffix | |
| assert len(row["constituent_ids"]) == suffix | |
| validate_conllu(config, row, checked_conllu, conllu_column) | |
| if args.publication == "sentence": | |
| assert all( | |
| record["source"] != "hypotactic" | |
| for record in row["source_records"] | |
| ) | |
| else: | |
| metre_units = load_metre_units(row["metre"]) | |
| syllable_units = load_syllable_units(row["syllables"]) | |
| assert len(metre_units) == suffix | |
| assert len(syllable_units) == suffix | |
| if track_of_config(config) != "verse": | |
| assert set(metre_units) == {HEXAMETER}, ( | |
| f"{config}, row {row['id']}: a hexameter track holds " | |
| f"{sorted(set(metre_units))}" | |
| ) | |
| for text, line, unit in zip( | |
| text_units, syllable_units, load_conllu_units(row["conllu"]), | |
| ): | |
| forms = " ".join( | |
| token["form"] for sentence in unit for token in sentence | |
| ) | |
| assert text == forms, ( | |
| f"{config}, row {row['id']}: text is not the joined CoNLL-U forms" | |
| ) | |
| transcription = "".join( | |
| syllable["text"] for syllable in line["syllables"] | |
| ) | |
| assert syntax_text_normalize(transcription) == syntax_text_normalize(text), ( | |
| f"{config}, row {row['id']}: syllables do not transcribe the text" | |
| ) | |
| for syllable in line["syllables"]: | |
| assert syllable["quantity"] in {"long", "short"} | |
| assert set(syllable["features"]) <= {"caesura", "hiatus"}, ( | |
| f"{config}, row {row['id']}: upstream syllable class " | |
| f"published: {syllable['features']}" | |
| ) | |
| for row in rows: | |
| for unit in load_text_units(row["text"]): | |
| assert unit == lower_greek(unit), ( | |
| f"{config}, row {row['id']}: text is not lowercased" | |
| ) | |
| assert not any( | |
| is_editorial_punctuation(character) for character in unit | |
| ), f"{config}, row {row['id']}: text retains editorial punctuation" | |
| if config.rsplit("_", 1)[0].endswith("work_held_out"): | |
| check_work_held_out(config, rows) | |
| print(config, len(rows), dict(Counter(row["split"] for row in rows))) | |
| if args.publication == "metre": | |
| # Per track, not once: a feature restricted to some of the poets of a | |
| # track names the author on that track whatever it does on the others. | |
| for base in METRE_BASE_CONFIGS: | |
| track = PUBLIC_CONFIG_PREFIX[base] | |
| atomic = rows_by_config[f"{track}_1"] | |
| authors = {row["author"] for row in atomic} | |
| feature_authors = {"caesura": set(), "hiatus": set()} | |
| for row in atomic: | |
| for line in load_syllable_units(row["syllables"]): | |
| for syllable in line["syllables"]: | |
| for feature in feature_authors.keys() & set(syllable["features"]): | |
| feature_authors[feature].add(row["author"]) | |
| assert feature_authors == { | |
| "caesura": authors, | |
| "hiatus": authors, | |
| } | |
| print( | |
| f"{track}: derived boundary feature author coverage", | |
| {feature: len(covered) for feature, covered in feature_authors.items()}, | |
| ) | |
| for track in sorted({track_of_config(config) for config in expected_configs}): | |
| track_atomic = rows_by_config[f"{track}_1"] | |
| for config in expected_configs: | |
| if track_of_config(config) != track or config == f"{track}_1": | |
| continue | |
| for split in SPLITS: | |
| expected_ids = { | |
| row["id"] for row in track_atomic if row["split"] == split | |
| } | |
| represented_ids = [ | |
| constituent_id | |
| for row in rows_by_config[config] | |
| 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 | |
| print("validated unique CoNLL-U documents", len(checked_conllu)) | |
| print("all publication checks passed") | |
| if __name__ == "__main__": | |
| main() | |