File size: 18,994 Bytes
1f231e9
24c3b46
1f231e9
1539318
1f231e9
 
0bd1a9f
1f231e9
d2c51c1
c6b9888
0bd1a9f
 
 
 
 
 
0879baf
 
 
 
 
 
 
733d9e5
 
 
 
 
 
667319c
0879baf
8280489
667319c
0879baf
8280489
6fc8784
667319c
 
6fc8784
667319c
6fc8784
733d9e5
 
 
 
 
1bcc6c0
733d9e5
 
1f231e9
733d9e5
 
 
 
 
 
 
 
 
1f231e9
 
1539318
8280489
733d9e5
 
 
 
 
 
667319c
733d9e5
 
 
 
 
667319c
733d9e5
 
 
1539318
6fc8784
 
 
 
 
8280489
733d9e5
 
 
 
 
 
 
 
 
 
1539318
 
fb96d98
6fc8784
fb96d98
 
 
 
 
667319c
fb96d98
 
 
 
 
667319c
 
fb96d98
 
 
 
f8c1953
fb96d98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87f113
f8c1953
 
eaebf86
8280489
4a0d2b0
733d9e5
 
 
 
1f231e9
4a0d2b0
 
 
733d9e5
667319c
eaebf86
 
 
4a0d2b0
 
733d9e5
8280489
733d9e5
 
 
e1e2e3d
733d9e5
 
 
4a0d2b0
8280489
733d9e5
d12f7cb
 
 
733d9e5
 
667319c
4a0d2b0
733d9e5
 
4a0d2b0
733d9e5
 
 
 
 
 
667319c
733d9e5
f194eef
733d9e5
 
f194eef
e1e2e3d
 
733d9e5
 
 
 
 
 
 
667319c
733d9e5
 
 
 
 
 
 
 
 
31e2783
e1e2e3d
733d9e5
 
838a0aa
667319c
838a0aa
 
 
 
 
d2c51c1
 
 
733d9e5
d2c51c1
9c2923f
d2c51c1
 
 
 
 
 
 
 
 
24c3b46
d2c51c1
 
667319c
733d9e5
 
9c2923f
d2c51c1
733d9e5
 
d2c51c1
 
 
 
 
 
 
24c3b46
d2c51c1
24c3b46
 
 
30903f0
d2c51c1
 
 
 
30903f0
 
 
d2c51c1
 
30903f0
 
 
 
 
 
 
 
 
d2c51c1
 
 
30903f0
 
 
 
 
0bd1a9f
 
 
 
 
 
 
 
 
 
 
31e2783
0bd1a9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e2783
0bd1a9f
 
 
 
 
667319c
0bd1a9f
 
 
 
 
 
667319c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30903f0
 
 
d2c51c1
30903f0
9c2923f
30903f0
 
 
 
0bd1a9f
 
 
30903f0
 
 
 
d2c51c1
 
5a7dc0a
 
 
 
9c2923f
5a7dc0a
 
 
 
 
31e2783
5a7dc0a
83dae89
 
 
 
5a7dc0a
667319c
5a7dc0a
 
9c2923f
5a7dc0a
 
83dae89
5a7dc0a
 
0280c7d
 
 
 
83dae89
0280c7d
 
 
 
 
 
 
 
 
 
9c2923f
0280c7d
 
 
 
 
 
31e2783
0280c7d
 
 
 
83dae89
0280c7d
 
 
 
 
 
 
 
83dae89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24c3b46
667319c
733d9e5
9c2923f
24c3b46
 
1bcc6c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e2783
1bcc6c0
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
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<config>[^`]+)` \| (?P<authors>[\d,]+) \| [^|]+ "
                r"\| (?P<train>[\d,]+) \| (?P<validation>[\d,]+) "
                r"\| (?P<validation2>[\d,]+) \| (?P<test>[\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<author>[^|*]+?) \| (?P<train>[\d,]+) "
                r"\| (?P<validation>[\d,]+) \| (?P<validation2>[\d,]+) "
                r"\| (?P<test>[\d,]+) "
                r"\| (?P<total>[\d,]+) \((?P<share>\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(
        '<div class="poem" data-author="Test" data-work="Test" data-number="1">'
        '<div class="line hexameter" data-number="1" data-metre="hexameter">'
        '<span class="word"><span class="syll long">μῆ</span></span>'
        f'{separator}<span class="word"><span class="syll long">ἄει</span></span>'
        f'{separator}<span class="word"><span class="syll short hiatus">θεά</span></span>'
        '</div></div>'
    )
    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(
        '<div class="poem" data-author="Test" data-work="Test" data-number="1">'
        '<div class="line hexameter" data-number="1" data-metre="hexameter">'
        '<span class="word"><span class="syll diastole">ας</span></span>'
        '</div></div>'
    )
    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(
        '<div class="poem" data-author="Test" data-work="Test" data-number="1">'
        '<div class="line hexameter" data-number="1" data-metre="hexameter">'
        '<span class="word"><span class="syll long lbn correption">μῆ</span></span>'
        '<span class="word"><span class="syll short fixme context-menu-active">νι</span>'
        '<span class="syll long synizesis">ν</span></span>'
        '</div></div>'
    )
    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