impact-psnc-polish-ocr / scripts /audit_pagexml.py
PiotrSty's picture
Add files using upload-large-folder tool
c0a0069 verified
Raw History Blame Contribute Delete
3.32 kB
from __future__ import annotations
import argparse
import json
from collections import Counter, defaultdict
from pathlib import Path
import xml.etree.ElementTree as ET
def local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def audit_file(path: Path, root: Path) -> dict:
tree = ET.parse(path)
xml_root = tree.getroot()
page = next((node for node in xml_root.iter() if local_name(node.tag) == "Page"), None)
if page is None:
raise ValueError("PAGE XML has no Page element")
unicode_values = [
(node.text or "").strip()
for node in xml_root.iter()
if local_name(node.tag) == "Unicode" and (node.text or "").strip()
]
text = "\n".join(unicode_values)
regions = Counter(
local_name(node.tag)
for node in xml_root.iter()
if local_name(node.tag).endswith("Region")
)
collection = path.relative_to(root).parts[0]
return {
"path": path.relative_to(root).as_posix(),
"collection": collection,
"image_filename": page.attrib.get("imageFilename"),
"image_width": int(page.attrib.get("imageWidth", 0) or 0),
"image_height": int(page.attrib.get("imageHeight", 0) or 0),
"unicode_nodes": len(unicode_values),
"characters": len(text),
"words": len(text.split()),
"regions": dict(sorted(regions.items())),
"text": text,
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
records = []
errors = []
for path in sorted(args.source.rglob("*.xml")):
try:
records.append(audit_file(path, args.source))
except (ET.ParseError, ValueError, OSError) as exc:
errors.append({"path": path.relative_to(args.source).as_posix(), "error": str(exc)})
by_collection = defaultdict(lambda: {"pages": 0, "annotated": 0, "characters": 0, "words": 0})
region_types = Counter()
for record in records:
stats = by_collection[record["collection"]]
stats["pages"] += 1
stats["annotated"] += int(record["characters"] > 0)
stats["characters"] += record["characters"]
stats["words"] += record["words"]
region_types.update(record["regions"])
summary = {
"pages": len(records),
"annotated_pages": sum(record["characters"] > 0 for record in records),
"empty_pages": sum(record["characters"] == 0 for record in records),
"characters": sum(record["characters"] for record in records),
"words": sum(record["words"] for record in records),
"errors": errors,
"region_types": dict(sorted(region_types.items())),
"collections": dict(sorted(by_collection.items())),
}
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "audit.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
with (args.output / "pages.jsonl").open("w", encoding="utf-8", newline="\n") as handle:
for record in records:
handle.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()