File size: 25,199 Bytes
1bd5e76
 
 
 
 
 
ac04b84
 
1bd5e76
 
 
 
 
 
 
 
ac04b84
 
 
 
 
ecfe7f5
 
4a0d2b0
ecfe7f5
 
 
1bcc6c0
e1e2e3d
ecfe7f5
 
4a0d2b0
ecfe7f5
 
 
1bcc6c0
e1e2e3d
ecfe7f5
1bd5e76
85f00da
 
 
 
 
1bd5e76
e1c252e
1bd5e76
85f00da
 
 
 
 
 
 
 
 
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
d44b077
ecfe7f5
aa7a784
 
ecfe7f5
24c3b46
ecfe7f5
 
 
1bd5e76
 
 
 
 
 
 
 
 
aa7a784
ecfe7f5
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f231e9
4a0d2b0
ecfe7f5
 
1f231e9
 
4a0d2b0
 
 
 
 
 
 
 
1f231e9
 
 
d44b077
85f00da
d44b077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f00da
d44b077
 
 
 
 
 
 
 
aa7a784
1bd5e76
 
 
 
 
85f00da
1bd5e76
 
 
85f00da
aa7a784
85f00da
1bd5e76
24c3b46
1bd5e76
 
 
 
 
aa7a784
1bd5e76
 
 
85f00da
1bcc6c0
 
85f00da
1bd5e76
24c3b46
1bd5e76
 
 
 
 
 
 
1bcc6c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa7a784
 
 
e1e2e3d
 
 
aa7a784
 
 
 
4a0d2b0
ecfe7f5
85f00da
 
 
 
 
 
 
 
 
 
 
4a0d2b0
 
 
 
 
 
 
 
e1e2e3d
 
 
 
 
 
 
 
 
 
85f00da
4a0d2b0
85f00da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a0d2b0
aa7a784
 
85f00da
 
4a0d2b0
 
 
 
 
85f00da
 
4a0d2b0
 
 
 
 
 
 
 
85f00da
 
 
4a0d2b0
ecfe7f5
 
4a0d2b0
ecfe7f5
 
 
 
 
 
 
 
 
4a0d2b0
 
ecfe7f5
 
 
 
 
 
 
 
4a0d2b0
ecfe7f5
 
e1e2e3d
 
 
 
 
 
24c3b46
 
 
 
 
 
 
ecfe7f5
 
 
 
 
 
 
 
 
 
 
 
4a0d2b0
ecfe7f5
 
 
 
 
 
4a0d2b0
ecfe7f5
 
 
 
 
 
 
 
 
 
 
24c3b46
 
ecfe7f5
 
 
 
 
 
 
 
 
24c3b46
 
85f00da
 
aa7a784
1bd5e76
aa7a784
85f00da
1bd5e76
 
 
aa7a784
 
 
1bd5e76
 
 
 
 
85f00da
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f00da
aa7a784
 
 
 
 
 
 
85f00da
aa7a784
 
 
4a0d2b0
 
 
 
 
 
aa7a784
1bd5e76
 
 
ac04b84
 
 
 
 
 
 
 
 
 
e1c252e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac04b84
 
 
 
 
 
 
 
 
 
 
 
 
1bd5e76
 
 
 
 
 
 
 
85f00da
 
1bd5e76
e1e2e3d
 
 
 
 
 
 
85f00da
1bd5e76
 
 
d44b077
1f231e9
ecfe7f5
85f00da
4a0d2b0
aa7a784
1bcc6c0
aa7a784
 
ac04b84
1bd5e76
1bcc6c0
4a0d2b0
1bd5e76
aa7a784
ac04b84
1bd5e76
 
 
 
 
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#!/usr/bin/env python3
"""Independent validation for the published Sphregis Parquet files."""

from __future__ import annotations

import argparse
import hashlib
import io
import json
import re
import unicodedata
from collections import Counter
from pathlib import Path

import pyarrow.parquet as pq

try:
    from scripts.vendor.conll18_ud_eval import UDError, load_conllu
except ModuleNotFoundError:  # Direct execution from the scripts directory.
    from vendor.conll18_ud_eval import UDError, load_conllu

try:
    from scripts.dataset_variants import (
        BOTTLENECK_TARGET,
        actual_order_key,
        variant_schema,
    )
    from scripts.metrical_lines import load_public_metrical_lines
    from scripts.text_units import load_text_units
except ModuleNotFoundError:  # Direct execution from the scripts directory.
    from dataset_variants import (  # type: ignore[no-redef]
        BOTTLENECK_TARGET,
        actual_order_key,
        variant_schema,
    )
    from metrical_lines import load_public_metrical_lines
    from text_units import load_text_units


BASE_CONFIGS = ("prose", "verse_sentence", "verse_metre")
VARIANT_SUFFIXES = ("1", "10", "100")
CONFIGS = tuple(
    f"{config}_{suffix}" for config in BASE_CONFIGS for suffix in VARIANT_SUFFIXES
)
SPLITS = ("train", "validation", "test")
SAFE_CONLLU_MISC_KEYS = {"NativeRel", "NativeHead", "HeadRepair", "SpaceAfter"}

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",
}

EXCLUDED_DEMOSTHENIC_SPEECHS = {7, 17, 46, 47, 49, 50, 52, 53, 59}
EXCLUDED_AUTHOR_WORKS = {
    ("Aeschylus", "Prometheus Bound"),
    ("Aesop", "Fables"),
    ("Aesop", "Fables 1–50"),
    ("Antiphon", "antiphon 1 bu2"),
    ("Antiphon", "antiphon 2 bu2"),
    ("Chion", "Letters"),
    ("Epictetus", "Dissertationes ab Arriano digestae"),
    ("First Council of Nicea", "Nicene Creed 325 CE"),
    ("Hesiod", "Shield of Heracles"),
    ("Isocrates", "Letters"),
    ("John of Patmos", "Revelation"),
    ("Plato", "Cleitophon"),
    ("Xenophon", "xen cyr 8.8 bu1"),
}


LIGHT_COLUMNS = [
    "id", "parent_sentence_ids", "author", "work", "work_id", "genre", "text",
    "passage", "source_records",
    "dedup_key", "split", "alignment_component_id",
    "component_sentence_index", "component_line_index", "metrical_line_ids",
    "book", "poem_sequence", "line_number", "hypotactic_file",
    "syllables",
    "chunk_size", "chunk_target_size", "constituent_ids",
    "constituent_provenance", "chunk_work_ids", "chunk_works",
    "chunk_is_mixed_work",
]


def read_config(root: Path, config: str) -> list[dict]:
    rows = []
    for split in SPLITS:
        path = root / config / f"{split}-00000-of-00001.parquet"
        assert path.is_file(), f"missing {path}"
        parquet = pq.ParquetFile(path)
        columns = [name for name in LIGHT_COLUMNS if name in parquet.schema_arrow.names]
        if not config.endswith("_1"):
            columns.remove("source_records")
        part = parquet.read(columns=columns, use_threads=False).to_pylist()
        assert all(row["split"] == split for row in part), f"split label mismatch in {path}"
        rows.extend(part)
    return rows


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 validate_work_stratification(configs: dict[str, list[dict]]) -> None:
    """Validate the balanced splits after the shared 100-row bottleneck."""
    for config in (f"{base}_1" for base in BASE_CONFIGS):
        rows = configs[config]
        groups = {}
        for row in rows:
            groups.setdefault(row["author"], []).append(row)
        for author, author_rows in groups.items():
            actual = Counter(row["split"] for row in author_rows)
            assert actual["train"] > 0
            assert actual["validation"] == actual["test"]
            assert actual["validation"] >= BOTTLENECK_TARGET
            assert actual["validation"] % BOTTLENECK_TARGET == 0, (
                f"{config} is not 100-row chunkable for {author}: {dict(actual)}"
            )


def validate_authorship_policy(configs: dict[str, list[dict]]) -> None:
    rows = [row for config in BASE_CONFIGS for row in configs[f"{config}_1"]]
    for row in rows:
        author = row["author"]
        lowered = author.casefold()
        assert not lowered.startswith(("unknown", "anonymous", "pseudo-", "(pseudo-"))
        assert "(traditional)" not in lowered
        assert not re.search(r"\bfragments?\b", row["work"], re.I)
        assert (author, row["work"]) not in EXCLUDED_AUTHOR_WORKS
        if author == "Demosthenes":
            match = re.match(r"^dem(?:osthenes)?[ _]+(\d+)", row["work"], re.I)
            assert not match or int(match.group(1)) not in EXCLUDED_DEMOSTHENIC_SPEECHS
        if author.startswith("Homeric-"):
            assert (author, row["work"]) in {
                ("Homeric-Iliad", "Iliad"),
                ("Homeric-Odyssey", "Odyssey"),
            }
        assert author != "Homer"

    for row in configs["verse_metre_1"]:
        if (row["author"], row["work"]) != ("Aeschylus", "Seven Against Thebes"):
            continue
        match = re.match(r"^(\d+)", str(row["line_number"]))
        if match:
            number = int(match.group(1))
            assert not (861 <= number <= 874 or 1005 <= number <= 1078)


def validate_provenance_and_verse(root: Path) -> int:
    checked_lines = 0
    required_record_fields = {
        "source", "source_file", "source_sentence_id", "url", "revision",
        "license", "annotation_provenance", "syntax_scheme",
    }
    for config in (f"{base}_1" for base in BASE_CONFIGS):
        for split in SPLITS:
            path = root / config / f"{split}-00000-of-00001.parquet"
            columns = ["source_records", "licenses"]
            if config == "verse_sentence_1":
                columns += ["metrical_line_ids", "metrical_lines"]
            elif config == "verse_metre_1":
                columns += [
                    "metre", "syllables", "hypotactic_file",
                ]
            parquet = pq.ParquetFile(path)
            for batch in parquet.iter_batches(columns=columns, batch_size=256, use_threads=False):
                for row in batch.to_pylist():
                    records = json.loads(row["source_records"])
                    assert "NLP repackaging by Urdatorn" not in row["source_records"]
                    assert records and all(required_record_fields <= record.keys() for record in records)
                    assert all(re.fullmatch(r"[0-9a-f]{40}", record["revision"]) for record in records)
                    assert sorted(row["licenses"]) == sorted({record["license"] for record in records})
                    if config == "verse_sentence_1":
                        lines = load_public_metrical_lines(row["metrical_lines"])
                        assert len(lines) == len(row["metrical_line_ids"])
                    elif config == "verse_metre_1":
                        syllables = json.loads(row["syllables"])
                        assert row["metre"] and syllables
                        hyp_records = [record for record in records if record["source"] == "hypotactic"]
                        assert len(hyp_records) == 1
                        assert hyp_records[0]["source_file"] == row["hypotactic_file"]
                        checked_lines += 1
    return checked_lines


def validate_metrical_line_privacy(root: Path) -> int:
    """Check the strict public JSON contract in every relevant task and split."""
    checked = 0
    for suffix in VARIANT_SUFFIXES:
        config = f"verse_sentence_{suffix}"
        for split in SPLITS:
            path = root / config / f"{split}-00000-of-00001.parquet"
            parquet = pq.ParquetFile(path)
            for batch in parquet.iter_batches(
                columns=["id", "metrical_line_ids", "metrical_lines"],
                batch_size=256,
                use_threads=False,
            ):
                for row in batch.to_pylist():
                    try:
                        lines = load_public_metrical_lines(row["metrical_lines"])
                    except (TypeError, ValueError, json.JSONDecodeError) as error:
                        raise AssertionError(
                            f"Unsafe metrical_lines in {config}/{split}, "
                            f"row {row['id']}: {error}"
                        ) from error
                    assert len(lines) == len(row["metrical_line_ids"]), (
                        f"metrical line/id count mismatch in {config}/{split}, "
                        f"row {row['id']}"
                    )
                    checked += len(lines)
    return checked


def cumulative_lengths(rows: list[dict]) -> list[int]:
    boundaries = [0]
    for row in rows:
        boundaries.append(boundaries[-1] + sum(
            len(normalize(unit)) for unit in load_text_units(row["text"])
        ))
    return boundaries


def validate_alignment_components(configs: dict[str, list[dict]]) -> int:
    complete_components = 0
    for suffix in ("1",):
        sentences_by_id = {row["id"]: row for row in configs[f"verse_sentence_{suffix}"]}
        lines_by_id = {row["id"]: row for row in configs[f"verse_metre_{suffix}"]}
        components = {}
        for base, kind in (("verse_sentence", "sentences"), ("verse_metre", "lines")):
            for row in configs[f"{base}_{suffix}"]:
                components.setdefault(
                    row["alignment_component_id"], {"sentences": [], "lines": []}
                )[kind].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"])
            if not sentences or not lines:
                continue
            sentence_ids = {row["id"] for row in sentences}
            line_ids = {row["id"] for row in lines}
            if any(not set(row["metrical_line_ids"]) <= line_ids for row in sentences):
                continue
            if any(not set(row["parent_sentence_ids"]) <= sentence_ids for row in lines):
                continue
            sentence_text = "".join(
                normalize(unit)
                for row in sentences
                for unit in load_text_units(row["text"])
            )
            line_text = "".join(
                normalize(unit)
                for row in lines
                for unit in load_text_units(row["text"])
            )
            assert sentence_text == line_text
            complete_components += 1
            sentence_bounds = cumulative_lengths(sentences)
            line_bounds = cumulative_lengths(lines)
            for sentence_index, sentence in enumerate(sentences):
                start, end = sentence_bounds[sentence_index:sentence_index + 2]
                expected = [
                    line["id"] for line_index, line in enumerate(lines)
                    if max(start, line_bounds[line_index]) < min(end, line_bounds[line_index + 1])
                ]
                assert sentence["metrical_line_ids"] == expected
            for line_index, line in enumerate(lines):
                start, end = line_bounds[line_index:line_index + 2]
                expected = [
                    sentence["id"] for sentence_index, sentence in enumerate(sentences)
                    if max(start, sentence_bounds[sentence_index]) < min(end, sentence_bounds[sentence_index + 1])
                ]
                assert line["parent_sentence_ids"] == expected
                assert all(parent_id in sentences_by_id for parent_id in expected)
                assert line["id"] in lines_by_id
    return complete_components


def validate_variants(configs: dict[str, list[dict]]) -> None:
    for base in BASE_CONFIGS:
        atomic = configs[f"{base}_1"]
        atomic_by_id = {row["id"]: row for row in atomic}
        atomic_authors = {row["author"] for row in atomic}
        atomic_counts = {
            split: Counter(row["author"] for row in atomic if row["split"] == split)
            for split in ("validation", "test")
        }
        assert set(atomic_counts["validation"]) == atomic_authors
        assert set(atomic_counts["test"]) == atomic_authors
        for split in ("validation", "test"):
            assert all(
                count >= BOTTLENECK_TARGET and count % BOTTLENECK_TARGET == 0
                for count in atomic_counts[split].values()
            )

        for threshold in (10, 100):
            config = f"{base}_{threshold}"
            rows = configs[config]
            assert {row["author"] for row in rows} == atomic_authors
            train = [row for row in rows if row["split"] == "train"]
            expected_train_ids = {
                row["id"] for row in atomic if row["split"] == "train"
            }
            assert {row["id"] for row in train} == expected_train_ids
            assert all(row["chunk_size"] == 1 for row in train)
            assert all(row["chunk_target_size"] == threshold for row in train)
            assert all(row["constituent_ids"] == [row["id"]] for row in train)

            for split in ("validation", "test"):
                chunks = [row for row in rows if row["split"] == split]
                by_author = {}
                for row in atomic:
                    if row["split"] == split:
                        by_author.setdefault(row["author"], []).append(row)
                chunks_by_author = {}
                for chunk in chunks:
                    chunks_by_author.setdefault(chunk["author"], []).append(chunk)
                    assert chunk["chunk_size"] == threshold
                    assert chunk["chunk_target_size"] == threshold
                    assert len(chunk["constituent_ids"]) == threshold
                    assert len(set(chunk["constituent_ids"])) == threshold
                    constituents = [atomic_by_id[row_id] for row_id in chunk["constituent_ids"]]
                    assert all(row["author"] == chunk["author"] for row in constituents)
                    assert all(row["split"] == split for row in constituents)
                    expected_text_units = [
                        unit
                        for row in constituents
                        for unit in load_text_units(row["text"])
                    ]
                    assert load_text_units(chunk["text"]) == expected_text_units
                    if base == "verse_metre":
                        expected_syllables = [
                            syllable
                            for row in constituents
                            for syllable in json.loads(row["syllables"])
                        ]
                        assert json.loads(chunk["syllables"]) == expected_syllables
                    provenance = json.loads(chunk["constituent_provenance"])
                    assert [record["id"] for record in provenance] == chunk["constituent_ids"]
                    work_ids = []
                    for row in constituents:
                        if row["work_id"] not in work_ids:
                            work_ids.append(row["work_id"])
                    assert chunk["chunk_work_ids"] == work_ids
                    assert chunk["chunk_is_mixed_work"] == (len(work_ids) > 1)
                    for work_id in work_ids:
                        work_rows = [row for row in constituents if row["work_id"] == work_id]
                        assert work_rows == sorted(work_rows, key=actual_order_key)

                assert set(chunks_by_author) == atomic_authors
                for author, source_rows in by_author.items():
                    author_chunks = chunks_by_author[author]
                    used_ids = [
                        row_id for chunk in author_chunks for row_id in chunk["constituent_ids"]
                    ]
                    assert len(used_ids) == len(set(used_ids))
                    assert set(used_ids) == {row["id"] for row in source_rows}
                    assert len(author_chunks) == len(source_rows) // threshold


def validate_schemas(root: Path) -> None:
    for base in BASE_CONFIGS:
        base_schemas = [
            pq.ParquetFile(root / f"{base}_1" / f"{split}-00000-of-00001.parquet").schema_arrow
            for split in SPLITS
        ]
        assert all(schema == base_schemas[0] for schema in base_schemas)
        base_schema = base_schemas[0]
        if base == "verse_metre":
            assert "scansion" not in base_schema.names
        expected_variant_schema = variant_schema(base_schema)
        for threshold in (10, 100):
            schemas = [
                pq.ParquetFile(
                    root / f"{base}_{threshold}" / f"{split}-00000-of-00001.parquet"
                ).schema_arrow
                for split in SPLITS
            ]
            assert all(schema == expected_variant_schema for schema in schemas)
            if base == "verse_metre":
                assert all("scansion" not in schema.names for schema in schemas)


def validate_conllu(root: Path) -> tuple[int, dict[str, str]]:
    checked = 0
    verse_conllu = {}
    for config in ("prose_1", "verse_sentence_1"):
        for split in SPLITS:
            path = root / config / f"{split}-00000-of-00001.parquet"
            parquet = pq.ParquetFile(path)
            for batch in parquet.iter_batches(columns=["id", "conllu"], batch_size=256, use_threads=False):
                for row in batch.to_pylist():
                    conllu = row["conllu"]
                    token_rows = [
                        line.split("\t") for line in conllu.splitlines()
                        if line and not line.startswith("#") and re.fullmatch(r"\d+", line.split("\t", 1)[0])
                    ]
                    assert token_rows and all(len(row) == 10 for row in token_rows)
                    assert all(
                        re.fullmatch(r"[a-z][a-z0-9-]{8}", row[4])
                        for row in token_rows
                    ), "XPOS is not a canonical nine-position Ancient Greek tag"
                    assert all(
                        row[7].split(":", 1)[0] in UD_V2_RELATIONS
                        and re.fullmatch(r"[a-z]+(?::[a-z][a-z0-9_-]*)?", row[7])
                        for row in token_rows
                    ), "dependency relation is not UD v2"
                    ids = [int(row[0]) for row in token_rows]
                    assert ids == list(range(1, len(ids) + 1))
                    heads = [int(row[6]) for row in token_rows]
                    assert all(0 <= head <= len(ids) for head in heads)
                    assert all(token_id != head for token_id, head in zip(ids, heads))
                    assert sum(head == 0 for head in heads) == 1
                    assert sum(row[7] == "root" for row in token_rows) == 1
                    assert all((head == 0) == (row[7] == "root") for row, head in zip(token_rows, heads))
                    for token_id in ids:
                        visited = set()
                        cursor = token_id
                        while cursor:
                            assert cursor not in visited, "dependency cycle"
                            visited.add(cursor)
                            cursor = heads[cursor - 1]
                    checked += 1
                    if config == "verse_sentence_1":
                        verse_conllu[row["id"]] = conllu
    return checked, verse_conllu


def validate_combined_conllu(root: Path, parent_conllu: dict[str, str]) -> int:
    checked = 0
    for split in SPLITS:
        path = root / "verse_metre_1" / f"{split}-00000-of-00001.parquet"
        parquet = pq.ParquetFile(path)
        for batch in parquet.iter_batches(columns=["parent_sentence_ids", "conllu"], batch_size=256, use_threads=False):
            for row in batch.to_pylist():
                if all(parent_id in parent_conllu for parent_id in row["parent_sentence_ids"]):
                    expected = "\n\n".join(
                        parent_conllu[parent_id].strip()
                        for parent_id in row["parent_sentence_ids"]
                    ) + "\n\n"
                    assert row["conllu"] == expected
                checked += 1
    return checked


def validate_conllu_with_official_loader(root: Path) -> int:
    checked = set()
    for config in CONFIGS:
        for split in SPLITS:
            path = root / config / f"{split}-00000-of-00001.parquet"
            parquet = pq.ParquetFile(path)
            for batch in parquet.iter_batches(
                columns=["id", "conllu"], batch_size=256, use_threads=False,
            ):
                for row in batch.to_pylist():
                    comments = [
                        line for line in row["conllu"].splitlines()
                        if line.startswith("#")
                    ]
                    assert all(line.startswith("# text = ") for line in comments), (
                        f"Identifying CoNLL-U comment in {config}/{split}, "
                        f"row {row['id']}: {comments}"
                    )
                    for line in row["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}/{split}, "
                            f"row {row['id']}: {misc_keys}"
                        )
                    digest = hashlib.sha256(row["conllu"].encode("utf-8")).digest()
                    if digest in checked:
                        continue
                    try:
                        load_conllu(io.StringIO(row["conllu"]))
                    except UDError as error:
                        raise AssertionError(
                            f"Malformed CoNLL-U in {config}/{split}, row {row['id']}: {error}"
                        ) from error
                    checked.add(digest)
    return len(checked)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", type=Path, default=Path("data"))
    args = parser.parse_args()
    configs = {config: read_config(args.data, config) for config in CONFIGS}
    for config, rows in configs.items():
        ids = [row["id"] 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"])
            expected_units = row.get("chunk_size", 1)
            assert len(text_units) == expected_units, (
                f"text-unit count mismatch in {config}, row {row['id']}: "
                f"{len(text_units)} != {expected_units}"
            )
        if base_config == "prose":
            keys = [row["dedup_key"] for row in rows]
            assert len(keys) == len(set(keys)), "prose is not exactly deduplicated"
        print(config, len(rows), dict(Counter(row["split"] for row in rows)))
    validate_authorship_policy(configs)
    validate_work_stratification(configs)
    validate_schemas(args.data)
    validate_variants(configs)
    complete_components = validate_alignment_components(configs)
    checked_lines = validate_provenance_and_verse(args.data)
    checked_public_lines = validate_metrical_line_privacy(args.data)
    checked, parent_conllu = validate_conllu(args.data)
    checked_combined = validate_combined_conllu(args.data, parent_conllu)
    checked_official = validate_conllu_with_official_loader(args.data)
    print("validated aligned metrical lines", checked_lines)
    print("validated privacy-safe serialized metrical lines", checked_public_lines)
    print("validated complete retained verse alignment components", complete_components)
    print("validated CoNLL-U sentences", checked)
    print("validated combined metrical CoNLL-U documents", checked_combined)
    print("validated unique CoNLL-U documents with official CoNLL 2018 loader", checked_official)
    print("all checks passed")


if __name__ == "__main__":
    main()