File size: 8,985 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
#!/usr/bin/env python3
"""extract.py -- stream each candidate PDF into memory and write page-marked text.



No PDF is written to disk. Text goes to out/txt/<sha1>.txt; a sidecar line goes

to the text manifest. Scanned / text-less files are recorded, not silently kept.



  python extract.py --in out/manifest.jsonl --out-root out --workers 32 --limit 500

"""
from __future__ import annotations
import argparse, hashlib, io, json, os, re, sys, threading, time
import urllib.parse, urllib.request, urllib.error, ssl
from concurrent.futures import ThreadPoolExecutor, as_completed

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 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0 Safari/537.36 mdflow/0.1")
REPO_KEYS = ("eprints", "repository", "repo.", "dspace", "ir.", "iris.", "lirias",
             "edoc", "curis", "repositorio", "sfx", "ntrs", "citeseerx", "core.ac.uk",
             "hal.science", "hal.archives", "osf.io", "d-nb.info", "jstage.jst.go.jp",
             "arxiv.org", "scielo", "redalyc", "doaj.org", "mdpi.com", "frontiersin",
             "plos.org", "jstatsoft.org", "aimsciences", "projecteuclid", "numdam",
             "iucr.org", "copernicus.org", "aanda.org", "epj.org", "dialnet",
             "diva-portal", "europepmc", "ncbi.nlm.nih.gov/pmc", "osti.gov",
             "zenodo.org", "figshare", "hal.", "openaire", "ssoar", "unipa",
             "bibnum", "kuleuven", "ugent", "ds.lib", "digitalcommons", "scholarworks")
PUB_BLOCK = ("sciencedirect.com", "onlinelibrary.wiley.com", "link.springer",
             "nature.com", "cell.com", "ieeexplore.ieee", "pubs.acs.org",
             "tandfonline", "jamanetwork", "nejm.org", "academic.oup", "lww.com",
             "sagepub", "thelancet", "link.aps.org", "aip.scitation", "pubs.aip",
             "worldscientific", "brill.com", "emerald", "ingentaconnect",
             "eurekaselect", "scitepress")
MIN_PDF = 8 * 1024
MAX_PDF = 80 * 1024 * 1024
HDR = {"User-Agent": UA, "Accept": "application/pdf,*/*"}


def dkey(u):
    p = urllib.parse.urlparse(u)
    return (p.netloc.lower(), p.path.rstrip("/").lower())


def tier(u):
    full = (urllib.parse.urlparse(u).netloc + urllib.parse.urlparse(u).path).lower()
    if any(b in full for b in PUB_BLOCK):
        return 2
    if any(g in full for g in REPO_KEYS):
        return 0
    return 1


def cand_urls(rec, skip_pub=True):
    out, seen = [], set()
    for loc in [rec.get("best_oa_location")] + (rec.get("locations") or []):
        if not loc:
            continue
        for u in (loc.get("pdf_url"), loc.get("landing_page_url")):
            if not u:
                continue
            k = dkey(u)
            if k in seen:
                continue
            seen.add(k)
            out.append(u)
    out = [u for u in out if not (skip_pub and tier(u) == 2)]
    return sorted(out, key=lambda u: (tier(u), dkey(u)))


def fetch_bytes(url, budget=45.0):
    req = urllib.request.Request(url, headers=dict(HDR))
    started = time.time()
    with urllib.request.urlopen(req, timeout=30, context=SSL_CTX) as r:
        ct = r.headers.get("Content-Type", "").lower()
        if "html" in ct:
            return None, "html_instead"
        buf = io.BytesIO()
        while True:
            if time.time() - started > budget:
                return None, "too_slow"
            chunk = r.read(1 << 16)
            if not chunk:
                break
            buf.write(chunk)
            if buf.tell() > MAX_PDF:
                return None, "too_big"
    return buf.getvalue(), "ok"


def extract_text(data):
    doc = pymupdf.open(stream=data, filetype="pdf")
    pages = doc.page_count
    out = []
    for i, page in enumerate(doc):
        out.append("\n[page %d]\n" % (i + 1))
        out.append(page.get_text("text"))
    doc.close()
    return pages, "".join(out)


def do_one(rec, out_root, lock, state):
    rid = rec.get("id")
    sha = None
    txt_dir = os.path.join(out_root, "txt")
    urls = cand_urls(rec)
    if not urls:
        return {"id": rid, "status": "no_url"}
    last = "unreachable"
    for u in urls:
        try:
            data, tag = fetch_bytes(u)
        except urllib.error.HTTPError as e:
            last = "http_%d" % e.code
            continue
        except Exception as e:
            last = type(e).__name__
            continue
        if data is None:
            last = tag
            continue
        if data[:5] != b"%PDF-" or len(data) < MIN_PDF:
            last = "not_pdf"
            continue
        sha = hashlib.sha1(data).hexdigest()
        with lock:
            if sha in state["seen"]:
                return {"id": rid, "sha1": sha, "status": "dup"}
        try:
            pages, text = extract_text(data)
        except Exception as e:
            last = "parse:" + type(e).__name__
            continue
        chars = len(text.strip())
        min_chars = max(600, pages * 80)
        if pages == 0 or chars < min_chars:
            with lock:
                state["seen"].add(sha)
            return {"id": rid, "sha1": sha, "status": "scanned", "pages": pages,
                    "chars": chars, "url": u, "host": urllib.parse.urlparse(u).netloc}
        with lock:
            state["seen"].add(sha)
        path = os.path.join(txt_dir, sha + ".txt")
        tmp = path + ".tmp"
        header = ("%% mdflow source: %s\n%% title: %s\n%% doi: %s\n%% year: %s\n%% pages: %d\n"
                  % (u, rec.get("title"), rec.get("doi"), rec.get("publication_year"), pages))
        with open(tmp, "w", encoding="utf-8") as f:
            f.write(header)
            f.write(text)
        os.replace(tmp, path)
        return {"id": rid, "sha1": sha, "status": "text", "pages": pages, "chars": chars,
                "url": u, "host": urllib.parse.urlparse(u).netloc,
                "doi": rec.get("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)}
    return {"id": rid, "status": "fail", "err": last}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in", dest="inp", required=True)
    ap.add_argument("--out-root", default="out")
    ap.add_argument("--workers", type=int, default=32)
    ap.add_argument("--limit", type=int, default=0)
    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)
    recs = [json.loads(l) for l in open(a.inp, encoding="utf-8") if l.strip()]
    if a.limit:
        recs = recs[:a.limit]

    state = {"seen": set()}
    if os.path.exists(a.manifest):
        for l in open(a.manifest, encoding="utf-8"):
            try:
                r = json.loads(l)
                if r.get("sha1"):
                    state["seen"].add(r["sha1"])
            except Exception:
                pass
    lock = threading.Lock()
    done_ids = set()
    if os.path.exists(a.manifest):
        for l in open(a.manifest, encoding="utf-8"):
            try:
                done_ids.add(json.loads(l).get("id"))
            except Exception:
                pass

    todo = [r for r in recs if r.get("id") not in done_ids]
    print("[extract] %d total | %d already done | %d todo | %d workers"
          % (len(recs), len(recs) - len(todo), len(todo), a.workers), file=sys.stderr)
    mfh = open(a.manifest, "a", encoding="utf-8", buffering=1)
    tally, t0, n = {}, time.time(), 0
    try:
        with ThreadPoolExecutor(a.workers) as ex:
            futs = {ex.submit(do_one, r, a.out_root, lock, state): r for r in todo}
            for f in as_completed(futs):
                try:
                    res = f.result()
                except Exception as e:
                    res = {"status": "crash", "err": "%s: %s" % (type(e).__name__, e)}
                tally[res["status"]] = tally.get(res["status"], 0) + 1
                if res.get("status") in ("text", "scanned"):
                    res["title"] = res.get("title") or futs[f].get("title")
                    mfh.write(json.dumps(res, ensure_ascii=False) + "\n")
                n += 1
                if n % 25 == 0 or n == len(todo):
                    print("[extract] %d/%d %s %.1f/s" % (n, len(todo), tally,
                          n / max(time.time() - t0, 1e-6)), file=sys.stderr)
    finally:
        mfh.close()
    print("[extract] DONE %s in %.0fs" % (tally, time.time() - t0), file=sys.stderr)


if __name__ == "__main__":
    main()