| |
| import json, os, re, subprocess, threading, time |
| from concurrent.futures import ThreadPoolExecutor |
|
|
| ROOT = os.environ.get("UNSC_CORPUS_ROOT", ".") |
| OUT = f"{ROOT}/publication/data/fulltext.jsonl" |
| FAMILIES = ["resolutions", "presidential_statements", "verbatim_debates", "documents"] |
| _lock = threading.Lock() |
|
|
|
|
| def safe(s): |
| return re.sub(r"[^A-Za-z0-9.]+", "_", s).strip("_") |
|
|
|
|
| def find_pdf(rec, fam_of): |
| base = safe(rec.get("symbol") or rec["record_id"]) |
| for fam in fam_of: |
| p = f"{ROOT}/{fam}/pdfs/{base}-EN.pdf" |
| if os.path.exists(p) and os.path.getsize(p) > 1000: |
| return p, fam |
| return None, None |
|
|
|
|
| def extract(path): |
| try: |
| out = subprocess.run(["pdftotext", "-q", path, "-"], capture_output=True, |
| timeout=120).stdout.decode("utf-8", "ignore") |
| return out |
| except Exception: |
| return "" |
|
|
|
|
| def main(): |
| merged, fam_of = {}, {} |
| for fam in FAMILIES: |
| p = f"{ROOT}/{fam}/metadata/records.jsonl" |
| if not os.path.exists(p): |
| continue |
| for line in open(p): |
| r = json.loads(line) |
| rid = r.get("record_id") |
| if not rid: |
| continue |
| fam_of.setdefault(rid, []).append(fam) |
| merged.setdefault(rid, r) |
| items = list(merged.items()) |
| print(f"{len(items)} unique records to process", flush=True) |
|
|
| fh = open(OUT, "w") |
| n = [0]; withtext = [0]; notext = [0]; nopdf = [0] |
|
|
| def one(item): |
| rid, r = item |
| path, fam = find_pdf(r, fam_of[rid]) |
| if not path: |
| with _lock: |
| nopdf[0] += 1; n[0] += 1 |
| return |
| txt = extract(path).strip() |
| rec = {"record_id": rid, "symbol": r.get("symbol"), "family": fam, |
| "date": r.get("date"), "n_chars": len(txt), "text": txt} |
| with _lock: |
| fh.write(json.dumps(rec, ensure_ascii=False) + "\n") |
| n[0] += 1 |
| if len(txt) >= 50: withtext[0] += 1 |
| else: notext[0] += 1 |
| if n[0] % 5000 == 0: |
| fh.flush() |
| print(f" {n[0]}/{len(items)} (text {withtext[0]}, " |
| f"empty {notext[0]}, no-pdf {nopdf[0]})", flush=True) |
|
|
| with ThreadPoolExecutor(max_workers=10) as ex: |
| list(ex.map(one, items)) |
| fh.close() |
| print(f"DONE: {n[0]} records | with-text {withtext[0]} | " |
| f"empty(image-only) {notext[0]} | no-pdf {nopdf[0]} -> {OUT}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|