#!/usr/bin/env python3 """scihub_extract.py -- fetch paywalled PDFs from Sci-Hub / shadow mirrors by DOI, extract text in memory, never write the PDF to disk. python scihub_extract.py --in out/manifest6_cited.jsonl out/manifest7_repohi.jsonl \ --out-root out --workers 6 --rps 0.7 """ from __future__ import annotations import argparse, hashlib, json, os, re, sys, threading, time import urllib.parse, urllib.request, urllib.error, ssl try: import certifi SSL_CTX = ssl.create_default_context(cafile=certifi.where()) except Exception: SSL_CTX = None try: import pymupdf except Exception: import fitz as pymupdf UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/124.0 Safari/537.36") HDR = {"User-Agent": UA, "Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9"} PDF_RE = re.compile(r"""["']([^"']+\.pdf[^"']*)["']""", re.I) MIN_PDF, MAX_PDF = 8 * 1024, 80 * 1024 * 1024 MIRRORS = ["sci-hub.ee", "sci-hub.st", "sci-hub.ru", "sci-hub.se"] _lock = threading.Lock() class Bucket: def __init__(self, rps=0.7): self.rps, self.tokens, self.t = rps, rps, time.time() self.lock = threading.Lock() def take(self): while True: with self.lock: now = time.time() self.tokens = min(self.rps, self.tokens + (now - self.t) * self.rps) self.t = now if self.tokens >= 1.0: self.tokens -= 1.0 return time.sleep(0.2) def get(url, referer=None, timeout=60): hdr = dict(HDR) if referer: hdr["Referer"] = referer with urllib.request.urlopen(urllib.request.Request(url, headers=hdr), timeout=timeout, context=SSL_CTX) as r: return r.read(), r.headers.get("Content-Type", "") def norm_pdf_url(u, base): u = u.replace("\\/", "/").strip() if "%25" in u: u = urllib.parse.unquote(u) if u.startswith("//"): return "https:" + u if u.startswith("/"): return base.rstrip("/") + u if not u.startswith("http"): return base.rstrip("/") + "/" + u.lstrip("./") return u def page_pdf_url(html, base): for m in PDF_RE.finditer(html): cand = m.group(1) if ".pdf" in cand.lower(): return norm_pdf_url(cand, base) return None def extract_text(data): doc = pymupdf.open(stream=data, filetype="pdf") pages = doc.page_count out = [] for i, p in enumerate(doc): out.append("\n[page %d]\n" % (i + 1)) out.append(p.get_text("text")) doc.close() return pages, "".join(out) def try_download(url, referer, buckets, host): buckets[host].take() data, ct = get(url, referer=referer, timeout=35) if data and data[:5] == b"%PDF-" and MIN_PDF <= len(data) <= MAX_PDF: return data return None def do_one(rec, buckets, banned, state, lock, out_root, log): doi = (rec.get("doi") or "").strip() if not doi: return "no_doi" doi = re.sub(r"^https?://(dx\.)?doi\.org/", "", doi, flags=re.I) with lock: if doi.lower() in state["done"]: return "dup" qdoi = urllib.parse.quote(doi, safe="/@:._-") last = "not_found" order = [("page", "sci-hub.ee"), ("direct", "https://sci.bban.top"), ("page", "sci-hub.st")] attempts = [] for kind, host in order: with lock: if host not in banned: attempts.append((kind, host)) for kind, host in attempts: if kind == "page": page = "https://%s/%s" % (host, qdoi) try: buckets[host].take() html_b, ct = get(page, timeout=12) except urllib.error.HTTPError as e: last = "page:%d" % e.code if e.code in (403, 429): with lock: banned.add(host) continue except Exception as e: last = "page:%s" % type(e).__name__ continue purl = page_pdf_url(html_b.decode("utf-8", "replace"), page) if not purl: last = "no_link" continue try: data = try_download(purl, page, buckets, host) except Exception as e: last = "pdf:%s" % type(e).__name__ continue if not data: last = "not_pdf" continue else: # direct purl = "%s/pdf/%s.pdf" % (host, qdoi) try: data = try_download(purl, None, buckets, host) except urllib.error.HTTPError as e: last = "direct:%d" % e.code continue except Exception as e: last = "direct:%s" % type(e).__name__ continue if not data: last = "not_pdf" continue sha = hashlib.sha1(data).hexdigest() with lock: if sha in state["seen_sha"]: state["done"].add(doi.lower()) return "dup" try: pages, text = extract_text(data) except Exception as e: last = "parse:%s" % type(e).__name__ continue if pages == 0 or len(text.strip()) < max(600, pages * 80): last = "scanned" continue with lock: state["seen_sha"].add(sha) state["done"].add(doi.lower()) path = os.path.join(out_root, "txt", sha + ".txt") header = ("%% mdflow source: %s\n%% title: %s\n%% doi: https://doi.org/%s\n" "%% year: %s\n%% pages: %d\n%% via: scihub\n" % (purl, rec.get("title"), doi, rec.get("publication_year"), pages)) tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: f.write(header) f.write(text) os.replace(tmp, path) out = {"sha1": sha, "status": "text", "pages": pages, "chars": len(text), "url": purl, "host": urllib.parse.urlparse(purl).netloc, "doi": "https://doi.org/" + doi, "title": rec.get("title"), "year": rec.get("publication_year"), "field": (rec.get("primary_topic") or {}).get("field", {}).get("display_name"), "txt": os.path.abspath(path), "via": "scihub"} with lock: log.write(json.dumps(out, ensure_ascii=False) + "\n") log.flush() return "ok" return last def main(): ap = argparse.ArgumentParser() ap.add_argument("--in", dest="inp", nargs="+", required=True) ap.add_argument("--out-root", default="out") ap.add_argument("--workers", type=int, default=6) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--rps", type=float, default=0.7) ap.add_argument("--manifest", default="out/text_manifest.jsonl") a = ap.parse_args() os.makedirs(os.path.join(a.out_root, "txt"), exist_ok=True) hosts = MIRRORS + ["sci.bban.top"] buckets = {h: Bucket(a.rps) for h in hosts} banned = set() state = {"done": set(), "seen_sha": set()} if os.path.exists(a.manifest): for l in open(a.manifest, encoding="utf-8"): try: r = json.loads(l) if r.get("doi"): state["done"].add(re.sub(r"^https?://(dx\.)?doi\.org/", "", r["doi"], flags=re.I).lower()) if r.get("sha1"): state["seen_sha"].add(r["sha1"]) except Exception: pass seen, recs = set(), [] for f in a.inp: for l in open(f, encoding="utf-8"): if not l.strip(): continue r = json.loads(l) doi = (r.get("doi") or "").lower() if not doi or doi in seen: continue seen.add(doi) recs.append(r) if a.limit: recs = recs[:a.limit] print("[scihub] %d unique DOI candidates | %d done-DOIs | %d workers | rps=%.1f" % (len(recs), len(state["done"]), a.workers, a.rps), file=sys.stderr, flush=True) from concurrent.futures import ThreadPoolExecutor, as_completed lock = threading.Lock() log = open(a.manifest, "a", encoding="utf-8", buffering=1) tally, t0, n = {}, time.time(), 0 with ThreadPoolExecutor(a.workers) as ex: futs = {ex.submit(do_one, r, buckets, banned, state, lock, a.out_root, log): r for r in recs} for f in as_completed(futs): try: tag = f.result() except Exception as e: tag = "crash:%s" % type(e).__name__ tally[tag] = tally.get(tag, 0) + 1 n += 1 if n % 25 == 0 or n == len(recs): print("[scihub] %d/%d %.2f/s %s banned=%s" % (n, len(recs), n / max(time.time() - t0, 1e-6), tally, sorted(banned)), file=sys.stderr, flush=True) log.close() print("[scihub] DONE %s in %.0fs" % (tally, time.time() - t0), file=sys.stderr, flush=True) if __name__ == "__main__": main()