Datasets:
Download scripts/validate_reviewed_pages_release.py from nkeetha/paninian-sanskrit: direct link, hf CLI and curl.
- Browser
- Download file 7.79 kB
-
https://huggingface.co/datasets/nkeetha/paninian-sanskrit/resolve/main/scripts/validate_reviewed_pages_release.py
- Command line
-
hf download hf://datasets/nkeetha/paninian-sanskrit/scripts/validate_reviewed_pages_release.py
-
curl -L -o validate_reviewed_pages_release.py https://huggingface.co/datasets/nkeetha/paninian-sanskrit/resolve/main/scripts/validate_reviewed_pages_release.py
7.79 kB
| #!/usr/bin/env python3 | |
| """Validate the frozen reviewed-page Hugging Face release.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from datasets import load_dataset | |
| SUSPICIOUS_TEXT = re.compile(r"[A-Za-z*?\ufffd]|[\u200b-\u200d\u2060\ufeff]") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--root", type=Path, default=Path(__file__).resolve().parents[1] | |
| ) | |
| parser.add_argument("--version", default="v0.1") | |
| return parser.parse_args() | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def main() -> int: | |
| args = parse_args() | |
| root = args.root.resolve() | |
| version = args.version | |
| release_name = f"reviewed-pages-{version}" | |
| failures = [] | |
| summary_path = root / "metadata" / f"reviewed_pages_{version}_summary.json" | |
| checksums_path = root / "metadata" / f"reviewed_pages_{version}_checksums.sha256" | |
| exclusions_path = root / "metadata" / f"reviewed_pages_{version}_exclusions.parquet" | |
| snapshot_path = ( | |
| root / "releases" / release_name / "folio_alignment_review_snapshot.json" | |
| ) | |
| summary = json.loads(summary_path.read_text(encoding="utf-8")) | |
| for line_number, line in enumerate( | |
| checksums_path.read_text(encoding="utf-8").splitlines(), 1 | |
| ): | |
| expected, relative = line.split(" ", 1) | |
| path = root / relative | |
| if not path.is_file(): | |
| failures.append( | |
| f"Missing checksum target on line {line_number}: {relative}" | |
| ) | |
| elif sha256(path) != expected: | |
| failures.append(f"Checksum mismatch: {relative}") | |
| if sha256(snapshot_path) != summary["review_snapshot_sha256"]: | |
| failures.append("Review snapshot does not match the summary digest") | |
| if summary.get("release") != release_name or summary.get("version") != version: | |
| failures.append("Summary release identity does not match the requested version") | |
| if correction_digest := summary.get("correction_manifest_sha256"): | |
| correction_path = root / "releases" / release_name / "corrections.json" | |
| if not correction_path.is_file(): | |
| failures.append("Correction manifest is missing") | |
| elif sha256(correction_path) != correction_digest: | |
| failures.append("Correction manifest does not match the summary digest") | |
| seen_pages = set() | |
| seen_source_pages = set() | |
| observed = {} | |
| split_manuscripts = {} | |
| for config, directory, expect_blank in ( | |
| ("pages", "pages", False), | |
| ("blanks", "blanks", True), | |
| ): | |
| files = sorted( | |
| (root / "data" / "reviewed_pages" / version / directory).glob("*.parquet") | |
| ) | |
| dataset = load_dataset( | |
| "parquet", | |
| data_files={"release": [str(path) for path in files]}, | |
| split="release", | |
| ) | |
| counts = Counter() | |
| manuscripts = set() | |
| characters = 0 | |
| lines = 0 | |
| for row in dataset: | |
| page_id = row["page_id"] | |
| if page_id in seen_pages: | |
| failures.append(f"Duplicate page_id: {page_id}") | |
| seen_pages.add(page_id) | |
| source_key = (row["source_pdf_sha256"], row["pdf_page_index"]) | |
| if source_key in seen_source_pages: | |
| failures.append(f"Duplicate source page: {page_id}") | |
| seen_source_pages.add(source_key) | |
| if row["is_blank"] != expect_blank: | |
| failures.append(f"Incorrect blank flag: {page_id}") | |
| if expect_blank and row["transcription_devanagari"]: | |
| failures.append(f"Blank page has text: {page_id}") | |
| if not expect_blank and not row["transcription_devanagari"]: | |
| failures.append(f"Text page has an empty target: {page_id}") | |
| if SUSPICIOUS_TEXT.search(row["transcription_devanagari"]): | |
| failures.append(f"Suspicious target text: {page_id}") | |
| if row["manuscript_id"] == "M00670": | |
| failures.append(f"Duplicate manuscript included: {page_id}") | |
| if row["verification_status"] != "alignment_reviewed": | |
| failures.append(f"Incorrect verification status: {page_id}") | |
| split = row["split"] | |
| counts[split] += 1 | |
| manuscripts.add((split, row["manuscript_id"])) | |
| characters += len(row["transcription_devanagari"]) | |
| lines += len( | |
| [ | |
| line | |
| for line in row["transcription_devanagari"].splitlines() | |
| if line.strip() | |
| ] | |
| ) | |
| if not row["image"]["bytes"]: | |
| failures.append(f"Image bytes missing: {page_id}") | |
| elif ( | |
| hashlib.sha256(row["image"]["bytes"]).hexdigest() | |
| != row["page_image_sha256"] | |
| ): | |
| failures.append(f"Image digest mismatch: {page_id}") | |
| observed[config] = counts | |
| split_manuscripts[config] = manuscripts | |
| if not expect_blank: | |
| expected_characters = summary["totals"]["characters"] | |
| expected_lines = summary["totals"]["transcription_lines"] | |
| if characters != expected_characters: | |
| failures.append( | |
| f"Character total is {characters}, expected {expected_characters}" | |
| ) | |
| if lines != expected_lines: | |
| failures.append(f"Line total is {lines}, expected {expected_lines}") | |
| text_manuscripts = defaultdict(set) | |
| for split, manuscript_id in split_manuscripts["pages"]: | |
| text_manuscripts[manuscript_id].add(split) | |
| leaked = {key: value for key, value in text_manuscripts.items() if len(value) > 1} | |
| if leaked: | |
| failures.append(f"Manuscripts cross splits: {leaked}") | |
| for split, values in summary["splits"].items(): | |
| if observed["pages"][split] != values["text_pages"]: | |
| failures.append(f"Text-page count mismatch for {split}") | |
| if observed["blanks"][split] != values["blank_pages"]: | |
| failures.append(f"Blank-page count mismatch for {split}") | |
| exclusions = load_dataset( | |
| "parquet", | |
| data_files=str(exclusions_path), | |
| split="train", | |
| ) | |
| if len(exclusions) != summary["totals"]["excluded_pages"]: | |
| failures.append("Exclusion count does not match summary") | |
| exclusion_counts = Counter(exclusions["exclusion_reason"]) | |
| if ( | |
| dict(sorted(exclusion_counts.items())) | |
| != summary["totals"]["excluded_by_reason"] | |
| ): | |
| failures.append("Exclusion reasons do not match summary") | |
| exclusion_page_ids = exclusions["page_id"] | |
| if len(set(exclusion_page_ids)) != len(exclusion_page_ids): | |
| failures.append("Exclusion manifest contains duplicate page IDs") | |
| overlap = seen_pages.intersection(exclusion_page_ids) | |
| if overlap: | |
| failures.append( | |
| f"Included pages also appear in exclusions: {sorted(overlap)[:5]}" | |
| ) | |
| if failures: | |
| print("Reviewed-page release validation failed:", file=sys.stderr) | |
| for failure in failures: | |
| print(f"- {failure}", file=sys.stderr) | |
| return 1 | |
| print( | |
| "Reviewed-page release valid: " | |
| f"{summary['totals']['text_pages']} text pages, " | |
| f"{summary['totals']['blank_pages']} blank pages, " | |
| f"{summary['totals']['excluded_pages']} excluded pages" | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |