from collections import Counter, defaultdict import json from pathlib import Path import re import pyarrow.parquet as pq import pytest from scripts.build_dataset import HypotacticParser from scripts.conllu_units import load_conllu_units from scripts.metre_units import ( line_features, load_metre_units, load_syllable_units, syllable_line, ) from scripts.dataset_variants import ( BOTTLENECK_TARGET, ELIGIBILITY_MINIMUM, METRE_BASE_CONFIGS, PUBLIC_CONFIG_PREFIX, SENTENCE_BASE_CONFIGS, ) from scripts.metrical_lines import PUBLIC_METRICAL_LINE_FIELD_SET, sanitize_metrical_lines from scripts.text_units import load_text_units REPO_ROOT = Path(__file__).resolve().parents[1] METRE_ROOT = REPO_ROOT.parent / "sphragis-metre" SPLITS = ("train", "validation", "validation2", "test") METRE_TRACKS = tuple(PUBLIC_CONFIG_PREFIX[base] for base in METRE_BASE_CONFIGS) PUBLICATIONS = ( *((REPO_ROOT, base, (1, 5, 10)) for base in SENTENCE_BASE_CONFIGS), *((METRE_ROOT, track, (1, 5, 10)) for track in METRE_TRACKS), ) # The per-author unit table in each README documents the main track only; the # other tracks' per-author counts live in build_report.json, because several # tables of the same shape in one README cannot be told apart by pattern. README_AUTHOR_TABLES = tuple( publication for publication in PUBLICATIONS if publication[1] in {"sentence", "verse"} ) TREEBANK_SOURCES = { "agdt", "ud_perseus", "ud_proiel", "ud_ptnk", "gorman", "pedalion", "harrington", } def config_path(root: Path, base: str, suffix: int, split: str) -> Path: return root / "data" / f"{base}_{suffix}" / f"{split}-00000-of-00001.parquet" def test_sentence_build_uses_every_treebank_and_no_external_metrical_source() -> None: revisions = json.loads((REPO_ROOT / "metadata/source_revisions.json").read_text()) report = json.loads((REPO_ROOT / "metadata/build_report.json").read_text()) inventory = report["authorship_curation"]["treebank_source_inventory"] assert set(revisions) == TREEBANK_SOURCES assert set(inventory["rows_by_source"]) == TREEBANK_SOURCES assert all(count > 0 for count in inventory["rows_by_source"].values()) assert sum(inventory["rows_by_source"].values()) == inventory["total_rows"] def test_readme_configuration_counts_match_parquet_rows() -> None: for root, base, suffixes in PUBLICATIONS: readme = (root / "README.md").read_text(encoding="utf-8") table_rows = { match.group("config"): { "authors": int(match.group("authors").replace(",", "")), "train": int(match.group("train").replace(",", "")), "validation": int(match.group("validation").replace(",", "")), "validation2": int(match.group("validation2").replace(",", "")), "test": int(match.group("test").replace(",", "")), } for match in re.finditer( r"^\| `(?P[^`]+)` \| (?P[\d,]+) \| [^|]+ " r"\| (?P[\d,]+) \| (?P[\d,]+) " r"\| (?P[\d,]+) \| (?P[\d,]+) \|$", readme, flags=re.MULTILINE, ) } # One README documents both sentence tracks, so match on this base. table_rows = { config: counts for config, counts in table_rows.items() if config.rsplit("_", 1)[0] == base } expected_configs = {f"{base}_{suffix}" for suffix in suffixes} assert set(table_rows) == expected_configs for config in sorted(expected_configs): expected = {} authors = set() for split in SPLITS: path = root / "data" / config / f"{split}-00000-of-00001.parquet" table = pq.read_table(path, columns=["author"]) expected[split] = table.num_rows authors.update(table["author"].to_pylist()) assert table_rows[config] == {"authors": len(authors), **expected} def test_readme_author_unit_counts_and_shares_match_atomic_parquets() -> None: for root, base, _suffixes in README_AUTHOR_TABLES: readme = (root / "README.md").read_text(encoding="utf-8") documented = { match.group("author"): { **{ split: int(match.group(split).replace(",", "")) for split in ("train", "validation", "validation2", "test", "total") }, "share": match.group("share"), } for match in re.finditer( r"^\| (?P[^|*]+?) \| (?P[\d,]+) " r"\| (?P[\d,]+) \| (?P[\d,]+) " r"\| (?P[\d,]+) " r"\| (?P[\d,]+) \((?P\d+\.\d%)\) \|$", readme, flags=re.MULTILINE, ) } expected = defaultdict(Counter) for split in SPLITS: authors = pq.read_table( config_path(root, base, 1, split), columns=["author"], )["author"].to_pylist() for author in authors: expected[author][split] += 1 expected[author]["total"] += 1 grand_total = sum(counts["total"] for counts in expected.values()) assert documented == { author: { **dict(counts), "share": f"{100 * counts['total'] / grand_total:.1f}%", } for author, counts in expected.items() } def test_all_atomic_splits_are_balanced_and_chunkable() -> None: for root, base, _suffixes in PUBLICATIONS: counts = defaultdict(Counter) for split in SPLITS: table = pq.read_table( config_path(root, base, 1, split), columns=["author", "split"], ) for row in table.to_pylist(): counts[row["author"]][row["split"]] += 1 assert counts for author, author_counts in counts.items(): for split in SPLITS: assert author_counts[split] >= ELIGIBILITY_MINIMUM[split], (base, author, split) assert author_counts[split] % BOTTLENECK_TARGET == 0, ( base, author, split, ) def test_chunk_sizes_and_atomic_coverage_are_exact_in_every_split() -> None: for root, base, suffixes in PUBLICATIONS: atomic = {} for split in SPLITS: atomic[split] = { row["id"]: load_text_units(row["text"]) for row in pq.read_table( config_path(root, base, 1, split), columns=["id", "text"], ).to_pylist() } for suffix in suffixes[1:]: for split in SPLITS: # The metre publication names the column "conllu" in every one of # its tracks; the sentence publication carries two parse layers. conllu_column = "conllu" if root == METRE_ROOT else "conllu_human" rows = pq.read_table( config_path(root, base, suffix, split), columns=["text", conllu_column, "chunk_size", "constituent_ids"], ).to_pylist() represented = [ row_id for row in rows for row_id in row["constituent_ids"] ] assert len(represented) == len(set(represented)) assert set(represented) == set(atomic[split]) for row in rows: assert row["chunk_size"] == suffix assert len(row["constituent_ids"]) == suffix assert len(load_text_units(row["text"])) == suffix assert len(load_conllu_units(row[conllu_column])) == suffix assert load_text_units(row["text"]) == [ unit for row_id in row["constituent_ids"] for unit in atomic[split][row_id] ] def test_sentence_publication_contains_no_hypotactic_fields_or_provenance() -> None: 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", } for suffix in (1, 5, 10): for split in SPLITS: path = config_path(REPO_ROOT, "sentence", suffix, split) schema = pq.ParquetFile(path).schema_arrow assert not (forbidden & set(schema.names)) rows = pq.read_table(path, columns=["genre", "source_records"]).to_pylist() assert {row["genre"] for row in rows} <= {"prose", "verse"} for row in rows: assert all( record["source"] != "hypotactic" for record in row["source_records"] ) def test_metre_publication_omits_redundant_genre_column() -> None: for suffix in (1, 5, 10): for split in SPLITS: path = config_path(METRE_ROOT, "verse", suffix, split) assert "genre" not in pq.ParquetFile(path).schema_arrow.names def test_metre_chunks_preserve_aligned_metre_and_syllable_line_units() -> None: atomic_syllables = {} atomic_metres = {} for split in SPLITS: rows = pq.read_table( config_path(METRE_ROOT, "verse", 1, split), columns=["id", "metre", "syllables"], ).to_pylist() atomic_syllables[split] = { row["id"]: load_syllable_units(row["syllables"]) for row in rows } atomic_metres[split] = { row["id"]: load_metre_units(row["metre"]) for row in rows } assert all(len(units) == 1 for units in atomic_syllables[split].values()) assert all(len(units) == 1 for units in atomic_metres[split].values()) for suffix in (5, 10): for split in SPLITS: rows = pq.read_table( config_path(METRE_ROOT, "verse", suffix, split), columns=["constituent_ids", "metre", "syllables"], ).to_pylist() for row in rows: assert load_metre_units(row["metre"]) == [ metre for row_id in row["constituent_ids"] for metre in atomic_metres[split][row_id] ] assert load_syllable_units(row["syllables"]) == [ syllables for row_id in row["constituent_ids"] for syllables in atomic_syllables[split][row_id] ] def parse_boundary_fixture(separator: str) -> list[dict]: parser = HypotacticParser("test") parser.feed( '
' '
' 'μῆ' f'{separator}ἄει' f'{separator}θεά' '
' ) return parser.lines[0]["syllables"] def test_hypotactic_word_boundaries_are_serialization_invariant() -> None: minified = parse_boundary_fixture("") spaced = parse_boundary_fixture(" \n ") assert minified == spaced assert [syllable["features"] for syllable in minified] == [ ["caesura", "hiatus"], ["caesura"], [], ] def test_hypotactic_upstream_hiatus_is_replaced_by_derived_hiatus() -> None: syllables = parse_boundary_fixture("") assert "hiatus" not in syllables[-1]["features"] def test_bare_hypotactic_diastole_is_long() -> None: parser = HypotacticParser("test") parser.feed( '
' '
' 'ας' '
' ) assert parser.lines[0]["syllables"][0]["quantity"] == "long" def test_line_features_use_half_morae_and_listed_caesura_positions() -> None: syllables = [ {"text": "μῆ", "quantity": "long", "features": []}, {"text": "νι", "quantity": "short", "features": []}, { "text": "ν", "quantity": "short", "features": ["caesura", "hiatus"], }, {"text": "ἄει", "quantity": "long", "features": []}, ] assert syllable_line(syllables) == { "features": { "hiatus": 1, "longa": 2, "brevia": 2, "morae": 3, "caesurae": [{"isochronic": 2, "isosyllabic": 3}], }, "syllables": syllables, } def test_unquantified_syllable_rejects_line_features() -> None: with pytest.raises(ValueError, match="cannot derive line time"): line_features([ {"text": "?", "quantity": "unknown", "features": []}, ]) def test_upstream_hypotactic_syllable_classes_are_not_published() -> None: parser = HypotacticParser("test") parser.feed( '
' '
' 'μῆ' 'νι' 'ν' '
' ) assert [syllable["features"] for syllable in parser.lines[0]["syllables"]] == [ ["caesura"], [], [], ] def test_published_boundary_features_cover_every_author_but_never_line_final() -> None: feature_authors = defaultdict(set) authors = set() for split in SPLITS: for row in pq.read_table( config_path(METRE_ROOT, "verse", 1, split), columns=["author", "syllables"], ).to_pylist(): authors.add(row["author"]) for line in load_syllable_units(row["syllables"]): syllables = line["syllables"] assert not ({"caesura", "hiatus"} & set(syllables[-1]["features"])) for syllable in syllables[:-1]: for feature in {"caesura", "hiatus"} & set(syllable["features"]): feature_authors[feature].add(row["author"]) assert feature_authors["caesura"] == authors assert feature_authors["hiatus"] == authors def test_metre_syntax_origin_is_explicit_and_provenance_matches() -> None: atomic_origins = set() for split in SPLITS: rows = pq.read_table( config_path(METRE_ROOT, "verse", 1, split), columns=["syntax_annotation", "treebank_source", "source_records"], ).to_pylist() for row in rows: origin = row["syntax_annotation"] atomic_origins.add(origin) sources = {record["source"] for record in row["source_records"]} assert "hypotactic" in sources assert origin == "predicted" assert row["treebank_source"] == "stoicheia_tagger_parser" assert "stoicheia_tagger_parser" in sources assert atomic_origins == {"predicted"} for suffix in (5, 10): for split in SPLITS: origins = set(pq.read_table( config_path(METRE_ROOT, "verse", suffix, split), columns=["syntax_annotation"], )["syntax_annotation"].to_pylist()) assert origins == {"predicted"} def test_predicted_metre_trees_use_reconstructed_sentence_context() -> None: report = json.loads((METRE_ROOT / "metadata/build_report.json").read_text()) syntax = report["automatic_syntax"] assert syntax["inference_unit"] == ( "punctuation-delimited context with punctuation removed before parsing" ) assert syntax["publication_unit"] == ( "metrical line cropped from its inferred sentence tree" ) assert 0 < syntax["context_sentences"] < syntax["predictions_in_cache"] assert 0 < syntax["context_sentences_spanning_multiple_lines"] found_prediction = False for split in SPLITS: rows = pq.read_table( config_path(METRE_ROOT, "verse", 1, split), columns=["syntax_annotation", "source_records"], ).to_pylist() for row in rows: if row["syntax_annotation"] != "predicted": continue found_prediction = True records = row["source_records"] model_record = next( record for record in records if record["source"] == "stoicheia_tagger_parser" ) assert "removing all editorial punctuation" in ( model_record["annotation_provenance"] ) break if found_prediction: break assert found_prediction def test_gold_is_diagnostic_only_and_quality_metrics_are_reported() -> None: report = json.loads((METRE_ROOT / "metadata/build_report.json").read_text()) syntax = report["automatic_syntax"] quality = syntax["gold_reference_quality"] assert syntax["machine_predictions_replacing_prior_gold"] > 0 assert quality["comparison_lines"] == syntax["gold_reference_lines"] assert quality["matched_character_span_tokens"] > 0 for name in ( "token_boundary_precision", "token_boundary_recall", "exact_tokenization_line_rate", "lemma_exact_nfc_accuracy_on_matched_tokens", "upos_accuracy_on_matched_tokens", "deprel_accuracy_on_matched_tokens", "uas_on_matched_tokens", "las_on_matched_tokens", ): assert 0 <= quality[name] <= 1 def test_scansion_is_not_published() -> None: for suffix in (1, 5, 10): for split in SPLITS: path = config_path(METRE_ROOT, "verse", suffix, split) assert "scansion" not in pq.ParquetFile(path).schema_arrow.names def test_metrical_line_sanitizer_drops_all_provenance_and_identifiers() -> None: unsafe = json.dumps([{ "text": "μῆνιν ἄειδε", "metre": "hexameter", "syllables": [{"text": "μῆ", "quantity": "long", "features": []}], "hypotactic_file": "iliad1.html", "hypotactic_author": "Homer", "hypotactic_work": "Iliad", "book": "1", "poem_sequence": "1", "number": "1", "speaker": "Achilles", "id": "vm-secret", "coverage_in_sentence": "full", "scansion": "–", }], ensure_ascii=False) lines = sanitize_metrical_lines(unsafe) assert len(lines) == 1 assert set(lines[0]) == PUBLIC_METRICAL_LINE_FIELD_SET