Datasets:
Download scripts/pmc.py from viktor-shcherb/mathconv-corpus: direct link, hf CLI and curl.
- Browser
- Download file 26 kB
-
https://huggingface.co/datasets/viktor-shcherb/mathconv-corpus/resolve/main/scripts/pmc.py
- Command line
-
hf download hf://datasets/viktor-shcherb/mathconv-corpus/scripts/pmc.py
-
curl -L -o pmc.py https://huggingface.co/datasets/viktor-shcherb/mathconv-corpus/resolve/main/scripts/pmc.py
26 kB
| #!/usr/bin/env python3 | |
| """Extract MathML formulas from the PubMed Central open-access bucket. | |
| Three stages, all resumable: | |
| ``select`` asks the Europe PMC REST search for candidate articles of | |
| a list of journals (by publisher group and publication | |
| period) whose abstracts mention mathematical vocabulary and | |
| whose licence field names CC BY, CC BY-SA or CC0. | |
| ``extract`` fetches each candidate from the anonymous ``pmc-oa-opendata`` | |
| S3 bucket (metadata JSON, then JATS XML), confirms the | |
| licence, finds the MathML formulas, samples at most 60 | |
| distinct formulas per article and appends them to a | |
| compressed store. Documents are streamed one at a time and | |
| never kept. | |
| ``build`` merges the store into ``pmc.jsonl`` (one row per distinct | |
| formula) and ``pmc.documents.jsonl`` (one line per article). | |
| Licence rule: an article is used only if the ``license_code`` of its | |
| metadata JSON and the Creative Commons URLs in the licence element of | |
| its JATS agree on one of CC BY, CC BY-SA or CC0, with a stated version. | |
| Service etiquette: about one request per second to each service, one | |
| connection at a time, generic client name, stop on HTTP 429 or 403. | |
| Usage: | |
| pmc.py select --work DIR [--per-bucket N] [--groups g1,g2] [--max-journals N] [--windows N] | |
| pmc.py extract --work DIR [--max-docs-per-group N] [--groups g1,g2] | |
| pmc.py build --work DIR --out DIR | |
| """ | |
| import argparse | |
| import hashlib | |
| import html | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import urllib.parse | |
| import scholarly_common as sc | |
| BUCKET = "https://pmc-oa-opendata.s3.amazonaws.com" | |
| EUROPE_PMC = "https://www.ebi.ac.uk/europepmc/webservices/rest/search" | |
| SEED = "mathconv-corpus-v1" | |
| CAP_PER_DOCUMENT = 60 | |
| # Target number of distinct formulas per publisher group. | |
| TARGETS = { | |
| "springer-nature": 25000, | |
| "elsevier": 20000, | |
| "mdpi": 15000, | |
| "wiley-hindawi": 15000, | |
| "oup-pnas-royal-society": 15000, | |
| "plos": 12000, | |
| "elife": 12000, | |
| "frontiers": 8000, | |
| "f1000research": 8000, | |
| "aims-press": 8000, | |
| "peerj": 8000, | |
| "other": 15000, | |
| } | |
| # Journals to query (Europe PMC journal names) for each group. | |
| JOURNALS = { | |
| "springer-nature": [ | |
| "Sci Rep", "Nat Commun", "BMC Bioinformatics", "Theor Biol Med Model", | |
| "Malar J", "Parasit Vectors", "BMC Public Health", "J Math Neurosci", | |
| "Commun Biol", "Commun Phys", "Light Sci Appl", "Genome Biol", | |
| "BMC Syst Biol", "BMC Med Res Methodol", "npj Syst Biol Appl", | |
| "J Cheminform", "BMC Biol", "Eur Phys J C", "Adv Differ Equ", | |
| ], | |
| "elsevier": [ | |
| "Heliyon", "Biophys J", "Cell Rep", "iScience", "Cell Rep Phys Sci", | |
| "Patterns (N Y)", "Comput Struct Biotechnol J", "Neuroimage", | |
| "J Biol Chem", "Epidemics", "Infect Dis Model", "Curr Res Struct Biol", | |
| "Biophys Rep (N Y)", "Neuron", "Cell Syst", "Ultrason Sonochem", | |
| "Math Biosci", "Neuroimage Clin", "Curr Res Neurobiol", "Mater Today Bio", | |
| "Data Brief", "MethodsX", "Genomics Proteomics Bioinformatics", "J Adv Res", | |
| "Redox Biol", "EBioMedicine", "Neurobiol Dis", "Biophys Rep", "STAR Protoc", | |
| "Cell Rep Methods", "Cell Rep Med", "Cell Genom", "Curr Biol", "Cell", | |
| "Mol Cell", "Dev Cell", "Structure", "Biochim Biophys Acta", "Nanomedicine", | |
| ], | |
| "mdpi": [ | |
| "Entropy (Basel)", "Sensors (Basel)", "Symmetry (Basel)", | |
| "Mathematics (Basel)", "Materials (Basel)", "Micromachines (Basel)", | |
| "Algorithms", "Appl Sci (Basel)", "Polymers (Basel)", "Int J Mol Sci", | |
| "Biosensors (Basel)", "Nanomaterials (Basel)", "Sensors", | |
| "Entropy", "Math", "Axioms", "Fractal Fract", | |
| ], | |
| "wiley-hindawi": [ | |
| "Comput Math Methods Med", "Comput Intell Neurosci", "J Healthc Eng", | |
| "Ecol Evol", "Stat Med", "Med Phys", "Biomed Res Int", "J Math", | |
| "J Appl Math", "Math Probl Eng", "Contrast Media Mol Imaging", | |
| "Brain Behav", "Cancer Med", "Evol Appl", "Methods Ecol Evol", | |
| "Wiley Interdiscip Rev Comput Mol Sci", "Bioeng Transl Med", | |
| "Comput Intell Neurosci", | |
| ], | |
| "oup-pnas-royal-society": [ | |
| "Gigascience", "Bioinformatics", "Nucleic Acids Res", "Mol Biol Evol", | |
| "Genetics", "G3 (Bethesda)", "Proc Natl Acad Sci U S A", | |
| "Proc Biol Sci", "J R Soc Interface", "Philos Trans A Math Phys Eng Sci", | |
| "Proc Math Phys Eng Sci", "R Soc Open Sci", "Interface Focus", | |
| "Biol Lett", "Open Biol", "Cereb Cortex", "Genome Biol Evol", | |
| "Bioinform Adv", "Plant Physiol", | |
| ], | |
| "plos": [ | |
| "PLoS One", "PLoS Comput Biol", "PLoS Genet", "PLoS Pathog", | |
| "PLoS Biol", "PLoS Negl Trop Dis", | |
| ], | |
| "elife": ["eLife"], | |
| "frontiers": [ | |
| "Front Neurosci", "Front Physiol", "Front Comput Neurosci", | |
| "Front Neuroinform", "Front Psychol", "Front Genet", "Front Phys", | |
| "Front Appl Math Stat", "Front Neurorobot", "Front Bioeng Biotechnol", | |
| "Front Neural Circuits", "Front Syst Neurosci", "Front Public Health", | |
| ], | |
| "f1000research": ["F1000Res"], | |
| "aims-press": ["Math Biosci Eng", "AIMS Public Health", "AIMS Neurosci", | |
| "AIMS Microbiol", "AIMS Biophys"], | |
| "peerj": ["PeerJ", "PeerJ Comput Sci", "PeerJ Phys Chem", "PeerJ Mater Sci"], | |
| "other": [ | |
| "Biomed Opt Express", "Opt Express", "ACS Omega", "ACS Cent Sci", | |
| "J Phys Chem Lett", "Epidemiol Infect", "Proc Nutr Soc", "Nanophotonics", | |
| "Open Phys", "J Integr Bioinform", "Int J Nanomedicine", "Sci Adv", | |
| "eNeuro", "mBio", "J Exp Biol", "Development", "Biol Open", | |
| "Nano Lett", "Phys Med Biol", "AIP Adv", "Chaos", "J Chem Phys", | |
| "IEEE Access", "Stat Appl Genet Mol Biol", "Biometrics", "J Appl Stat", | |
| "Life Sci Alliance", "Physiol Rep", "Genes Dev", "Genome Res", | |
| "JACS Au", "ACS Phys Chem Au", "ACS Nano", "Anal Chem", "J Chem Inf Model", | |
| "J Chem Theory Comput", "ACS Appl Mater Interfaces", "J Biol Dyn", | |
| "Stat Methods Med Res", "Quant Plant Biol", "Parasitology", "Epidemiol Infect", | |
| "Cambridge Prisms Glob Ment Health", "Philos Trans R Soc Lond B Biol Sci", | |
| "Nat Hum Behav", "Sci Data", "Commun Chem", "Commun Mater", "Commun Earth Environ", | |
| "Nat Commun", "Phys Rev Res", "Rev Mod Phys", | |
| "Micromachines", "Photonics", "Open Math", "Adv Sci (Weinh)", | |
| "Environ Res Lett", "Sensors and Actuators", "Atmos Chem Phys", | |
| ], | |
| } | |
| WINDOWS = [(2009, 2014), (2015, 2018), (2019, 2021), (2022, 2026)] | |
| MATH_TERMS = ('("differential equation" OR "mathematical model" OR "analytical solution" ' | |
| 'OR Hamiltonian OR "numerical simulation" OR theorem OR stochastic OR Bayesian ' | |
| 'OR optimization OR equations)') | |
| LICENCE_FILTER = '(LICENSE:"cc by" OR LICENSE:"cc0" OR LICENSE:"cc by-sa")' | |
| # metadata license_code -> class; Creative Commons URL path -> class | |
| CODE_CLASS = {"CC BY": "by", "CC BY-SA": "by-sa", "CC0": "zero"} | |
| SPDX = {"by": "CC-BY-{v}", "by-sa": "CC-BY-SA-{v}", "zero": "CC0-{v}"} | |
| CC_URL = re.compile(r"https?://creativecommons\.org/(licenses|publicdomain)/([\w-]+)/?([\d.]*)", re.I) | |
| PUBLISHER_GROUP = [ # (substring of the lower-case publisher name, producer, group) | |
| ("royal society of chemistry", "Royal Society of Chemistry", "other"), | |
| ("springer", "Springer Nature", "springer-nature"), | |
| ("nature", "Springer Nature", "springer-nature"), | |
| ("biomed central", "Springer Nature", "springer-nature"), | |
| ("bmc", "Springer Nature", "springer-nature"), | |
| ("elsevier", "Elsevier", "elsevier"), | |
| ("cell press", "Elsevier", "elsevier"), | |
| ("mdpi", "MDPI", "mdpi"), | |
| ("hindawi", "Hindawi", "wiley-hindawi"), | |
| ("wiley", "Wiley", "wiley-hindawi"), | |
| ("oxford university press", "Oxford University Press", "oup-pnas-royal-society"), | |
| ("national academy of sciences", "PNAS", "oup-pnas-royal-society"), | |
| ("royal society", "Royal Society", "oup-pnas-royal-society"), | |
| ("public library of science", "PLOS", "plos"), | |
| ("elife", "eLife", "elife"), | |
| ("frontiers", "Frontiers", "frontiers"), | |
| ("f1000", "F1000Research", "f1000research"), | |
| ("aims press", "AIMS Press", "aims-press"), | |
| ("public library", "PLOS", "plos"), | |
| ("plos", "PLOS", "plos"), | |
| ("faculty of 1000", "F1000Research", "f1000research"), | |
| ("american institute of mathematical sciences", "AIMS Press", "aims-press"), | |
| ("peerj", "PeerJ", "peerj"), | |
| ] | |
| # DOI prefix -> (producer, group); the prefix identifies the publisher | |
| # whose production pipeline wrote the markup, also for society journals. | |
| DOI_PREFIX = { | |
| "10.1016": ("Elsevier", "elsevier"), "10.3390": ("MDPI", "mdpi"), | |
| "10.1038": ("Springer Nature", "springer-nature"), | |
| "10.1186": ("Springer Nature", "springer-nature"), | |
| "10.1007": ("Springer Nature", "springer-nature"), | |
| "10.1155": ("Hindawi", "wiley-hindawi"), "10.1002": ("Wiley", "wiley-hindawi"), | |
| "10.1111": ("Wiley", "wiley-hindawi"), | |
| "10.1093": ("Oxford University Press", "oup-pnas-royal-society"), | |
| "10.1073": ("PNAS", "oup-pnas-royal-society"), | |
| "10.1098": ("Royal Society", "oup-pnas-royal-society"), | |
| "10.1371": ("PLOS", "plos"), "10.7554": ("eLife", "elife"), | |
| "10.3389": ("Frontiers", "frontiers"), "10.12688": ("F1000Research", "f1000research"), | |
| "10.3934": ("AIMS Press", "aims-press"), "10.7717": ("PeerJ", "peerj"), | |
| } | |
| def producer_and_group(publisher, doi=None): | |
| """Normalise to ``(producer, group)`` from the DOI prefix, else the publisher name.""" | |
| low = publisher.lower() | |
| if doi and doi.split("/")[0] in DOI_PREFIX: | |
| producer, group = DOI_PREFIX[doi.split("/")[0]] | |
| if "hindawi" in low: | |
| producer = "Hindawi" | |
| return producer, group | |
| for needle, producer, group in PUBLISHER_GROUP: | |
| if needle in low: | |
| return producer, group | |
| return publisher.strip() or "unknown", "other" | |
| # ---------------------------------------------------------------- select | |
| def bucket_size(group, docs_per_target=30, margin=2): | |
| """Candidates to request per (journal, period) bucket of a group. | |
| About ``target / 30`` articles are needed to reach a group's target at | |
| roughly 30 distinct formulas per article; twice as many are requested | |
| because some articles carry no MathML or fail the licence check. | |
| """ | |
| buckets = len(set(JOURNALS[group])) * len(WINDOWS) | |
| need = margin * TARGETS[group] / docs_per_target | |
| return int(min(400, max(40, need / buckets))) | |
| def select(args): | |
| """Query Europe PMC for candidate articles and append them to candidates.jsonl.""" | |
| os.makedirs(args.work, exist_ok=True) | |
| http = sc.HttpClient(1.0) | |
| done = sc.DoneList(os.path.join(args.work, "select.done")) | |
| name = "candidates." + (args.groups.replace(",", "+") if args.groups else "all") \ | |
| + (".any" if args.any_topic else "") + ".jsonl" | |
| out = open(os.path.join(args.work, name), "a", encoding="utf-8") | |
| only = set(args.groups.split(",")) if args.groups else None | |
| for group, journals in JOURNALS.items(): | |
| if only and group not in only: | |
| continue | |
| for journal in list(dict.fromkeys(journals))[: args.max_journals or None]: | |
| for lo, hi in WINDOWS[-args.windows:]: | |
| bucket = f"{group}|{journal}|{lo}-{hi}" + ("|any" if args.any_topic else "") | |
| if bucket in done: | |
| continue | |
| per_bucket = args.per_bucket or bucket_size(group) | |
| query = (f'JOURNAL:"{journal}" AND OPEN_ACCESS:y AND HAS_FT:y AND {LICENCE_FILTER} ' | |
| f'AND PUB_YEAR:[{lo} TO {hi}]' | |
| + ('' if args.any_topic else f' AND ABSTRACT:{MATH_TERMS}')) | |
| url = EUROPE_PMC + "?" + urllib.parse.urlencode({ | |
| "query": query, "format": "json", "resultType": "lite", | |
| "pageSize": per_bucket}) | |
| status, body, _ = http.get(url) | |
| if status != 200: | |
| sc.log("select failed", bucket, status) | |
| continue | |
| data = json.loads(body) | |
| for rank, r in enumerate(data["resultList"]["result"]): | |
| if not r.get("pmcid"): | |
| continue | |
| out.write(json.dumps({ | |
| "pmcid": r["pmcid"], "group": group, "bucket": bucket, "rank": rank, | |
| "journal": r.get("journalTitle"), "year": r.get("pubYear")}) + "\n") | |
| out.flush() | |
| done.add(bucket) | |
| sc.log("select", bucket, data["hitCount"], len(data["resultList"]["result"])) | |
| # --------------------------------------------------------------- extract | |
| def first(pattern, text, flags=re.S): | |
| m = re.search(pattern, text, flags) | |
| return m.group(1) if m else None | |
| def plain(s): | |
| """Text of an XML fragment with tags removed and entities decoded.""" | |
| return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", s or ""))).strip() | |
| def parse_front(xml): | |
| """Return bibliographic metadata and licence URLs from the article front matter.""" | |
| front = xml[: xml.find("</front>")] if "</front>" in xml else xml[:200000] | |
| journal_meta = first(r"<journal-meta>(.*?)</journal-meta>", front) or "" | |
| meta = first(r"<article-meta>(.*)", front) or front | |
| authors = [] | |
| for c in re.findall(r'<contrib\b[^>]*contrib-type="author"[^>]*>(.*?)</contrib>', meta, re.S): | |
| sn = first(r"<surname[^>]*>(.*?)</surname>", c) | |
| gn = first(r"<given-names[^>]*>(.*?)</given-names>", c) | |
| if sn: | |
| authors.append(plain((gn + " " if gn else "") + sn)) | |
| years = re.findall(r"<pub-date\b[^>]*>.*?<year>(\d{4})</year>", meta, re.S) | |
| perms = first(r"<permissions>(.*?)</permissions>", meta) or "" | |
| return { | |
| "title": plain(first(r"<article-title[^>]*>(.*?)</article-title>", meta)), | |
| "authors": "; ".join(authors), | |
| "journal": plain(first(r"<journal-title[^>]*>(.*?)</journal-title>", journal_meta)), | |
| "publisher": plain(first(r"<publisher-name[^>]*>(.*?)</publisher-name>", journal_meta)), | |
| "year": min(years) if years else None, | |
| "doi": plain(first(r'<article-id pub-id-type="doi">(.*?)</article-id>', meta)), | |
| "licence_urls": sorted({m.group(0).rstrip("/") + "/" for m in CC_URL.finditer(perms)}), | |
| } | |
| def licence_decision(code, urls): | |
| """Return ``(spdx, url, reason)``; ``spdx`` is None when the article must be skipped.""" | |
| cls = CODE_CLASS.get(code) | |
| if cls is None: | |
| return None, None, f"licence code {code!r}" | |
| parsed = set() | |
| for u in urls: | |
| m = CC_URL.match(u) | |
| kind = {"zero": "zero", "by": "by", "by-sa": "by-sa"}.get(m.group(2).lower(), "other:" + m.group(2)) | |
| parsed.add((kind, m.group(3).strip("."))) | |
| classes = {k for k, _ in parsed} | |
| # A CC0 dedication next to the article licence (Springer Nature adds one | |
| # for supplementary data) is more permissive and does not conflict. | |
| if classes - {"zero"} != {cls} - {"zero"} or (cls != "zero" and cls not in classes): | |
| return None, None, f"licence mismatch: code {code!r}, JATS {sorted(classes) or 'none'}" | |
| parsed = {(k, v) for k, v in parsed if k == cls} | |
| versions = sorted({v for _, v in parsed}) | |
| if len(versions) != 1 or not versions[0]: | |
| return None, None, "licence version missing or ambiguous" | |
| url = next(u for u in urls if CC_URL.match(u).group(2).lower() == cls and versions[0] in u) | |
| return SPDX[cls].format(v=versions[0]), url, None | |
| class Frame: | |
| __slots__ = ("kind", "tex", "maths") | |
| def __init__(self, kind): | |
| self.kind, self.tex, self.maths = kind, [], [] | |
| WRAPPER = re.compile(r"<(/?)(inline-formula|disp-formula|alternatives)(?=[\s>/])[^>]*?(/?)>") | |
| TEX_MATH = re.compile(r"<tex-math(?=[\s>])[^>]*>(.*?)</tex-math>", re.S) | |
| ANNOTATION_TEX = re.compile( | |
| r"<(?:\w+:)?annotation\b[^>]*encoding=[\"'][^\"']*tex[^\"']*[\"'][^>]*>(.*?)</(?:\w+:)?annotation\s*>", | |
| re.S | re.I) | |
| def clean_tex(raw): | |
| raw = raw.strip() | |
| m = re.fullmatch(r"<!\[CDATA\[(.*)\]\]>", raw, re.S) | |
| raw = m.group(1) if m else html.unescape(raw) | |
| return sc.tidy_tex(raw) | |
| def extract_formulas(xml): | |
| """Return ``(found, formulas)`` for a JATS document. | |
| ``found`` is the number of math elements; ``formulas`` maps each | |
| distinct MathML string to a record with its occurrence count, context | |
| (from the enclosing inline or display formula, else the ``display`` | |
| attribute) and the TeX of a sibling ``tex-math`` inside the same | |
| ``alternatives`` element. | |
| """ | |
| spans = sc.find_math_spans(xml) | |
| events = [] # (position, order, kind, payload) | |
| for m in WRAPPER.finditer(xml): | |
| if m.group(3) == "/": | |
| continue | |
| events.append((m.start(), 0, "close" if m.group(1) else "open", m.group(2))) | |
| for m in TEX_MATH.finditer(xml): | |
| events.append((m.start(), 1, "tex", m.group(1))) | |
| for i, (a, b) in enumerate(spans): | |
| events.append((a, 2, "math", i)) | |
| events.sort(key=lambda e: e[:2]) | |
| stack, math_info = [], {} | |
| for _, _, kind, payload in events: | |
| if kind == "open": | |
| stack.append(Frame(payload)) | |
| elif kind == "close": | |
| while stack and stack[-1].kind != payload: | |
| stack.pop() | |
| if not stack: | |
| continue | |
| f = stack.pop() | |
| if f.kind == "alternatives" and f.tex and len(f.tex) == len(f.maths): | |
| for i, t in zip(f.maths, f.tex): | |
| math_info[i]["tex"] = t | |
| elif kind == "tex": | |
| for f in reversed(stack): | |
| if f.kind == "alternatives": | |
| f.tex.append(payload) | |
| break | |
| else: | |
| ctx = None | |
| for f in reversed(stack): | |
| if f.kind in ("inline-formula", "disp-formula"): | |
| ctx = "inline" if f.kind == "inline-formula" else "display" | |
| break | |
| math_info[payload] = {"ctx": ctx, "tex": None} | |
| for f in reversed(stack): | |
| if f.kind == "alternatives": | |
| f.maths.append(payload) | |
| break | |
| formulas = {} | |
| for i, (a, b) in enumerate(spans): | |
| s = xml[a:b] | |
| info = math_info.get(i, {"ctx": None, "tex": None}) | |
| tex, kind = (clean_tex(info["tex"]) if info["tex"] else None), None | |
| if tex: | |
| kind = "author" | |
| else: | |
| m = ANNOTATION_TEX.search(s) | |
| if m: | |
| tex = clean_tex(m.group(1)) | |
| kind = "author" if tex else None | |
| rec = formulas.get(s) | |
| if rec is None: | |
| formulas[s] = {"n": 1, "context": info["ctx"] or sc.context_from_display(s), | |
| "tex": tex, "tex_kind": kind, "markup": sc.classify_markup(s)} | |
| else: | |
| rec["n"] += 1 | |
| if rec["tex"] is None and tex: | |
| rec["tex"], rec["tex_kind"] = tex, kind | |
| return len(spans), formulas | |
| def candidate_order(work, only): | |
| """Per-group candidate lists, interleaved across (journal, period) buckets. | |
| Reads every ``candidates*.jsonl`` file of the work directory (one per | |
| ``select`` run). | |
| """ | |
| queues, seen, rows = {}, set(), [] | |
| for name in sorted(os.listdir(work)): | |
| if name.startswith("candidates") and name.endswith(".jsonl"): | |
| with open(os.path.join(work, name), encoding="utf-8") as f: | |
| rows.extend(json.loads(line) for line in f) | |
| rows.sort(key=lambda r: (r["rank"], hashlib.sha256((SEED + r["bucket"]).encode()).hexdigest())) | |
| for r in rows: | |
| if r["pmcid"] in seen or (only and r["group"] not in only): | |
| continue | |
| seen.add(r["pmcid"]) | |
| queues.setdefault(r["group"], []).append(r) | |
| return queues | |
| def extract(args): | |
| """Fetch candidates until every group reaches its target or runs out.""" | |
| http = sc.HttpClient(1.0) | |
| done = sc.DoneList(os.path.join(args.work, "extract.done")) | |
| store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz")) | |
| log_path = open(os.path.join(args.work, "decisions.tsv"), "a", encoding="utf-8") | |
| only = set(args.groups.split(",")) if args.groups else None | |
| queues = candidate_order(args.work, only) | |
| distinct = {g: set() for g in TARGETS} | |
| for rec in store: | |
| g = rec["doc"]["group"] | |
| distinct[g].update(sc.formula_id(f["mathml"]) for f in rec["formulas"]) | |
| attempts = {g: 0 for g in TARGETS} | |
| cursor = {g: 0 for g in queues} | |
| try: | |
| while True: | |
| open_groups = [g for g in queues | |
| if len(distinct[g]) < TARGETS[g] and cursor[g] < len(queues[g]) | |
| and (not args.max_docs_per_group or attempts[g] < args.max_docs_per_group)] | |
| if not open_groups: | |
| break | |
| group = max(open_groups, key=lambda g: TARGETS[g] - len(distinct[g])) | |
| cand = queues[group][cursor[group]] | |
| cursor[group] += 1 | |
| if cand["pmcid"] in done: | |
| continue | |
| attempts[group] += 1 | |
| outcome = process(http, cand, store, distinct) | |
| log_path.write(f"{cand['pmcid']}\t{cand['group']}\t{outcome}\n") | |
| log_path.flush() | |
| done.add(cand["pmcid"]) | |
| if len(done.keys) % 25 == 0: | |
| sc.log("done", len(done.keys), {g: len(v) for g, v in distinct.items() if v}) | |
| except sc.StopRequested as e: | |
| sc.log("stopped:", e) | |
| return 3 | |
| sc.log("finished", {g: len(v) for g, v in distinct.items() if v}) | |
| return 0 | |
| def find_version(http, pmcid): | |
| """Return the highest version of an article in the bucket, or None.""" | |
| status, body, _ = http.get(f"{BUCKET}/?list-type=2&delimiter=/&prefix={pmcid}.") | |
| versions = re.findall(rf"<Prefix>{pmcid}\.(\d+)/</Prefix>", body.decode("utf-8", "replace")) | |
| return max(map(int, versions)) if versions else None | |
| def process(http, cand, store, distinct): | |
| """Fetch, check and store one article. Returns a short outcome string.""" | |
| pmcid = cand["pmcid"] | |
| ver = 1 | |
| status, body, _ = http.get(f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.json") | |
| if status == 404: | |
| ver = find_version(http, pmcid) | |
| if ver is None: | |
| return "skip: not in bucket" | |
| status, body, _ = http.get(f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.json") | |
| if status != 200: | |
| return f"skip: metadata status {status}" | |
| meta = json.loads(body) | |
| if meta.get("license_code") not in CODE_CLASS: | |
| return f"skip: licence code {meta.get('license_code')!r}" | |
| if meta.get("is_manuscript") or meta.get("is_retracted") or meta.get("is_historical_ocr"): | |
| return "skip: manuscript, retracted or scanned" | |
| xml_url = f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.xml" | |
| status, body, _ = http.get(xml_url) | |
| if status != 200: | |
| return f"skip: xml status {status}" | |
| xml = body.decode("utf-8", "replace") | |
| front = parse_front(xml) | |
| spdx, lic_url, reason = licence_decision(meta["license_code"], front["licence_urls"]) | |
| if spdx is None: | |
| return "skip: " + reason | |
| found, formulas = extract_formulas(xml) | |
| if not formulas: | |
| return "skip: no MathML" | |
| doi = front["doi"] or meta.get("doi") | |
| producer, group = producer_and_group(front["publisher"], doi) | |
| if len(distinct[group]) >= TARGETS[group]: | |
| return f"skip: group {group} complete" | |
| origin = f"https://doi.org/{doi}" if doi else f"https://pmc.ncbi.nlm.nih.gov/articles/{pmcid}/" | |
| chosen = sc.sample_formulas(formulas, CAP_PER_DOCUMENT, SEED, pmcid) | |
| doc = { | |
| "origin": origin, "pmcid": pmcid, "pmc_version": ver, "title": front["title"], | |
| "authors": front["authors"], "journal": front["journal"], "year": front["year"], | |
| "publisher": front["publisher"], "producer": producer, "group": group, | |
| "licence": spdx, "licence_url": lic_url, "license_code": meta["license_code"], | |
| "access_url": xml_url, "retrieved": sc.today(), | |
| "formulas_found": found, "formulas_distinct": len(formulas), | |
| } | |
| out = [dict(mathml=s, **{k: v for k, v in rec.items()}) for s, rec in chosen] | |
| store.append({"doc": doc, "formulas": out}) | |
| distinct[group].update(sc.formula_id(s) for s, _ in chosen) | |
| return f"kept {len(chosen)}/{len(formulas)} {group}" | |
| # ----------------------------------------------------------------- build | |
| def build(args): | |
| """Merge the store into ``pmc.jsonl`` and ``pmc.documents.jsonl``.""" | |
| store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz")) | |
| print(json.dumps(sc.build_outputs(store, "pmc", args.out), indent=1)) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = p.add_subparsers(dest="cmd", required=True) | |
| s = sub.add_parser("select") | |
| s.add_argument("--work", required=True) | |
| s.add_argument("--per-bucket", type=int, default=0, help="candidates per bucket (0: sized from the group target)") | |
| s.add_argument("--groups", default="", help="comma-separated group names (default: all)") | |
| s.add_argument("--any-topic", action="store_true", | |
| help="do not require mathematical vocabulary in the abstract") | |
| s.add_argument("--max-journals", type=int, default=0, help="first N journals per group (0: all)") | |
| s.add_argument("--windows", type=int, default=len(WINDOWS), help="use the latest N periods") | |
| e = sub.add_parser("extract") | |
| e.add_argument("--work", required=True) | |
| e.add_argument("--max-docs-per-group", type=int, default=0) | |
| e.add_argument("--groups", default="") | |
| b = sub.add_parser("build") | |
| b.add_argument("--work", required=True) | |
| b.add_argument("--out", required=True) | |
| args = p.parse_args() | |
| return {"select": select, "extract": extract, "build": build}[args.cmd](args) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |