pyrefman-crossref 0.1.0a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Icntaann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyrefman-crossref
3
+ Version: 0.1.0a1
4
+ Summary: Crossref resolver plugin for pyrefman
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: pyrefman>=0.1.0a1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # pyrefman-crossref
15
+
16
+ A Crossref resolver for [pyrefman](https://github.com/Icntaann/pyrefman).
17
+
18
+ ```sh
19
+ pip install pyrefman pyrefman-crossref
20
+ ```
21
+
22
+ ```python
23
+ from pyrefman import ReferenceManager
24
+
25
+ manager = ReferenceManager("library")
26
+ reference = manager.add(identifier="10.1038/nphys1170", type="article-journal")
27
+ print(reference.title) # Measured measurement
28
+ ```
29
+
30
+ The plugin registers itself through the `pyrefman.resolvers` entry-point group, so nothing
31
+ in your code names it. If Crossref does not know the DOI, `add()` returns `None` and
32
+ `manager.last_resolution.error` says why.
33
+
34
+ **Status: alpha.** The translation covers the fields that matter for citation — title,
35
+ authors, container, year, volume, issue, pages, DOI, ISSN, type. Crossref carries much more
36
+ (relations, licences, funders, abstracts as JATS XML); none of it is mapped yet.
37
+
38
+ ## License
39
+
40
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ # pyrefman-crossref
2
+
3
+ A Crossref resolver for [pyrefman](https://github.com/Icntaann/pyrefman).
4
+
5
+ ```sh
6
+ pip install pyrefman pyrefman-crossref
7
+ ```
8
+
9
+ ```python
10
+ from pyrefman import ReferenceManager
11
+
12
+ manager = ReferenceManager("library")
13
+ reference = manager.add(identifier="10.1038/nphys1170", type="article-journal")
14
+ print(reference.title) # Measured measurement
15
+ ```
16
+
17
+ The plugin registers itself through the `pyrefman.resolvers` entry-point group, so nothing
18
+ in your code names it. If Crossref does not know the DOI, `add()` returns `None` and
19
+ `manager.last_resolution.error` says why.
20
+
21
+ **Status: alpha.** The translation covers the fields that matter for citation — title,
22
+ authors, container, year, volume, issue, pages, DOI, ISSN, type. Crossref carries much more
23
+ (relations, licences, funders, abstracts as JATS XML); none of it is mapped yet.
24
+
25
+ ## License
26
+
27
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pyrefman-crossref"
7
+ version = "0.1.0a1"
8
+ description = "Crossref resolver plugin for pyrefman"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["pyrefman>=0.1.0a1"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+
20
+ [dependency-groups]
21
+ dev = ["pytest>=8"]
22
+
23
+ [project.entry-points."pyrefman.resolvers"]
24
+ crossref = "pyrefman_crossref:CrossrefResolver"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/pyrefman_crossref"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
@@ -0,0 +1,145 @@
1
+ """A Crossref resolver for pyrefman.
2
+
3
+ The plugin speaks the ``Resolver`` contract without importing it: a name, the schemes it
4
+ answers for, and a ``resolve()`` that returns ``(fields, error)``. Every failure becomes an
5
+ error string — a timeout, a malformed body and a DOI Crossref does not know are all normal
6
+ answers to a lookup, not exceptions.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from collections.abc import Callable
16
+ from typing import Any
17
+
18
+ API = "https://api.crossref.org/works/"
19
+ USER_AGENT = "pyrefman-crossref/0.1 (+https://github.com/Icntaann/pyrefman)"
20
+
21
+ #: Crossref names its types after its own model; CSL names them after the citation model.
22
+ TYPE_MAP = {
23
+ "journal-article": "article-journal",
24
+ "book-chapter": "chapter",
25
+ "book-section": "chapter",
26
+ "proceedings-article": "paper-conference",
27
+ "book": "book",
28
+ "monograph": "book",
29
+ "edited-book": "book",
30
+ "reference-book": "book",
31
+ "report": "report",
32
+ "dissertation": "thesis",
33
+ "posted-content": "article",
34
+ "dataset": "dataset",
35
+ "peer-review": "article",
36
+ "standard": "standard",
37
+ "component": "article",
38
+ }
39
+
40
+ #: Fields Crossref already spells the way CSL does.
41
+ PLAIN_FIELDS = ("DOI", "volume", "issue", "page", "publisher", "URL")
42
+
43
+ #: Fields Crossref sends as a list whose first entry CSL wants as a string.
44
+ LIST_FIELDS = ("title", "container-title", "short-container-title", "ISSN")
45
+
46
+ #: Where a work's date may live, best first.
47
+ DATE_FIELDS = ("issued", "published-print", "published-online", "published", "created")
48
+
49
+
50
+ class CrossrefResolver:
51
+ """Looks a DOI up in the Crossref REST API."""
52
+
53
+ name = "crossref"
54
+ schemes: tuple[str, ...] = ("doi",)
55
+
56
+ def __init__(self, fetch: Callable[[str], dict[str, Any]] | None = None, timeout: float = 15.0):
57
+ self._fetch = fetch or (lambda url: _get_json(url, timeout))
58
+
59
+ def resolve(self, identifier: str) -> tuple[dict[str, Any] | None, str | None]:
60
+ """Return CSL fields for a DOI, or a reason why there are none."""
61
+ try:
62
+ message = self._fetch(API + urllib.parse.quote(identifier, safe="/"))
63
+ except LookupError as error:
64
+ return None, str(error)
65
+ except urllib.error.HTTPError as error:
66
+ return None, f"crossref answered {error.code} for {identifier}"
67
+ except urllib.error.URLError as error:
68
+ return None, f"crossref unreachable: {error.reason}"
69
+ except (TimeoutError, json.JSONDecodeError, UnicodeDecodeError) as error:
70
+ return None, f"crossref sent an unusable answer: {error}"
71
+
72
+ if not isinstance(message, dict):
73
+ return None, "crossref sent an unusable answer: not an object"
74
+
75
+ try:
76
+ fields = to_csl(message)
77
+ except (TypeError, ValueError, KeyError) as error: # a shape we do not understand
78
+ return None, f"crossref sent an unexpected record: {error}"
79
+
80
+ if not fields.get("title"):
81
+ return None, f"crossref has no title for {identifier}"
82
+
83
+ # The caller may have sent a bare DOI that Crossref echoes under another case.
84
+ fields["DOI"] = str(message.get("DOI") or identifier)
85
+ return fields, None
86
+
87
+
88
+ def to_csl(message: dict[str, Any]) -> dict[str, Any]:
89
+ """Crossref's ``message`` object as CSL fields."""
90
+ fields: dict[str, Any] = {}
91
+
92
+ for name in LIST_FIELDS:
93
+ value = message.get(name)
94
+ if isinstance(value, list) and value:
95
+ fields[name] = str(value[0])
96
+ for name in PLAIN_FIELDS:
97
+ value = message.get(name)
98
+ if isinstance(value, str) and value.strip():
99
+ fields[name] = value.strip()
100
+
101
+ authors = _names(message.get("author")) or _names(message.get("editor"))
102
+ if authors:
103
+ fields["author"] = authors
104
+
105
+ for name in DATE_FIELDS:
106
+ date_parts = (message.get(name) or {}).get("date-parts")
107
+ if isinstance(date_parts, list) and date_parts and date_parts[0]:
108
+ fields["issued"] = {"date-parts": [date_parts[0]]}
109
+ break
110
+
111
+ csl_type = TYPE_MAP.get(str(message.get("type", "")))
112
+ fields["type"] = csl_type or "article"
113
+ return fields
114
+
115
+
116
+ def _names(people: Any) -> list[dict[str, str]]:
117
+ """Crossref people as CSL names, keeping organisations as literal names."""
118
+ if not isinstance(people, list):
119
+ return []
120
+ names = []
121
+ for person in people:
122
+ if not isinstance(person, dict):
123
+ continue
124
+ if "family" in person:
125
+ names.append({"family": str(person["family"]), "given": str(person.get("given", ""))})
126
+ elif "name" in person:
127
+ # A corporate author: CSL has no family/given split for it.
128
+ names.append({"literal": str(person["name"])})
129
+ return names
130
+
131
+
132
+ def _get_json(url: str, timeout: float) -> dict[str, Any]:
133
+ """The ``message`` object of a Crossref response."""
134
+ request = urllib.request.Request(
135
+ url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"}
136
+ )
137
+ try:
138
+ with urllib.request.urlopen(request, timeout=timeout) as response:
139
+ document: dict[str, Any] = json.loads(response.read().decode("utf-8"))
140
+ message: dict[str, Any] = document["message"]
141
+ return message
142
+ except urllib.error.HTTPError as error:
143
+ if error.code == 404:
144
+ raise LookupError(f"Crossref does not know the DOI in {url}") from error
145
+ raise
@@ -0,0 +1,194 @@
1
+ """The Crossref response becomes CSL; failures come back as reasons, not exceptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from pyrefman_crossref import CrossrefResolver, to_csl
11
+
12
+ from pyrefman import ReferenceManager
13
+ from pyrefman.plugins import Registry
14
+
15
+ MESSAGE = {
16
+ "DOI": "10.1038/nphys1170",
17
+ "type": "journal-article",
18
+ "title": ["Measured measurement"],
19
+ "author": [
20
+ {"given": "Markus", "family": "Aspelmeyer", "sequence": "first", "affiliation": []},
21
+ {"given": "Anton", "family": "Zeilinger", "sequence": "additional"},
22
+ ],
23
+ "issued": {"date-parts": [[2009, 1]]},
24
+ "container-title": ["Nature Physics"],
25
+ "page": "11-12",
26
+ "volume": "5",
27
+ "issue": "1",
28
+ "publisher": "Springer Science and Business Media LLC",
29
+ "ISSN": ["1745-2473", "1745-2481"],
30
+ "URL": "https://doi.org/10.1038/nphys1170",
31
+ }
32
+
33
+
34
+ def fake_fetch(message: dict[str, Any] | None = None, error: Exception | None = None):
35
+ def fetch(url: str) -> dict[str, Any]:
36
+ if error is not None:
37
+ raise error
38
+ return message if message is not None else MESSAGE
39
+
40
+ return fetch
41
+
42
+
43
+ # --- translation -------------------------------------------------------------
44
+
45
+
46
+ def test_a_journal_article_becomes_csl_fields() -> None:
47
+ fields = to_csl(MESSAGE)
48
+
49
+ assert fields["title"] == "Measured measurement"
50
+ assert fields["container-title"] == "Nature Physics"
51
+ assert fields["type"] == "article-journal"
52
+ assert fields["DOI"] == "10.1038/nphys1170"
53
+ assert fields["issued"] == {"date-parts": [[2009, 1]]}
54
+ assert fields["page"] == "11-12"
55
+ assert fields["ISSN"] == "1745-2473"
56
+
57
+
58
+ def test_authors_become_csl_names_without_crossref_bookkeeping() -> None:
59
+ fields = to_csl(MESSAGE)
60
+
61
+ assert fields["author"] == [
62
+ {"family": "Aspelmeyer", "given": "Markus"},
63
+ {"family": "Zeilinger", "given": "Anton"},
64
+ ]
65
+
66
+
67
+ def test_a_corporate_author_survives_as_a_literal_name() -> None:
68
+ fields = to_csl({"title": ["A Report"], "author": [{"name": "World Health Organization"}]})
69
+
70
+ assert fields["author"] == [{"literal": "World Health Organization"}]
71
+
72
+
73
+ def test_a_chapter_keeps_its_own_type() -> None:
74
+ assert to_csl({"type": "book-chapter", "title": ["A Chapter"]})["type"] == "chapter"
75
+
76
+
77
+ def test_an_unknown_type_falls_back_to_article() -> None:
78
+ assert to_csl({"type": "something-new", "title": ["X"]})["type"] == "article"
79
+
80
+
81
+ def test_an_online_only_date_is_used_when_nothing_else_is_there() -> None:
82
+ fields = to_csl({"title": ["X"], "published-online": {"date-parts": [[2021, 5]]}})
83
+
84
+ assert fields["issued"] == {"date-parts": [[2021, 5]]}
85
+
86
+
87
+ def test_an_abstract_is_not_copied_into_csl() -> None:
88
+ fields = to_csl({"title": ["X"], "abstract": "<jats:p>raw xml</jats:p>"})
89
+
90
+ assert "abstract" not in fields, "abstracts belong to an enricher, not the resolver"
91
+
92
+
93
+ # --- failure -----------------------------------------------------------------
94
+
95
+
96
+ def test_an_unknown_doi_is_a_reason_not_an_exception() -> None:
97
+ resolver = CrossrefResolver(fetch=fake_fetch(error=LookupError("Crossref does not know it")))
98
+
99
+ fields, error = resolver.resolve("10.9999/missing")
100
+
101
+ assert fields is None
102
+ assert "does not know" in (error or "")
103
+
104
+
105
+ def test_an_unreachable_api_is_a_reason_not_an_exception() -> None:
106
+ resolver = CrossrefResolver(fetch=fake_fetch(error=urllib.error.URLError("offline")))
107
+
108
+ _, error = resolver.resolve("10.1038/nphys1170")
109
+
110
+ assert "unreachable" in (error or "")
111
+
112
+
113
+ def test_a_rate_limit_is_reported_with_its_status() -> None:
114
+ failure = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) # type: ignore[arg-type]
115
+ resolver = CrossrefResolver(fetch=fake_fetch(error=failure))
116
+
117
+ _, error = resolver.resolve("10.1038/nphys1170")
118
+
119
+ assert "429" in (error or "")
120
+
121
+
122
+ def test_a_read_timeout_is_a_reason_not_an_exception() -> None:
123
+ resolver = CrossrefResolver(fetch=fake_fetch(error=TimeoutError("timed out")))
124
+
125
+ _, error = resolver.resolve("10.1038/nphys1170")
126
+
127
+ assert "unusable answer" in (error or "")
128
+
129
+
130
+ def test_a_malformed_body_is_a_reason_not_an_exception() -> None:
131
+ resolver = CrossrefResolver(fetch=fake_fetch(error=json.JSONDecodeError("x", "", 0)))
132
+
133
+ _, error = resolver.resolve("10.1038/nphys1170")
134
+
135
+ assert "unusable answer" in (error or "")
136
+
137
+
138
+ def test_a_record_without_a_title_is_not_a_success() -> None:
139
+ resolver = CrossrefResolver(fetch=fake_fetch({"DOI": "10.1038/nphys1170"}))
140
+
141
+ fields, error = resolver.resolve("10.1038/nphys1170")
142
+
143
+ assert fields is None
144
+ assert "no title" in (error or "")
145
+
146
+
147
+ def test_the_requested_identifier_is_always_in_the_result() -> None:
148
+ resolver = CrossrefResolver(fetch=fake_fetch({"title": ["X"], "type": "journal-article"}))
149
+
150
+ fields, _ = resolver.resolve("10.1038/nphys1170")
151
+
152
+ assert fields is not None
153
+ assert fields["DOI"] == "10.1038/nphys1170", "without it, duplicate detection falls to titles"
154
+
155
+
156
+ # --- through the library -----------------------------------------------------
157
+
158
+
159
+ def test_the_plugin_creates_a_reference_through_the_api(tmp_path: Path) -> None:
160
+ registry = Registry()
161
+ registry.register("resolvers", CrossrefResolver(fetch=fake_fetch()))
162
+ manager = ReferenceManager(tmp_path / "library", registry=registry)
163
+
164
+ reference = manager.add(identifier="10.1038/nphys1170", type="article-journal")
165
+
166
+ assert reference is not None
167
+ assert reference.title == "Measured measurement"
168
+ assert reference.type == "article-journal"
169
+ assert reference.provenance["title"]["source"] == "crossref"
170
+
171
+
172
+ def test_a_failed_lookup_creates_nothing(tmp_path: Path) -> None:
173
+ registry = Registry()
174
+ registry.register(
175
+ "resolvers", CrossrefResolver(fetch=fake_fetch(error=LookupError("unknown DOI")))
176
+ )
177
+ manager = ReferenceManager(tmp_path / "library", registry=registry)
178
+
179
+ assert manager.add(identifier="10.9999/missing") is None
180
+ assert manager.find("missing") == []
181
+
182
+
183
+ def test_the_entry_point_yields_a_working_resolver() -> None:
184
+ from importlib.metadata import entry_points
185
+
186
+ found = {entry.name: entry for entry in entry_points(group="pyrefman.resolvers")}
187
+ resolver = found["crossref"].load()()
188
+
189
+ assert resolver.schemes == ("doi",)
190
+ assert resolver.name == "crossref"
191
+
192
+
193
+ def test_the_resolver_answers_for_dois_only() -> None:
194
+ assert CrossrefResolver().schemes == ("doi",)