Download scripts/r5_print/r5_print_fetch.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_print/r5_print_fetch.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_print/r5_print_fetch.py
-
curl -L -o r5_print_fetch.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_print/r5_print_fetch.py
10 kB
| #!/usr/bin/env python3 | |
| """R5 PRINT stage A2: fetch the original PDFs of the candidate list (download only, no parsing). | |
| Each document goes into its own folder RAW/<lang>/<docid>/doc.pdf with meta.json beside it. | |
| Downloaded files are untrusted data and are never executed or opened here (only the first bytes are | |
| checked for the %PDF magic). A host that answers 401/403/429/451 is dropped for the rest of the run | |
| (no bypass); a host with 3 connection failures is dropped too. At most one request per host per second. | |
| Usage: | |
| python -I r5_print_fetch.py cand CANDIDATE_DIR RAW_DIR CFG TARGET | |
| python -I r5_print_fetch.py tbmm RAW_DIR TERMS(comma list) PER_TERM_YEAR SEED | |
| """ | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import re | |
| import sys | |
| import threading | |
| import time | |
| import concurrent.futures as cf | |
| from urllib.parse import urlparse | |
| import requests | |
| MAX_BYTES = 80 * 1024 * 1024 | |
| DEADLINE_S = 100 | |
| HOST_LOCK = {} | |
| HOST_LAST = {} | |
| HOST_FAIL = {} | |
| BLOCKED = set() | |
| G = threading.Lock() | |
| COUNT = {"ok": 0} | |
| def host_lock(h): | |
| with G: | |
| if h not in HOST_LOCK: | |
| HOST_LOCK[h] = threading.Lock() | |
| HOST_LAST[h] = 0.0 | |
| return HOST_LOCK[h] | |
| def fetch(url, dest_pdf, host, timeout=(8, 25)): | |
| """returns (status, reason, nbytes, sha256)""" | |
| lk = host_lock(host) | |
| with lk: | |
| if host in BLOCKED: | |
| return ("skipped", "host blocked earlier", 0, "") | |
| wait = 1.0 - (time.time() - HOST_LAST[host]) | |
| if wait > 0: | |
| time.sleep(wait) | |
| t0 = time.time() | |
| try: | |
| r = requests.get(url, stream=True, timeout=timeout, allow_redirects=True, | |
| headers={"Accept": "application/pdf,*/*;q=0.5"}) | |
| except Exception as e: # connection problems, TLS errors, timeouts | |
| HOST_LAST[host] = time.time() | |
| with G: | |
| HOST_FAIL[host] = HOST_FAIL.get(host, 0) + 1 | |
| if HOST_FAIL[host] >= 3: | |
| BLOCKED.add(host) | |
| return ("error", type(e).__name__, 0, "") | |
| HOST_LAST[host] = time.time() | |
| if r.status_code in (401, 403, 429, 451): | |
| with G: | |
| BLOCKED.add(host) | |
| r.close() | |
| return (str(r.status_code), "refused; host dropped", 0, "") | |
| if r.status_code != 200: | |
| r.close() | |
| return (str(r.status_code), "not 200", 0, "") | |
| h = hashlib.sha256() | |
| n = 0 | |
| first = b"" | |
| tmp = dest_pdf + ".part" | |
| os.makedirs(os.path.dirname(dest_pdf), exist_ok=True) | |
| try: | |
| with open(tmp, "wb") as fo: | |
| for chunk in r.iter_content(chunk_size=1 << 16): | |
| if not chunk: | |
| continue | |
| if not first: | |
| first = chunk[:1024] | |
| if b"%PDF" not in first: | |
| r.close() | |
| fo.close() | |
| os.remove(tmp) | |
| return ("notpdf", "no %PDF magic in first 1 KB", 0, "") | |
| n += len(chunk) | |
| if n > MAX_BYTES: | |
| r.close() | |
| fo.close() | |
| os.remove(tmp) | |
| return ("toolarge", f">{MAX_BYTES} bytes", n, "") | |
| if time.time() - t0 > DEADLINE_S: | |
| r.close() | |
| fo.close() | |
| os.remove(tmp) | |
| return ("slow", f">{DEADLINE_S}s", n, "") | |
| h.update(chunk) | |
| fo.write(chunk) | |
| except Exception as e: | |
| try: | |
| os.remove(tmp) | |
| except OSError: | |
| pass | |
| return ("error", "stream " + type(e).__name__, n, "") | |
| if n < 1000: | |
| os.remove(tmp) | |
| return ("tiny", "under 1000 bytes", n, "") | |
| os.replace(tmp, dest_pdf) | |
| return ("ok", "", n, h.hexdigest()) | |
| def do_candidate(c, raw, target, logf): | |
| if COUNT["ok"] >= target: | |
| return None | |
| docid = c["lang"] + "_" + hashlib.sha1(c["url"].encode()).hexdigest()[:10] | |
| d = os.path.join(raw, c["lang"], docid) | |
| if os.path.exists(os.path.join(d, "meta.json")): | |
| return "exists" | |
| st, why, n, sha = fetch(c["url"], os.path.join(d, "doc.pdf"), c["host"]) | |
| rec = {"docid": docid, "url": c["url"], "host": c["host"], "status": st, "why": why, | |
| "bytes": n, "sha256": sha, "t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} | |
| with G: | |
| logf.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| logf.flush() | |
| if st == "ok": | |
| COUNT["ok"] += 1 | |
| if st == "ok": | |
| meta = {"docid": docid, "lang": c["lang"], "url": c["url"], "host": c["host"], "bytes": n, | |
| "sha256": sha, "source": "finepdfs", "finepdfs_id": c.get("id"), "finepdfs_cfg": c.get("cfg"), | |
| "finepdfs_dump": c.get("dump"), "finepdfs_pages": c.get("pages"), | |
| "fetched_utc": rec["t"]} | |
| with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as fm: | |
| json.dump(meta, fm, ensure_ascii=False) | |
| return st | |
| def run_cand(cand_dir, raw, cfg, target): | |
| cands = [json.loads(x) for x in open(os.path.join(cand_dir, f"candidates_{cfg}.jsonl"), encoding="utf-8")] | |
| lang = cands[0]["lang"] | |
| os.makedirs(os.path.join(raw, "_fetch"), exist_ok=True) | |
| # count what already exists (resume) | |
| ld = os.path.join(raw, lang) | |
| if os.path.isdir(ld): | |
| COUNT["ok"] = sum(1 for x in os.listdir(ld) if os.path.exists(os.path.join(ld, x, "meta.json"))) | |
| print(cfg, "candidates", len(cands), "already", COUNT["ok"], "target", target, flush=True) | |
| with open(os.path.join(raw, "_fetch", f"fetch_log_{cfg}.jsonl"), "a", encoding="utf-8") as logf: | |
| with cf.ThreadPoolExecutor(max_workers=12) as ex: | |
| futs = [ex.submit(do_candidate, c, raw, target, logf) for c in cands] | |
| stats = {} | |
| for f in cf.as_completed(futs): | |
| try: | |
| r = f.result() | |
| except Exception as e: | |
| r = "exc:" + type(e).__name__ | |
| if r is not None: | |
| stats[r] = stats.get(r, 0) + 1 | |
| print(cfg, "done", json.dumps(stats), "ok_total", COUNT["ok"], "blocked_hosts", len(BLOCKED), flush=True) | |
| with open(os.path.join(raw, "_fetch", f"fetch_summary_{cfg}.json"), "w") as fo: | |
| json.dump({"cfg": cfg, "lang": lang, "candidates": len(cands), "stats": stats, | |
| "ok_total": COUNT["ok"], "blocked_hosts": sorted(BLOCKED)}, fo, indent=1) | |
| def get_text(url, timeout=(8, 30)): | |
| host = urlparse(url).netloc | |
| lk = host_lock(host) | |
| with lk: | |
| wait = 1.0 - (time.time() - HOST_LAST[host]) | |
| if wait > 0: | |
| time.sleep(wait) | |
| r = requests.get(url, timeout=timeout) | |
| HOST_LAST[host] = time.time() | |
| if r.status_code != 200: | |
| raise RuntimeError(f"{r.status_code} {url}") | |
| return r.text | |
| def run_tbmm(raw, terms, per, seed): | |
| """TBMM minutes: sitting list pages -> sitting page -> 'Basilmis' (printed) PDF on cdn.tbmm.gov.tr.""" | |
| rng = random.Random(int(seed)) | |
| os.makedirs(os.path.join(raw, "_fetch"), exist_ok=True) | |
| logf = open(os.path.join(raw, "_fetch", "fetch_log_tbmm.jsonl"), "a", encoding="utf-8") | |
| base = "https://www.tbmm.gov.tr" | |
| for term in [int(t) for t in terms.split(",")]: | |
| for year in range(1, 6): | |
| try: | |
| html = get_text(f"{base}/Tutanaklar/DoneminTutanakMetinleri?Donem={term}&YasamaYili={year}") | |
| except Exception as e: | |
| print("list fail", term, year, e, flush=True) | |
| continue | |
| ids = sorted(set(re.findall(r"/Tutanaklar/Tutanak\?Id=([0-9a-fA-F-]{36})", html))) | |
| if not ids: | |
| continue | |
| rng.shuffle(ids) | |
| got = 0 | |
| for tid in ids: | |
| if got >= per: | |
| break | |
| try: | |
| page = get_text(f"{base}/Tutanaklar/Tutanak?Id={tid}") | |
| except Exception as e: | |
| print("sitting fail", tid, e, flush=True) | |
| continue | |
| m = re.search(r"https://cdn\.tbmm\.gov\.tr/TbmmWeb/Tutanak/(\d+)/(\d+)/(\d+)/Basilmis/[0-9a-fA-F-]{36}\.pdf", page) | |
| if not m: | |
| continue | |
| url = m.group(0) | |
| docid = f"tr_tbmm_d{m.group(1)}y{m.group(2)}b{m.group(3)}" | |
| d = os.path.join(raw, "tr", docid) | |
| if os.path.exists(os.path.join(d, "meta.json")): | |
| got += 1 | |
| continue | |
| st, why, n, sha = fetch(url, os.path.join(d, "doc.pdf"), "cdn.tbmm.gov.tr", timeout=(10, 60)) | |
| rec = {"docid": docid, "url": url, "host": "cdn.tbmm.gov.tr", "status": st, "why": why, | |
| "bytes": n, "sha256": sha, "t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} | |
| logf.write(json.dumps(rec) + "\n") | |
| logf.flush() | |
| print(docid, st, n, flush=True) | |
| if st == "ok": | |
| got += 1 | |
| with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as fm: | |
| json.dump({"docid": docid, "lang": "tr", "url": url, "host": "cdn.tbmm.gov.tr", | |
| "bytes": n, "sha256": sha, "source": "tbmm_minutes", | |
| "term": int(m.group(1)), "legislative_year": int(m.group(2)), | |
| "sitting": int(m.group(3)), "fetched_utc": rec["t"]}, fm) | |
| if __name__ == "__main__": | |
| mode = sys.argv[1] | |
| if mode == "cand": | |
| run_cand(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5])) | |
| elif mode == "tbmm": | |
| run_tbmm(sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5]) | |
| else: | |
| raise SystemExit("mode?") | |