| |
| 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() |
|
|