File size: 4,048 Bytes
356ffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download Europe PMC full-text XML for each PMCID given and render it to plain text.

XML  -> _raw/europepmc/fulltext/<PMCID>.xml   (raw, never committed)
text -> _raw/europepmc/text/<PMCID>.txt       (derived, regenerated by the build)
Tables are rendered row by row, cells separated by ' | ', under a 'TABLE <label>' header,
so that extraction rows can quote them verbatim.
"""
import sys, time, pathlib, urllib.request
import xml.etree.ElementTree as ET
ROOT = pathlib.Path(__file__).resolve().parents[2] / "_raw" / "europepmc"
XML = ROOT / "fulltext"; TXT = ROOT / "text"
XML.mkdir(parents=True, exist_ok=True); TXT.mkdir(parents=True, exist_ok=True)

def fetch(pmcid):
    fn = XML / f"{pmcid}.xml"
    if not fn.exists() or fn.stat().st_size < 200:
        url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML"
        with urllib.request.urlopen(url, timeout=90) as r:
            fn.write_bytes(r.read())
        time.sleep(0.3)
    return fn

def text_of(el):
    return " ".join("".join(el.itertext()).split())

def render(fn):
    root = ET.parse(fn).getroot()
    out = []
    front = root.find("front")
    if front is not None:
        t = front.find(".//article-title")
        if t is not None: out.append("TITLE: " + text_of(t))
        for aid in front.iter("article-id"):
            out.append(f"ID {aid.get('pub-id-type')}: {(aid.text or '').strip()}")
        lic = front.find(".//license")
        if lic is not None:
            href = lic.get("{http://www.w3.org/1999/xlink}href") or ""
            out.append("LICENSE: " + href + " " + text_of(lic)[:300])
    def walk(el, depth=0):
        for ch in el:
            tag = ch.tag
            if tag == "sec":
                t = ch.find("title")
                if t is not None: out.append("\n" + "#" * min(depth + 2, 4) + " " + text_of(t))
                walk(ch, depth + 1)
            elif tag == "p":
                # paragraphs may contain table-wrap; render text excluding them
                inner = [c for c in ch if c.tag in ("table-wrap", "fig")]
                for c in inner: ch.remove(c)
                s = text_of(ch)
                if s: out.append(s)
                for c in inner: walk_block(c)
            elif tag in ("table-wrap", "fig", "table-wrap-group"):
                walk_block(ch)
            elif tag in ("title",):
                continue
            else:
                walk(ch, depth)
    def walk_block(tw):
        seen.add(id(tw))
        if tw.tag == "table-wrap-group":
            for c in tw: walk_block(c)
            return
        lab = tw.find("label"); cap = tw.find("caption")
        kind = "TABLE" if tw.tag == "table-wrap" else "FIGURE"
        out.append(f"\n{kind} {text_of(lab) if lab is not None else ''}: {text_of(cap) if cap is not None else ''}")
        for tr in tw.iter("tr"):
            cells = [text_of(c) for c in tr if c.tag in ("td", "th")]
            out.append(" | ".join(cells))
        foot = tw.find("table-wrap-foot")
        if foot is not None: out.append("FOOTNOTE: " + text_of(foot))
        if tw.tag == "table-wrap" and tw.find(".//table") is None:
            out.append("[table present only as image in the XML]")
    seen = set()
    body = root.find("body")
    if body is not None: walk(body)
    # tables and figures placed outside <body> (e.g. <floats-group>) or missed above
    for tw in root.iter("table-wrap"):
        if id(tw) not in seen: walk_block(tw)
    back = root.find("back")
    if back is not None:
        for sm in back.iter("supplementary-material"):
            out.append("SUPPLEMENT: " + text_of(sm)[:300])
    return "\n".join(out) + "\n"

if __name__ == "__main__":
    for pmcid in sys.argv[1:]:
        try:
            fn = fetch(pmcid)
            (TXT / f"{pmcid}.txt").write_text(render(fn))
            t = (TXT / f"{pmcid}.txt").read_text()
            print(pmcid, "ok", len(t), "tables:", t.count("\nTABLE "), "img-only:", t.count("only as image"))
        except Exception as e:
            print(pmcid, "FAIL", e)