File size: 3,195 Bytes
39a78f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
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()