| |
| import argparse, csv, os, shutil, subprocess, sys, threading, time |
| from concurrent.futures import ThreadPoolExecutor |
|
|
| ROOT = os.environ.get("UNSC_CORPUS_ROOT", ".") |
| FLAGS = f"{ROOT}/documents/ocr_flags.tsv" |
| PAGE_JOBS = 3 |
| _lock = threading.Lock() |
| counts = {"ok": 0, "fail": 0, "skip": 0, "n": 0} |
| faillog = f"{ROOT}/documents/ocr_failures.tsv" |
|
|
|
|
| def log(m): |
| with _lock: |
| print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True) |
|
|
|
|
| def archive_dir(pdf_path): |
| d = os.path.join(os.path.dirname(pdf_path), "..", "pdfs_ocr_originals") |
| d = os.path.normpath(d) |
| os.makedirs(d, exist_ok=True) |
| return d |
|
|
|
|
| def ocr_one(row, total): |
| path = row["path"] |
| name = os.path.basename(path) |
| arch = os.path.join(archive_dir(path), name) |
| with _lock: |
| counts["n"] += 1 |
| n = counts["n"] |
| if os.path.exists(arch): |
| with _lock: |
| counts["skip"] += 1 |
| return |
| if not os.path.exists(path): |
| with _lock: |
| counts["fail"] += 1 |
| return |
| tmp = path + ".ocr.pdf" |
| cmd = ["ocrmypdf", "--force-ocr", "-l", "eng", "--output-type", "pdf", |
| "--optimize", "0", "--deskew", "--jobs", str(PAGE_JOBS), path, tmp] |
| try: |
| r = subprocess.run(cmd, capture_output=True, timeout=600) |
| if r.returncode == 0 and os.path.exists(tmp) and os.path.getsize(tmp) > 1000: |
| shutil.copy2(path, arch) |
| os.replace(tmp, path) |
| with _lock: |
| counts["ok"] += 1 |
| else: |
| if os.path.exists(tmp): |
| os.remove(tmp) |
| with _lock: |
| counts["fail"] += 1 |
| with open(faillog, "a") as fh: |
| err = r.stderr.decode("utf-8", "ignore")[-200:].replace("\n", " ") |
| fh.write(f"{path}\trc={r.returncode}\t{err}\n") |
| except Exception as e: |
| if os.path.exists(tmp): |
| os.remove(tmp) |
| with _lock: |
| counts["fail"] += 1 |
| with open(faillog, "a") as fh: |
| fh.write(f"{path}\texception\t{e}\n") |
| with _lock: |
| if counts["n"] % 100 == 0: |
| log(f"{counts['n']}/{total} ocr'd={counts['ok']} fail={counts['fail']} skip={counts['skip']}") |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--jobs", type=int, default=4, help="concurrent files") |
| ap.add_argument("--page-jobs", type=int, default=3, help="threads per file") |
| ap.add_argument("--limit", type=int, default=0) |
| args = ap.parse_args() |
| global PAGE_JOBS |
| PAGE_JOBS = args.page_jobs |
|
|
| flagged = [r for r in csv.DictReader(open(FLAGS), delimiter="\t") |
| if r["needs_ocr"] == "YES"] |
| flagged.sort(key=lambda r: float(r["cpp"])) |
| if args.limit: |
| flagged = flagged[:args.limit] |
| log(f"{len(flagged)} flagged PDFs to re-OCR (jobs={args.jobs})") |
|
|
| total = len(flagged) |
| with ThreadPoolExecutor(max_workers=args.jobs) as ex: |
| list(ex.map(lambda r: ocr_one(r, total), flagged)) |
| log(f"DONE: ocr'd={counts['ok']} fail={counts['fail']} skip={counts['skip']} " |
| f"of {total}. Originals archived in each family's pdfs_ocr_originals/.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|