unsc-corpus / scripts /download_856_fallback.py
cemalatas's picture
Initial commit
39a78f4
Raw
History Blame Contribute Delete
4.53 kB
#!/usr/bin/env python3
import argparse, json, os, re, threading, time
from concurrent.futures import ThreadPoolExecutor
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import itertools
OUT = os.environ.get("UNSC_CORPUS_ROOT", ".")
PROXY_FILE = os.environ.get("UNSC_PROXY_FILE", "proxies.txt")
FAMILIES = ["resolutions", "presidential_statements", "verbatim_debates"]
_lock = threading.Lock()
def log(m):
with _lock:
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
def safe_name(s):
return re.sub(r"[^A-Za-z0-9.]+", "_", s).strip("_")
class Rotator:
def __init__(self, path):
self.sessions = []
for line in open(path):
line = line.strip()
if not line:
continue
ip, port, user, pw = line.split(":")
s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=Retry(
total=2, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504],
allowed_methods=["GET"]), pool_maxsize=4))
u = f"http://{user}:{pw}@{ip}:{port}"
s.proxies = {"http": u, "https": u}
self.sessions.append(s)
self._cyc = itertools.cycle(self.sessions)
self._lk = threading.Lock()
log(f"loaded {len(self.sessions)} proxies")
def get(self, url, timeout, attempts=6):
last = None
for _ in range(attempts):
with self._lk:
s = next(self._cyc)
try:
r = s.get(url, timeout=timeout)
if r.status_code == 429:
last = "429"
continue
return r
except Exception as e:
last = e
raise last if isinstance(last, Exception) else RuntimeError(str(last))
def pending(cat, langs):
recs = [json.loads(l) for l in open(f"{OUT}/{cat}/metadata/records.jsonl")]
pdir = f"{OUT}/{cat}/pdfs"
os.makedirs(pdir, exist_ok=True)
tasks = []
for r in recs:
sym = r.get("symbol")
files = r.get("files") or {}
if not sym:
continue
for lang in langs:
url = files.get(lang.upper())
if not url:
continue
fp = f"{pdir}/{safe_name(sym)}-{lang.upper()}.pdf"
if os.path.exists(fp) and os.path.getsize(fp) > 1000:
continue
tasks.append((sym, url, fp))
return tasks
def run(cat, langs, workers, rot):
tasks = pending(cat, langs)
if not tasks:
log(f"[{cat}] nothing missing")
return
log(f"[{cat}] {len(tasks)} PDFs to fetch via 856 fallback")
dead = 0
p = 0
while tasks:
p += 1
still, ok = [], 0
lk = threading.Lock()
def one(t):
nonlocal ok
sym, url, fp = t
try:
r = rot.get(url, timeout=60)
if r.content[:4] != b"%PDF":
raise ValueError(f"not pdf ({len(r.content)}B)")
tmp = fp + ".part"
with open(tmp, "wb") as fh:
fh.write(r.content)
os.replace(tmp, fp)
with lk:
ok += 1
except Exception:
with lk:
still.append(t)
t0 = time.time()
with ThreadPoolExecutor(max_workers=workers) as ex:
list(ex.map(one, tasks))
dt = time.time() - t0
tasks = still
log(f"[{cat}] pass {p}: +{ok}, {len(tasks)} left ({ok/dt:.1f}/s)")
if not tasks:
break
dead = dead + 1 if ok == 0 else 0
small = len(tasks) <= 25
if (small and dead >= 2) or dead >= 15:
log(f"[{cat}] {len(tasks)} unavailable; recording")
with open(f"{OUT}/{cat}/pdf_856_errors.log", "w") as fh:
for sym, url, _ in tasks:
fh.write(f"{sym}\t{url}\n")
break
time.sleep(20 if (dead == 0 or small) else min(300, 45 * 2 ** dead))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", nargs="*", choices=FAMILIES)
ap.add_argument("--langs", nargs="*", default=["en"])
ap.add_argument("--workers", type=int, default=8)
args = ap.parse_args()
rot = Rotator(PROXY_FILE)
for cat in (args.only or FAMILIES):
run(cat, args.langs, args.workers, rot)
log("ALL DONE")
if __name__ == "__main__":
main()