Download code/davis_ocr/audit_ocr_annotations.py from Phillo26/Paston-Letters: direct link, hf CLI and curl.
- Browser
- Download file 4.09 kB
-
https://huggingface.co/datasets/Phillo26/Paston-Letters/resolve/main/code/davis_ocr/audit_ocr_annotations.py
- Command line
-
hf download hf://datasets/Phillo26/Paston-Letters/code/davis_ocr/audit_ocr_annotations.py
-
curl -L -o audit_ocr_annotations.py https://huggingface.co/datasets/Phillo26/Paston-Letters/resolve/main/code/davis_ocr/audit_ocr_annotations.py
4.09 kB
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import re | |
| import sys | |
| from collections import Counter | |
| from pathlib import Path | |
| from volume_identity import logical_volume_id | |
| # Only the edited-text ranges are audited. Front matter, chronology tables, | |
| # glossary, and indexes use punctuation for different editorial purposes. | |
| TEXT_PAGE_RANGES = { | |
| "Paston_Letters_I": (87, 757), | |
| "Paston_Letters_II": (33, 651), | |
| "Paston_Letters_III": (107, 295), | |
| } | |
| CANDIDATE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( | |
| ("registered_mark", re.compile(r"(?i)[A-Za-zþȝ]{2,}®")), | |
| ( | |
| "terminal_apostrophe", | |
| re.compile(r"(?i)[A-Za-zþȝ]{2,}[\u2019\x27](?![A-Za-z])"), | |
| ), | |
| ("terminal_question", re.compile(r"(?i)[A-Za-zþȝ]{2,}\?(?![A-Za-z])")), | |
| ("terminal_bang", re.compile(r"(?i)[A-Za-zþȝ]{2,}!(?![A-Za-z])")), | |
| ) | |
| def audit(path: Path) -> tuple[list[dict[str, str]], Counter[str]]: | |
| page_range = TEXT_PAGE_RANGES.get(logical_volume_id(path)) | |
| if page_range is None: | |
| raise ValueError(f"No edited-text range configured for {path.name}") | |
| start_page, end_page = page_range | |
| page = 0 | |
| rows: list[dict[str, str]] = [] | |
| counts: Counter[str] = Counter() | |
| for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): | |
| marker = re.fullmatch(r"===== PDF PAGE (\d+) =====", line) | |
| if marker: | |
| page = int(marker.group(1)) | |
| continue | |
| if not start_page <= page <= end_page: | |
| continue | |
| for category, pattern in CANDIDATE_PATTERNS: | |
| for match in pattern.finditer(line): | |
| counts[category] += 1 | |
| rows.append( | |
| { | |
| "volume": logical_volume_id(path), | |
| "pdf_page": str(page), | |
| "line": str(line_number), | |
| "category": category, | |
| "token": match.group(0), | |
| "context": line, | |
| } | |
| ) | |
| return rows, counts | |
| def main() -> None: | |
| if hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| parser = argparse.ArgumentParser( | |
| description="Create a page-addressable review list for ambiguous OCR annotations." | |
| ) | |
| parser.add_argument("paths", nargs="+", type=Path, help="OCR text files to audit") | |
| parser.add_argument("--output-dir", type=Path, required=True, help="directory for TSV and summary") | |
| arguments = parser.parse_args() | |
| rows: list[dict[str, str]] = [] | |
| summary: Counter[str] = Counter() | |
| for path in arguments.paths: | |
| if not path.is_file(): | |
| raise SystemExit(f"Not a file: {path}") | |
| volume_rows, counts = audit(path) | |
| rows.extend(volume_rows) | |
| summary.update(counts) | |
| arguments.output_dir.mkdir(parents=True, exist_ok=True) | |
| tsv_path = arguments.output_dir / "annotation_candidates.tsv" | |
| with tsv_path.open("w", encoding="utf-8", newline="") as output: | |
| writer = csv.DictWriter( | |
| output, | |
| fieldnames=("volume", "pdf_page", "line", "category", "token", "context"), | |
| delimiter="\t", | |
| ) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| summary_path = arguments.output_dir / "annotation_audit_summary.md" | |
| lines = [ | |
| "# OCR Annotation Audit", | |
| "", | |
| "This report lists ambiguous symbols in edited-text page ranges only.", | |
| "Each entry must be verified against the PDF page before changing the OCR text.", | |
| "", | |
| f"Total candidates: {len(rows)}", | |
| "", | |
| "| Category | Count |", | |
| "| --- | ---: |", | |
| ] | |
| for category, _ in CANDIDATE_PATTERNS: | |
| lines.append(f"| {category} | {summary[category]} |") | |
| summary_path.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| print(f"Wrote {len(rows)} candidates to {tsv_path}") | |
| for category, _ in CANDIDATE_PATTERNS: | |
| print(f"{category}: {summary[category]}") | |
| if __name__ == "__main__": | |
| main() |