feat(prisma): parsers for Europe PMC, OpenAlex, Crossref, Semantic Scholar, arXiv

This commit is contained in:
kert
2026-10-31 20:31:21 -04:00
parent 43d8e51886
commit aa1d31db24
7 changed files with 359 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
"""arXiv Atom XML. The caller supplies the file."""
from __future__ import annotations
import xml.etree.ElementTree as ET
from prisma.search.base import (
SearchHit,
SearchResult,
bare_doi,
finish,
surname,
year_of,
)
_ATOM = "http://www.w3.org/2005/Atom"
_ARXIV = "http://arxiv.org/schemas/atom"
def _child(node: ET.Element, tag: str, ns: str = _ATOM) -> ET.Element | None:
found = node.find(f"{{{ns}}}{tag}")
return node.find(tag) if found is None else found
def _text(node: ET.Element | None) -> str:
if node is None:
return ""
return "".join(node.itertext()).strip()
def parse_arxiv(payload: str, *, query: str, searched_on: str) -> SearchResult:
"""Read one arXiv Atom feed. A blank payload has no hits."""
if not payload.strip():
return finish("arxiv", [], payload, query=query, searched_on=searched_on)
root = ET.fromstring(payload)
entries = list(root.iter(f"{{{_ATOM}}}entry")) or list(root.iter("entry"))
hits: list[SearchHit] = []
for entry in entries:
author = _child(entry, "author")
name = _text(_child(author, "name")) if author is not None else ""
doi = _text(_child(entry, "doi", _ARXIV)) or _text(_child(entry, "doi"))
hits.append(
SearchHit(
title=_text(_child(entry, "title")),
year=year_of(_text(_child(entry, "published"))),
doi=bare_doi(doi),
pmid="",
first_author=surname(name),
database="arxiv",
)
)
return finish("arxiv", hits, payload, query=query, searched_on=searched_on)

View File

@@ -42,6 +42,54 @@ class SearchResult:
log: SearchLog
def finish(
database: str,
hits: list[SearchHit],
payload: str,
*,
query: str,
searched_on: str,
) -> SearchResult:
"""Wrap hits in a log row. ``hit_count`` is the number of hits."""
found = tuple(hits)
return SearchResult(
hits=found,
log=SearchLog(
database=database,
interface=database,
searched_on=searched_on,
query=query,
filters="",
hit_count=len(found),
export_sha256=hashlib.sha256(payload.encode()).hexdigest(),
),
)
def surname(name: str) -> str:
"""Last token of a display name. One token is returned as-is."""
parts = name.split()
return parts[-1] if parts else ""
def bare_doi(value: str) -> str:
"""Drop a ``doi.org`` or ``doi:`` prefix."""
text = value.strip()
lowered = text.casefold()
for prefix in ("https://doi.org/", "http://doi.org/", "doi:"):
if lowered.startswith(prefix):
return text[len(prefix) :]
return text
def year_of(value: object) -> int | None:
"""First four digits of a year, or None when the field is blank."""
if value is None:
return None
head = str(value).strip()[:4]
return int(head) if head.isdigit() and len(head) == 4 else None
def seed_recall(retrieved: set[str], seeds: set[str]) -> float:
"""Share of the seed set present in the retrieved set.

View File

@@ -0,0 +1,43 @@
"""Crossref works JSON. The caller supplies the file."""
from __future__ import annotations
import json
from prisma.search.base import SearchHit, SearchResult, bare_doi, finish, year_of
def _title(row: dict) -> str:
title = row.get("title") or ""
if isinstance(title, list):
return str(title[0]) if title else ""
return str(title)
def _year(row: dict) -> int | None:
parts = (row.get("issued") or {}).get("date-parts") or []
if not parts or not parts[0]:
return None
return year_of(parts[0][0])
def parse_crossref(payload: str, *, query: str, searched_on: str) -> SearchResult:
"""Read one Crossref message. A blank payload has no hits."""
rows = []
if payload.strip():
rows = ((json.loads(payload).get("message") or {}).get("items")) or []
hits: list[SearchHit] = []
for row in rows:
authors = row.get("author") or []
family = (authors[0].get("family") or "") if authors else ""
hits.append(
SearchHit(
title=_title(row),
year=_year(row),
doi=bare_doi(row.get("DOI") or ""),
pmid="",
first_author=family,
database="crossref",
)
)
return finish("crossref", hits, payload, query=query, searched_on=searched_on)

View File

@@ -0,0 +1,33 @@
"""Europe PMC REST XML. The caller supplies the file."""
from __future__ import annotations
import xml.etree.ElementTree as ET
from prisma.search.base import SearchHit, SearchResult, bare_doi, finish, year_of
def _text(node: ET.Element | None) -> str:
if node is None:
return ""
return "".join(node.itertext()).strip()
def parse_europepmc(payload: str, *, query: str, searched_on: str) -> SearchResult:
"""Read one Europe PMC result list. A blank payload has no hits."""
if not payload.strip():
return finish("europepmc", [], payload, query=query, searched_on=searched_on)
root = ET.fromstring(payload)
hits: list[SearchHit] = []
for result in root.iter("result"):
hits.append(
SearchHit(
title=_text(result.find("title")),
year=year_of(_text(result.find("pubYear"))),
doi=bare_doi(_text(result.find("doi"))),
pmid=_text(result.find("pmid")),
first_author=_text(result.find("./authorList/author/lastName")),
database="europepmc",
)
)
return finish("europepmc", hits, payload, query=query, searched_on=searched_on)

View File

@@ -0,0 +1,36 @@
"""OpenAlex works JSON. The caller supplies the file."""
from __future__ import annotations
import json
from prisma.search.base import (
SearchHit,
SearchResult,
bare_doi,
finish,
surname,
year_of,
)
def parse_openalex(payload: str, *, query: str, searched_on: str) -> SearchResult:
"""Read one OpenAlex works page. A blank payload has no hits."""
rows = [] if not payload.strip() else (json.loads(payload).get("results") or [])
hits: list[SearchHit] = []
for row in rows:
authorships = row.get("authorships") or []
name = ""
if authorships:
name = ((authorships[0].get("author") or {}).get("display_name")) or ""
hits.append(
SearchHit(
title=row.get("title") or "",
year=year_of(row.get("publication_year")),
doi=bare_doi(row.get("doi") or ""),
pmid="",
first_author=surname(name),
database="openalex",
)
)
return finish("openalex", hits, payload, query=query, searched_on=searched_on)

View File

@@ -0,0 +1,39 @@
"""Semantic Scholar paper-search JSON. The caller supplies the file."""
from __future__ import annotations
import json
from prisma.search.base import (
SearchHit,
SearchResult,
bare_doi,
finish,
surname,
year_of,
)
def parse_semanticscholar(
payload: str, *, query: str, searched_on: str
) -> SearchResult:
"""Read one Semantic Scholar data page. A blank payload has no hits."""
rows = [] if not payload.strip() else (json.loads(payload).get("data") or [])
hits: list[SearchHit] = []
for row in rows:
authors = row.get("authors") or []
name = (authors[0].get("name") or "") if authors else ""
doi = ((row.get("externalIds") or {}).get("DOI")) or ""
hits.append(
SearchHit(
title=row.get("title") or "",
year=year_of(row.get("year")),
doi=bare_doi(doi),
pmid="",
first_author=surname(name),
database="semanticscholar",
)
)
return finish(
"semanticscholar", hits, payload, query=query, searched_on=searched_on
)

View File

@@ -0,0 +1,108 @@
"""Parsers for Europe PMC, OpenAlex, Crossref, Semantic Scholar, and arXiv."""
from __future__ import annotations
import pytest
from prisma.search.arxiv import parse_arxiv
from prisma.search.crossref import parse_crossref
from prisma.search.europepmc import parse_europepmc
from prisma.search.openalex import parse_openalex
from prisma.search.semanticscholar import parse_semanticscholar
_EUROPEPMC = """\
<response><resultList><result>
<title>Report title</title>
<doi>10.1/e</doi>
<pubYear>2020</pubYear>
<authorList><author><lastName>Kim</lastName></author></authorList>
</result></resultList></response>
"""
_OPENALEX = """\
{"results":[{"title":"Report title","publication_year":2020,
"doi":"https://doi.org/10.1/o",
"authorships":[{"author":{"display_name":"Ada Kim"}}]}]}
"""
_CROSSREF = """\
{"message":{"items":[{"title":["Report title"],"DOI":"10.1/c",
"issued":{"date-parts":[[2020,1,2]]},
"author":[{"family":"Kim","given":"Ada"}]}]}}
"""
_S2 = """\
{"data":[{"title":"Report title","year":2020,
"externalIds":{"DOI":"10.1/s"},
"authors":[{"name":"Ada Kim"}]}]}
"""
_ARXIV = """\
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:arxiv="http://arxiv.org/schemas/atom">
<entry>
<title>Report title</title>
<published>2020-01-02T00:00:00Z</published>
<author><name>Ada Kim</name></author>
<arxiv:doi>10.1/a</arxiv:doi>
</entry>
</feed>
"""
_CASES = [
(parse_europepmc, _EUROPEPMC, "europepmc", "10.1/e", 2020, "Kim"),
(parse_openalex, _OPENALEX, "openalex", "10.1/o", 2020, "Kim"),
(parse_crossref, _CROSSREF, "crossref", "10.1/c", 2020, "Kim"),
(parse_semanticscholar, _S2, "semanticscholar", "10.1/s", 2020, "Kim"),
(parse_arxiv, _ARXIV, "arxiv", "10.1/a", 2020, "Kim"),
]
_SPARSE = [
(
parse_europepmc,
"<response><resultList><result></result></resultList></response>",
),
(parse_openalex, '{"results":[{}]}'),
(parse_crossref, '{"message":{"items":[{}]}}'),
(parse_semanticscholar, '{"data":[{}]}'),
(parse_arxiv, '<feed xmlns="http://www.w3.org/2005/Atom"><entry></entry></feed>'),
]
@pytest.mark.parametrize(
("parser", "payload", "database", "doi", "year", "author"), _CASES
)
def test_one_record(parser, payload, database, doi, year, author):
result = parser(payload, query="frailty", searched_on="2026-10-31")
assert result.log.hit_count == 1
assert result.log.database == database
assert len(result.hits) == 1
hit = result.hits[0]
assert hit.title == "Report title"
assert hit.database == database
assert hit.doi == doi
assert hit.year == year
assert hit.first_author == author
assert hit.pmid == ""
@pytest.mark.parametrize(
("parser", "_payload", "database", "_doi", "_year", "_author"), _CASES
)
def test_empty_payload_returns_no_hits(
parser, _payload, database, _doi, _year, _author
):
result = parser("", query="frailty", searched_on="2026-10-31")
assert result.hits == ()
assert result.log.hit_count == 0
assert result.log.database == database
@pytest.mark.parametrize(("parser", "payload"), _SPARSE)
def test_missing_fields_are_empty(parser, payload):
result = parser(payload, query="frailty", searched_on="2026-10-31")
assert result.log.hit_count == 1
hit = result.hits[0]
assert hit.title == ""
assert hit.doi == ""
assert hit.first_author == ""
assert hit.year is None