sphragis / scripts /validate_dataset.py
Urdatorn's picture
Fix metrical chunk aggregation
24c3b46
Raw
History Blame Contribute Delete
23 kB
#!/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,
)
except ModuleNotFoundError: # Direct execution from the scripts directory.
from dataset_variants import ( # type: ignore[no-redef]
BOTTLENECK_TARGET,
actual_order_key,
variant_schema,
)
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 = json.loads(row["metrical_lines"])
assert lines and [line["id"] for line in lines] == row["metrical_line_ids"]
assert all(line["metre"] and line["syllables"] for line in lines)
assert all("scansion" not in line for line in lines)
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 cumulative_lengths(rows: list[dict]) -> list[int]:
boundaries = [0]
for row in rows:
boundaries.append(boundaries[-1] + len(normalize(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(row["text"]) for row in sentences)
line_text = "".join(normalize(row["text"]) for row in lines)
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)
assert chunk["text"] == (
"\n" if base == "verse_metre" else "\n\n"
).join(row["text"].strip() for row in constituents)
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)
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, 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 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()