From aa1d31db247951e87ff0ae57416ec7d26b140839 Mon Sep 17 00:00:00 2001 From: kert Date: Sat, 31 Oct 2026 20:31:21 -0400 Subject: [PATCH] feat(prisma): parsers for Europe PMC, OpenAlex, Crossref, Semantic Scholar, arXiv --- src/prisma/search/arxiv.py | 52 +++++++++++++ src/prisma/search/base.py | 48 ++++++++++++ src/prisma/search/crossref.py | 43 +++++++++++ src/prisma/search/europepmc.py | 33 ++++++++ src/prisma/search/openalex.py | 36 +++++++++ src/prisma/search/semanticscholar.py | 39 ++++++++++ tests/prisma/test_search_others.py | 108 +++++++++++++++++++++++++++ 7 files changed, 359 insertions(+) create mode 100644 src/prisma/search/arxiv.py create mode 100644 src/prisma/search/crossref.py create mode 100644 src/prisma/search/europepmc.py create mode 100644 src/prisma/search/openalex.py create mode 100644 src/prisma/search/semanticscholar.py create mode 100644 tests/prisma/test_search_others.py diff --git a/src/prisma/search/arxiv.py b/src/prisma/search/arxiv.py new file mode 100644 index 0000000..7b0bb17 --- /dev/null +++ b/src/prisma/search/arxiv.py @@ -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) diff --git a/src/prisma/search/base.py b/src/prisma/search/base.py index 7b10701..c57d609 100644 --- a/src/prisma/search/base.py +++ b/src/prisma/search/base.py @@ -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. diff --git a/src/prisma/search/crossref.py b/src/prisma/search/crossref.py new file mode 100644 index 0000000..e0a4228 --- /dev/null +++ b/src/prisma/search/crossref.py @@ -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) diff --git a/src/prisma/search/europepmc.py b/src/prisma/search/europepmc.py new file mode 100644 index 0000000..beaec9c --- /dev/null +++ b/src/prisma/search/europepmc.py @@ -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) diff --git a/src/prisma/search/openalex.py b/src/prisma/search/openalex.py new file mode 100644 index 0000000..65c7d3d --- /dev/null +++ b/src/prisma/search/openalex.py @@ -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) diff --git a/src/prisma/search/semanticscholar.py b/src/prisma/search/semanticscholar.py new file mode 100644 index 0000000..ee70bb0 --- /dev/null +++ b/src/prisma/search/semanticscholar.py @@ -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 + ) diff --git a/tests/prisma/test_search_others.py b/tests/prisma/test_search_others.py new file mode 100644 index 0000000..c392317 --- /dev/null +++ b/tests/prisma/test_search_others.py @@ -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 = """\ + + Report title + 10.1/e + 2020 + Kim + +""" + +_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 = """\ + + + Report title + 2020-01-02T00:00:00Z + Ada Kim + 10.1/a + + +""" + +_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, + "", + ), + (parse_openalex, '{"results":[{}]}'), + (parse_crossref, '{"message":{"items":[{}]}}'), + (parse_semanticscholar, '{"data":[{}]}'), + (parse_arxiv, ''), +] + + +@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