File size: 2,553 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 | #!/usr/bin/env python3
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()
|