Datasets:
Download scripts/finalize_package.py from PiotrSty/impact-psnc-polish-ocr: direct link, hf CLI and curl.
- Browser
- Download file 4.91 kB
-
https://huggingface.co/datasets/PiotrSty/impact-psnc-polish-ocr/resolve/main/scripts/finalize_package.py
- Command line
-
hf download hf://datasets/PiotrSty/impact-psnc-polish-ocr/scripts/finalize_package.py
-
curl -L -o finalize_package.py https://huggingface.co/datasets/PiotrSty/impact-psnc-polish-ocr/resolve/main/scripts/finalize_package.py
4.91 kB
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import shutil | |
| from collections import Counter | |
| from pathlib import Path | |
| import xml.etree.ElementTree as ET | |
| from PIL import Image | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def load_jsonl(path: Path) -> list[dict]: | |
| return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] | |
| def local_name(tag: str) -> str: | |
| return tag.rsplit("}", 1)[-1] | |
| def page_xml_dimensions(path: Path) -> tuple[int, int]: | |
| root = ET.parse(path).getroot() | |
| page = next(node for node in root.iter() if local_name(node.tag) == "Page") | |
| return int(page.attrib["imageWidth"]), int(page.attrib["imageHeight"]) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("package", type=Path) | |
| parser.add_argument("--tools", type=Path, required=True) | |
| args = parser.parse_args() | |
| pages = load_jsonl(args.package / "pages.jsonl") | |
| regions = load_jsonl(args.package / "regions.jsonl") | |
| errors = [] | |
| for modality, rows in (("pages", pages), ("regions", regions)): | |
| for split in ("train", "validation", "test"): | |
| split_rows = [row for row in rows if row["split"] == split] | |
| metadata_path = args.package / modality / split / "metadata.jsonl" | |
| metadata_path.parent.mkdir(parents=True, exist_ok=True) | |
| with metadata_path.open("w", encoding="utf-8", newline="\n") as handle: | |
| for row in split_rows: | |
| image_path = args.package / row["image"] | |
| exported = {**row, "file_name": image_path.relative_to(metadata_path.parent).as_posix()} | |
| exported.pop("image", None) | |
| handle.write(json.dumps(exported, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| page_ids = {row["id"] for row in pages} | |
| for row in pages: | |
| image_path = args.package / row["image"] | |
| xml_path = args.package / row["pagexml"] | |
| if not image_path.is_file() or not xml_path.is_file(): | |
| errors.append(f"Missing page asset: {row['id']}") | |
| continue | |
| with Image.open(image_path) as image: | |
| if image.size != (row["width"], row["height"]): | |
| errors.append(f"Image dimensions differ from manifest: {row['id']}") | |
| if page_xml_dimensions(xml_path) != (row["width"], row["height"]): | |
| errors.append(f"PAGE XML dimensions differ from image: {row['id']}") | |
| if sha256(image_path) != row["image_sha256"] or sha256(xml_path) != row["pagexml_sha256"]: | |
| errors.append(f"Checksum mismatch: {row['id']}") | |
| for row in regions: | |
| image_path = args.package / row["image"] | |
| if row["page_id"] not in page_ids: | |
| errors.append(f"Unknown parent page: {row['id']}") | |
| if not image_path.is_file(): | |
| errors.append(f"Missing region image: {row['id']}") | |
| continue | |
| left, top, right, bottom = row["bbox"] | |
| with Image.open(image_path) as image: | |
| if image.size != (right - left, bottom - top): | |
| errors.append(f"Region dimensions differ from bbox: {row['id']}") | |
| if sha256(image_path) != row["image_sha256"]: | |
| errors.append(f"Region checksum mismatch: {row['id']}") | |
| scripts_dir = args.package / "scripts" | |
| scripts_dir.mkdir(exist_ok=True) | |
| for name in ("audit_pagexml.py", "build_hf_subset.py", "finalize_package.py"): | |
| shutil.copy2(args.tools / name, scripts_dir / name) | |
| excluded_from_checksums = {"checksums.sha256", "validation_report.json"} | |
| files = sorted( | |
| path for path in args.package.rglob("*") | |
| if path.is_file() | |
| and path.name not in excluded_from_checksums | |
| and ".cache" not in path.relative_to(args.package).parts | |
| ) | |
| with (args.package / "checksums.sha256").open("w", encoding="ascii", newline="\n") as handle: | |
| for path in files: | |
| handle.write(f"{sha256(path)} {path.relative_to(args.package).as_posix()}\n") | |
| report = { | |
| "ok": not errors, | |
| "errors": errors, | |
| "pages": len(pages), | |
| "regions": len(regions), | |
| "page_collections": len({row["collection"] for row in pages}), | |
| "page_split_counts": dict(Counter(row["split"] for row in pages)), | |
| "region_split_counts": dict(Counter(row["split"] for row in regions)), | |
| "checksummed_files": len(files), | |
| } | |
| (args.package / "validation_report.json").write_text( | |
| json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| print(json.dumps(report, ensure_ascii=False, indent=2)) | |
| if errors: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |