Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,10 +374,36 @@ reference:
- `PMID:12345678`
- `12345678` (assumes PMID)

### Coming Soon
#### Preprints

- **DOI** - `DOI:10.1038/nature12345`
- **URLs** - Web pages and online documents
Preprints are supported as first-class references:

```yaml
reference:
id: DOI:10.1101/2024.01.01.573333 # by DOI
supporting_text: "the kinase phosphorylates the substrate in vitro"
```

```yaml
reference:
id: PPR:PPR123456 # by Europe PMC preprint id
supporting_text: "the kinase phosphorylates the substrate in vitro"
```

**Fetches:**
- Abstract and metadata (title, authors, server, year, DOI)
- Full-text body via the Europe PMC `fulltextRepo` PDF route (`epmc_preprint`
provider), for the Europe-PMC-ingested subset
- `is_preprint` / `peer_review_status` flags, so downstream KBs can apply
"not sole support" policies

**ID Formats:**
- `DOI:10.1101/...` (Crossref `posted-content` is detected as a preprint)
- `PPR:PPR123456` (Europe PMC `SRC:PPR` id)
- NIH Preprint Pilot preprints carry real PMIDs and resolve via the `PMID:` path

See the [full-text guide](docs/how-to/fetch-full-text-and-pdfs.md#preprints) for
details and coverage caveats.

---

Expand Down
52 changes: 49 additions & 3 deletions docs/how-to/fetch-full-text-and-pdfs.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ The validator tries providers in order until one returns usable full text.
The default order is:

```
pmc → unpaywall → openalex
pmc → epmc_preprint → unpaywall → openalex
```

- **`pmc`** — PubMed Central open-access subset (XML/HTML full text for many
biomedical articles).
- **`epmc_preprint`** — Europe PMC preprint body text via the `fulltextRepo`
PDF route (see [Preprints](#preprints) below).
- **`unpaywall`** — Unpaywall open-access lookup by DOI (often a publisher or
repository PDF).
- **`openalex`** — OpenAlex open-access location (PDF/HTML).
Expand All @@ -43,7 +45,7 @@ your config YAML or on the `ReferenceValidationConfig` object):
| Key | Default | Description |
|-----|---------|-------------|
| `fetch_full_text` | `true` | Attempt to obtain full text via the provider chain when a metadata source does not already return full text. |
| `full_text_providers` | `[pmc, unpaywall, openalex]` | Ordered list of provider names to try until one yields usable full text. |
| `full_text_providers` | `[pmc, epmc_preprint, unpaywall, openalex]` | Ordered list of provider names to try until one yields usable full text. |
| `pdf_backend` | `pypdf` | Name of the PDF text-extraction backend. |
| `download_pdfs` | `true` | If true, persist downloaded PDFs to the files cache directory. |
| `full_text_providers_file` | `null` | Optional path to a YAML file defining custom full-text providers. |
Expand All @@ -62,12 +64,56 @@ email: you@example.org
fetch_full_text: true
full_text_providers:
- pmc
- epmc_preprint
- unpaywall
- openalex
pdf_backend: pypdf
download_pdfs: true
```

## Preprints

Preprints are first-class references. They are increasingly cited for early
mechanistic findings, but they sit in two distinct universes that need
different handling:

- **NIH Preprint Pilot** — a subset of preprints carry real PMIDs, so they
resolve through the normal `PMID:` path with no special handling.
- **Europe PMC `SRC:PPR`** — the much larger preprint firehose is DOI-only
(no PMIDs). These resolve by DOI through Crossref, or directly by their
Europe PMC preprint id using the `PPR:` prefix (e.g. `PPR:PPR123456`).

### Full-text retrieval

Preprint bodies are **not** served by the PMC `fullTextXML` endpoint — even the
~7% with a PMCID expose only abstract/title/supplementary in PMC, and direct
`biorxiv.org/...full.pdf` links sit behind a bot challenge. The route that
works for automated clients is the Europe PMC `fulltextRepo` PDF, used by the
`epmc_preprint` provider: it resolves a preprint by DOI (or `SRC:PPR` id),
finds the open `fulltextRepo` PDF URL, and downloads it. The PDF's `%PDF-`
magic bytes are validated before extraction, so a stale-filename error blob is
rejected rather than fed to the PDF parser, and the chain falls through
gracefully.

Coverage note: the `epmc_preprint` route covers the Europe-PMC-ingested
preprint subset. The newest openRxiv DOIs (prefix `10.64898`) are not yet in
Europe PMC, so very recent preprints may resolve to metadata only until they
are ingested.

### Preprint / peer-review status

When a reference is detected as a preprint — via the Crossref `posted-content`
type or a Europe PMC `SRC:PPR` record — the cached reference records it:

| Field | Description |
|-------|-------------|
| `is_preprint` | `true` for a preprint, `false` when the source authoritatively classifies it as not a preprint (e.g. a Crossref `journal-article`), and unset when the type is unknown. |
| `peer_review_status` | `preprint` for preprints; left unset otherwise. |

Downstream knowledge bases can use these fields to apply policies such as "a
preprint may not be the sole support for a claim". A non-preprint is not
positively asserted as `peer_reviewed`; `peer_review_status` stays unset.

## CLI flag

Every `validate` subcommand accepts a `--full-text/--no-full-text` flag that
Expand Down Expand Up @@ -122,7 +168,7 @@ the text came from. These provenance fields are written alongside the content:

| Field | Description |
|-------|-------------|
| `full_text_provider` | Name of the provider that supplied the full text (e.g. `pmc`, `unpaywall`, or a custom name). |
| `full_text_provider` | Name of the provider that supplied the full text (e.g. `pmc`, `epmc_preprint`, `unpaywall`, or a custom name). |
| `oa_status` | Open-access status reported by the provider (e.g. `gold`, `green`, `bronze`). |
| `license` | License of the open-access copy, when known. |
| `local_pdf_path` | Path (relative to the cache directory) to the downloaded PDF, when one was persisted. |
Expand Down
2 changes: 2 additions & 0 deletions src/linkml_reference_validator/etl/fulltext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@

# Import providers to register them
from linkml_reference_validator.etl.fulltext.pmc import PMCFullTextProvider
from linkml_reference_validator.etl.fulltext.epmc_preprint import EuropePMCPreprintProvider
from linkml_reference_validator.etl.fulltext.unpaywall import UnpaywallProvider
from linkml_reference_validator.etl.fulltext.openalex import OpenAlexProvider

__all__ = [
"FullTextProvider",
"FullTextProviderRegistry",
"PMCFullTextProvider",
"EuropePMCPreprintProvider",
"UnpaywallProvider",
"OpenAlexProvider",
]
142 changes: 142 additions & 0 deletions src/linkml_reference_validator/etl/fulltext/epmc_preprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""Europe PMC preprint full-text provider.

Preprints (Europe PMC ``SRC:PPR`` records) are not served by the PMC
``fullTextXML`` endpoint and their bodies are absent from PMC even when a PMCID
exists. The one route that reliably serves a preprint body is the Europe PMC
``fulltextRepo`` PDF: every ``SRC:PPR AND HAS_FT:Y`` core record carries a direct
``/fulltextRepo?pprId=...`` PDF URL in its ``fullTextUrlList``.

This provider resolves that URL from a DOI (or a ``SRC:PPR`` id) and returns it as
a ``FullTextLocation``. The downstream acquire/extract machinery validates the
``%PDF-`` magic bytes (a minority of records return a stale-filename error blob),
so an HTML/error response is rejected rather than fed to the PDF parser.
"""

import logging
import time
from typing import Optional

import requests # type: ignore

from linkml_reference_validator.models import (
FullTextLocation,
ReferenceIdentifiers,
ReferenceValidationConfig,
)
from linkml_reference_validator.etl.fulltext.base import (
FullTextProvider,
FullTextProviderRegistry,
)

logger = logging.getLogger(__name__)

_EPMC_SEARCH_URL = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"


@FullTextProviderRegistry.register
class EuropePMCPreprintProvider(FullTextProvider):
"""Locate preprint full text via the Europe PMC fulltextRepo PDF route.

Examples:
>>> EuropePMCPreprintProvider.name()
'epmc_preprint'
"""

@classmethod
def name(cls) -> str:
return "epmc_preprint"

def locate(
self, ids: ReferenceIdentifiers, config: ReferenceValidationConfig
) -> Optional[FullTextLocation]:
# Skip the Europe PMC round-trip for records the metadata source already
# confirmed are peer-reviewed (is_preprint False). A None ("unknown", e.g.
# a PMID or DataCite record) is still attempted.
if ids.is_preprint is False:
return None

query = self._build_query(ids)
if query is None:
return None

time.sleep(config.rate_limit_delay)
params = {
"query": query,
"format": "json",
"resultType": "core",
"pageSize": "1",
"email": config.email,
}
response = requests.get(_EPMC_SEARCH_URL, params=params, timeout=30)
if response.status_code != 200:
logger.debug(f"Europe PMC search returned {response.status_code} for {query}")
return None

result = self._first_ppr_result(response.json())
if result is None:
return None

pdf_url = self._extract_pdf_url(result)
if not pdf_url:
return None

return FullTextLocation(
url=pdf_url,
format_hint="pdf",
oa_status="green",
license=result.get("license"),
version="preprint",
provider="epmc_preprint",
)

def _build_query(self, ids: ReferenceIdentifiers) -> Optional[str]:
"""Build a Europe PMC query restricted to the preprint source.

Examples:
>>> p = EuropePMCPreprintProvider()
>>> p._build_query(ReferenceIdentifiers(doi="10.1101/x"))
'DOI:"10.1101/x" AND SRC:PPR'
>>> p._build_query(ReferenceIdentifiers(pprid="PPR42"))
'EXT_ID:PPR42 AND SRC:PPR'
>>> p._build_query(ReferenceIdentifiers(pmid="123")) is None
True
"""
if ids.doi:
return f'DOI:"{ids.doi}" AND SRC:PPR'
if ids.pprid:
return f"EXT_ID:{ids.pprid} AND SRC:PPR"
return None

def _first_ppr_result(self, data: dict) -> Optional[dict]:
"""Return the first ``SRC:PPR`` result, or None.

Restricting to ``source == "PPR"`` guards against a peer-reviewed record
sharing the DOI namespace being mistaken for a preprint.
"""
results = data.get("resultList", {}).get("result", [])
for result in results:
if isinstance(result, dict) and result.get("source") == "PPR":
return result
return None

def _extract_pdf_url(self, result: dict) -> Optional[str]:
"""Find the fulltextRepo PDF URL for a preprint core record.

Returns the ``documentStyle == "pdf"`` entry from ``fullTextUrlList`` (the
Europe PMC ``fulltextRepo`` PDF). The full URL must be taken verbatim from
the record: the working endpoint includes a per-record ``fileName`` query
parameter that cannot be reconstructed from the preprint id alone (a
``fileName``-less request 500s), so a record without a usable PDF entry
yields no location rather than a guessed URL.
"""
full_text_urls = result.get("fullTextUrlList", {}).get("fullTextUrl", [])
for entry in full_text_urls:
if not isinstance(entry, dict):
continue
url = entry.get("url")
if not url:
continue
if entry.get("documentStyle") == "pdf" or "fulltextRepo" in url:
return url

return None
6 changes: 5 additions & 1 deletion src/linkml_reference_validator/etl/identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,21 @@ def build_identifiers(content: ReferenceContent) -> ReferenceIdentifiers:
>>> ids = build_identifiers(ReferenceContent(reference_id="PMID:9", doi="10.1/z"))
>>> ids.pmid, ids.doi
('9', '10.1/z')
>>> build_identifiers(ReferenceContent(reference_id="PPR:PPR42")).pprid
'PPR42'
"""
prefix, identifier = _split_reference_id(content.reference_id)

ids = ReferenceIdentifiers(doi=content.doi or None)
ids = ReferenceIdentifiers(doi=content.doi or None, is_preprint=content.is_preprint)

if prefix and identifier:
upper = prefix.upper()
if upper == "PMID":
ids.pmid = identifier
elif upper == "PMCID":
ids.pmcid = identifier
elif upper == "PPR":
ids.pprid = identifier
elif upper == "DOI" and not ids.doi:
ids.doi = identifier
elif prefix.lower() == "url":
Expand Down
8 changes: 8 additions & 0 deletions src/linkml_reference_validator/etl/reference_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,12 @@ def _save_to_disk(self, reference: ReferenceContent) -> None:
for keyword in reference.keywords:
lines.append(f"- {self._quote_yaml_value(keyword)}")
lines.append(f"content_type: {reference.content_type}")
if reference.is_preprint is not None:
lines.append(f"is_preprint: {str(reference.is_preprint).lower()}")
if reference.peer_review_status:
lines.append(
f"peer_review_status: {self._quote_yaml_value(reference.peer_review_status)}"
)
if reference.full_text_attempted:
lines.append("full_text_attempted: true")
if reference.full_text_provider:
Expand Down Expand Up @@ -651,6 +657,8 @@ def _load_markdown_format(
oa_status=frontmatter.get("oa_status"),
license=frontmatter.get("license"),
local_pdf_path=frontmatter.get("local_pdf_path"),
is_preprint=frontmatter.get("is_preprint"),
peer_review_status=frontmatter.get("peer_review_status"),
full_text_attempted=bool(frontmatter.get("full_text_attempted", False)),
)

Expand Down
2 changes: 2 additions & 0 deletions src/linkml_reference_validator/etl/sources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
# Import sources to register them
from linkml_reference_validator.etl.sources.pmid import PMIDSource
from linkml_reference_validator.etl.sources.doi import DOISource
from linkml_reference_validator.etl.sources.ppr import PPRSource
from linkml_reference_validator.etl.sources.file import FileSource
from linkml_reference_validator.etl.sources.url import URLSource
from linkml_reference_validator.etl.sources.entrez import (
Expand All @@ -50,6 +51,7 @@
"ReferenceSourceRegistry",
"PMIDSource",
"DOISource",
"PPRSource",
"FileSource",
"URLSource",
"GEOSource",
Expand Down
34 changes: 34 additions & 0 deletions src/linkml_reference_validator/etl/sources/doi.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ def _fetch_from_crossref(
abstract = (abstract + "\n\n" + format_extra_fields_for_content(extra)) if abstract else format_extra_fields_for_content(extra)
metadata["extra_fields_captured"] = list(extra.keys())

is_preprint = self._crossref_preprint_status(message)

return ReferenceContent(
reference_id=f"DOI:{doi}",
title=title,
Expand All @@ -151,8 +153,40 @@ def _fetch_from_crossref(
doi=doi,
keywords=keywords,
metadata=metadata,
is_preprint=is_preprint,
peer_review_status="preprint" if is_preprint else None,
)

def _crossref_preprint_status(self, message: dict) -> Optional[bool]:
"""Classify a Crossref work as preprint / not-preprint / unknown.

Crossref models preprints as ``type: "posted-content"`` (usually with
``subtype: "preprint"``). The ``type`` is authoritative, so a known
non-preprint type returns ``False`` (recorded so a preprint-specific
full-text provider can skip the record without a wasted lookup). Only an
entirely typeless record is left ``None`` ("unknown"). A DOI-prefix
heuristic is deliberately not used because, e.g., the ``10.1101`` prefix
also covers peer-reviewed Cold Spring Harbor journals.

Examples:
>>> source = DOISource()
>>> source._crossref_preprint_status({"type": "posted-content", "subtype": "preprint"})
True
>>> source._crossref_preprint_status({"type": "posted-content"})
True
>>> source._crossref_preprint_status({"type": "journal-article"})
False
>>> source._crossref_preprint_status({}) is None
True
"""
if message.get("type") == "posted-content":
return True
if str(message.get("subtype", "")).lower() == "preprint":
return True
if message.get("type"):
return False
return None

def _fetch_from_datacite(
self, doi: str, config: ReferenceValidationConfig
) -> Optional[ReferenceContent]:
Expand Down
Loading