unsc-corpus / scripts /supplement_documents.py
cemalatas's picture
Initial commit
39a78f4
Raw
History Blame Contribute Delete
2.06 kB
import json, os, re, sys, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import scrape_unsc as U
CC="Security Council"; PBASE='989:"Documents and Publications"'
ROOT = os.environ.get("UNSC_CORPUS_ROOT", ".")
OUT=f"{ROOT}/documents"; mdir=f"{OUT}/metadata/marcxml"
def cnt(pool,p):
r=pool.get(f"{U.BASE}/search",params={"cc":CC,"p":p,"rg":1,"ln":"en"},timeout=60)
m=re.search(r"<strong>([0-9,]+)</strong>\s*records found",r.text,re.I)
return int(m.group(1).replace(",","")) if m else 0
def page(pool,p,tag,so,sf,recs):
jrec,pi=1,0
while True:
pi+=1
raw=f"{mdir}/{tag}_{sf}{so}_p{pi:02d}.xml"
if os.path.exists(raw) and os.path.getsize(raw)>200: xml=open(raw,"rb").read()
else:
r=pool.get(f"{U.BASE}/search",params={"cc":CC,"p":p,"of":"xm","rg":200,"jrec":jrec,"so":so,"sf":sf},timeout=90)
xml=r.content; open(raw,"wb").write(xml)
b=len(recs)
for rec in U.parse_page(xml):
pr=U.parse_record(rec)
if pr.get("record_id"): recs[pr["record_id"]]=pr
if len(recs)==b: break
jrec+=200
def main():
pool=U.ProxyPool(U.PROXY_FILE)
recs={json.loads(l)["record_id"]:json.loads(l) for l in open(f"{OUT}/metadata/records.jsonl")}
U.log(f"start with {len(recs)}")
sorts=[("d","title"),("a","author"),("d","author"),("a","005"),("d","005"),("d","245")]
for year in range(1946,2027):
yc=cnt(pool,f"{PBASE} and year:{year}")
if yc<=650: continue
before=len(recs)
for so,sf in sorts:
page(pool,f"{PBASE} and year:{year}",str(year),so,sf,recs)
U.log(f"{year}: +{len(recs)-before} (now {len(recs)})")
tmp=f"{OUT}/metadata/records.jsonl.tmp"
with open(tmp,"w") as fh:
for r in sorted(recs.values(),key=lambda x:(x.get('date') or '',x.get('symbol') or '')):
fh.write(json.dumps(r,ensure_ascii=False)+"\n")
os.replace(tmp,f"{OUT}/metadata/records.jsonl")
U.log(f"DONE supplement: {len(recs)}")
main()