File size: 3,823 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 96 | #!/usr/bin/env python3
import argparse, json, os, re, subprocess, sys, threading, time
from concurrent.futures import ThreadPoolExecutor
ROOT = os.environ.get("UNSC_CORPUS_ROOT", ".")
FAMILIES = {
"resolutions": (f"{ROOT}/resolutions/metadata/records.jsonl", f"{ROOT}/resolutions/pdfs"),
"presidential_statements": (f"{ROOT}/presidential_statements/metadata/records.jsonl", f"{ROOT}/presidential_statements/pdfs"),
"verbatim_debates": (f"{ROOT}/verbatim_debates/metadata/records.jsonl", f"{ROOT}/verbatim_debates/pdfs"),
"documents": (f"{ROOT}/documents/metadata/records.jsonl", f"{ROOT}/documents/pdfs"),
}
MIN_CPP = 60.0
MAX_GARBAGE = 0.20
NORMAL = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 \t\n\r.,;:!?'\"()[]{}/-–—%&$#@*+=<>|°§")
_lock = threading.Lock()
def safe_name(s):
return re.sub(r"[^A-Za-z0-9.]+", "_", s).strip("_")
def measure(path):
try:
out = subprocess.run(["pdftotext", "-l", "6", "-q", path, "-"],
capture_output=True, timeout=60).stdout.decode("utf-8", "ignore")
except Exception:
return None
pages = out.count("\x0c") + 1
text = out.replace("\x0c", "")
non_space = [c for c in text if not c.isspace()]
n = len(non_space)
cpp = len(text) / max(pages, 1)
if n == 0:
return (pages, cpp, 1.0)
garbage = sum(1 for c in non_space if c not in NORMAL) / n
return (pages, cpp, garbage)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=10)
ap.add_argument("--out", default=f"{ROOT}/documents/ocr_flags.tsv")
ap.add_argument("--resume", action="store_true")
args = ap.parse_args()
done = set()
if args.resume and os.path.exists(args.out):
for line in open(args.out):
done.add(line.split("\t")[4] if line.count("\t") >= 4 else "")
tasks = []
for fam, (jl, pdir) in FAMILIES.items():
for r in (json.loads(l) for l in open(jl)):
base = safe_name(r.get("symbol") or r["record_id"])
fp = os.path.join(pdir, f"{base}-EN.pdf")
if os.path.exists(fp) and os.path.getsize(fp) > 1000 and fp not in done:
tasks.append((fam, r, fp))
print(f"measuring {len(tasks)} PDFs (resume skipped {len(done)})", flush=True)
mode = "a" if (args.resume and os.path.exists(args.out)) else "w"
fh = open(args.out, mode)
if mode == "w":
fh.write("family\tsymbol\trecord_id\tdate\tpath\tpages\tcpp\tgarbage\tneeds_ocr\n")
counts = {"flagged": 0, "ok": 0, "err": 0, "n": 0}
def one(t):
fam, r, fp = t
m = measure(fp)
with _lock:
counts["n"] += 1
if m is None:
counts["err"] += 1
flag = "ERROR"
pages = cpp = garb = -1
else:
pages, cpp, garb = m
need = (cpp < MIN_CPP) or (garb > MAX_GARBAGE)
flag = "YES" if need else "no"
counts["flagged" if need else "ok"] += 1
fh.write(f"{fam}\t{r.get('symbol')}\t{r['record_id']}\t{r.get('date')}\t{fp}\t"
f"{pages}\t{cpp:.0f}\t{garb:.3f}\t{flag}\n")
if counts["n"] % 2000 == 0:
fh.flush()
print(f" {counts['n']}/{len(tasks)} flagged={counts['flagged']} "
f"ok={counts['ok']} err={counts['err']}", flush=True)
with ThreadPoolExecutor(max_workers=args.workers) as ex:
list(ex.map(one, tasks))
fh.close()
print(f"DONE: {counts['n']} measured | needs_ocr={counts['flagged']} | "
f"clean={counts['ok']} | errors={counts['err']} -> {args.out}", flush=True)
if __name__ == "__main__":
main()
|