File size: 9,484 Bytes
eadaa58 | 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | #!/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()
|