pyrefman-crossref 0.1.0a1__py3-none-any.whl
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.
- pyrefman_crossref/__init__.py +145 -0
- pyrefman_crossref-0.1.0a1.dist-info/METADATA +40 -0
- pyrefman_crossref-0.1.0a1.dist-info/RECORD +6 -0
- pyrefman_crossref-0.1.0a1.dist-info/WHEEL +4 -0
- pyrefman_crossref-0.1.0a1.dist-info/entry_points.txt +2 -0
- pyrefman_crossref-0.1.0a1.dist-info/licenses/LICENSE +21 -0
|
@@ -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,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,6 @@
|
|
|
1
|
+
pyrefman_crossref/__init__.py,sha256=y_EIZ-y1yJgtnSfRbiKu5vqCLM4kDppb9DMkQlY33y8,5466
|
|
2
|
+
pyrefman_crossref-0.1.0a1.dist-info/METADATA,sha256=UFDfj9fyuS8wucEeJiANgMspzoAXF6duYPe1Mz5lDTo,1284
|
|
3
|
+
pyrefman_crossref-0.1.0a1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
4
|
+
pyrefman_crossref-0.1.0a1.dist-info/entry_points.txt,sha256=SHhGBud8Si6AVWZjc1Wl9KjXlysSumz9_v9-dS7TRw4,67
|
|
5
|
+
pyrefman_crossref-0.1.0a1.dist-info/licenses/LICENSE,sha256=5ORw3n8_e1PPmgvK86lRUn07XLoNdkHypRr0JKsLxYQ,1065
|
|
6
|
+
pyrefman_crossref-0.1.0a1.dist-info/RECORD,,
|
|
@@ -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.
|