paperminertoolkit 1.0.0__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.
- paperminertoolkit/__init__.py +10 -0
- paperminertoolkit/_version.py +11 -0
- paperminertoolkit/cli.py +1053 -0
- paperminertoolkit/corpus/__init__.py +1 -0
- paperminertoolkit/corpus/database.py +1542 -0
- paperminertoolkit/corpus/documents.py +313 -0
- paperminertoolkit/corpus/filtering.py +1390 -0
- paperminertoolkit/corpus/metadata.py +532 -0
- paperminertoolkit/extraction/__init__.py +1 -0
- paperminertoolkit/extraction/compression.py +486 -0
- paperminertoolkit/extraction/extract.py +573 -0
- paperminertoolkit/extraction/models.py +784 -0
- paperminertoolkit/extraction/recipes.py +241 -0
- paperminertoolkit/extraction/scrape.py +737 -0
- paperminertoolkit/extraction/store.py +244 -0
- paperminertoolkit/extraction/tokenizer.py +313 -0
- paperminertoolkit/providers/__init__.py +1 -0
- paperminertoolkit/providers/arxiv.py +760 -0
- paperminertoolkit/providers/base.py +514 -0
- paperminertoolkit/providers/biorxiv.py +561 -0
- paperminertoolkit/providers/chemrxiv.py +1115 -0
- paperminertoolkit/providers/core.py +423 -0
- paperminertoolkit/providers/crossref.py +649 -0
- paperminertoolkit/providers/elsevier.py +455 -0
- paperminertoolkit/providers/medrxiv.py +548 -0
- paperminertoolkit/providers/openalex.py +471 -0
- paperminertoolkit/providers/pubmed.py +1272 -0
- paperminertoolkit/providers/registry.py +521 -0
- paperminertoolkit/providers/rxiv.py +936 -0
- paperminertoolkit/providers/unpaywall.py +162 -0
- paperminertoolkit/resources/recipes.json +1670 -0
- paperminertoolkit/settings.py +661 -0
- paperminertoolkit/workflows/__init__.py +1 -0
- paperminertoolkit/workflows/download.py +1748 -0
- paperminertoolkit/workflows/enrichment.py +1906 -0
- paperminertoolkit/workflows/imports.py +121 -0
- paperminertoolkit/workflows/search.py +877 -0
- paperminertoolkit/workflows/topics.py +2837 -0
- paperminertoolkit/workflows/utilities.py +73 -0
- paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
- paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
- paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
- paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
- paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""Extract and enrich paper metadata from DOI text and Crossref.
|
|
2
|
+
|
|
3
|
+
The helpers here read DOI values from raw text/PDFs, normalize them, and use
|
|
4
|
+
Crossref to populate the public paper metadata fields stored in the corpus.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html
|
|
10
|
+
import re
|
|
11
|
+
import requests
|
|
12
|
+
import unicodedata
|
|
13
|
+
from collections import Counter
|
|
14
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
15
|
+
from os import PathLike
|
|
16
|
+
from typing import Any, Literal
|
|
17
|
+
from urllib.parse import unquote
|
|
18
|
+
|
|
19
|
+
from pypdf import PdfReader
|
|
20
|
+
|
|
21
|
+
from paperminertoolkit.corpus.documents import read_pdf_text
|
|
22
|
+
|
|
23
|
+
MODERN_DOI_PATTERN = r'10\.\d{4,9}/(?:[-._;()/:A-Z0-9]|%[0-9A-F]{2})+'
|
|
24
|
+
# These two older publisher formats contain characters excluded by the modern
|
|
25
|
+
# Crossref pattern. Keep them narrow to avoid treating arbitrary URLs as DOIs.
|
|
26
|
+
LEGACY_DOI_PATTERNS = (
|
|
27
|
+
r'10\.1002/\S+',
|
|
28
|
+
r'10\.1207/[\w\d]+&\d+_\d+',
|
|
29
|
+
)
|
|
30
|
+
DOI_PRESENTATION_PREFIX = r'(?:(?:https?://(?:dx\.)?doi\.org/)|(?:doi\s*:\s*))?'
|
|
31
|
+
DOI_PATTERN = re.compile(
|
|
32
|
+
DOI_PRESENTATION_PREFIX + '(?:' + '|'.join((*LEGACY_DOI_PATTERNS, MODERN_DOI_PATTERN)) + ')',
|
|
33
|
+
re.IGNORECASE,
|
|
34
|
+
)
|
|
35
|
+
DOI_URL_PREFIX = re.compile(r'^https?://(?:dx\.)?doi\.org/', re.IGNORECASE)
|
|
36
|
+
DOI_LABEL_PREFIX = re.compile(r'^doi\s*:\s*', re.IGNORECASE)
|
|
37
|
+
TRAILING_SENTENCE_PUNCTUATION = '.,;:'
|
|
38
|
+
TRAILING_DELIMITERS = {')': '(', ']': '[', '}': '{', '>': '<'}
|
|
39
|
+
INVISIBLE_CHARACTERS = str.maketrans('', '', '\u200b\u200c\u200d\u2060\ufeff')
|
|
40
|
+
UNICODE_PUNCTUATION = str.maketrans({
|
|
41
|
+
'\u2010': '-',
|
|
42
|
+
'\u2011': '-',
|
|
43
|
+
'\u2012': '-',
|
|
44
|
+
'\u2013': '-',
|
|
45
|
+
'\u2014': '-',
|
|
46
|
+
'\u2015': '-',
|
|
47
|
+
'\u2212': '-',
|
|
48
|
+
'\u2018': "'",
|
|
49
|
+
'\u2019': "'",
|
|
50
|
+
'\u201a': "'",
|
|
51
|
+
'\u201b': "'",
|
|
52
|
+
'\u201c': '"',
|
|
53
|
+
'\u201d': '"',
|
|
54
|
+
'\u201e': '"',
|
|
55
|
+
'\u201f': '"',
|
|
56
|
+
'\u2026': '...',
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def clean_doi(value: object) -> str:
|
|
61
|
+
"""Canonicalize a DOI presentation value.
|
|
62
|
+
|
|
63
|
+
Parameters
|
|
64
|
+
----------
|
|
65
|
+
value : object
|
|
66
|
+
Plain DOI, labelled DOI, or DOI resolver URL.
|
|
67
|
+
|
|
68
|
+
Returns
|
|
69
|
+
-------
|
|
70
|
+
str
|
|
71
|
+
Case-folded DOI without presentation prefixes or trailing sentence
|
|
72
|
+
punctuation.
|
|
73
|
+
"""
|
|
74
|
+
doi = unicodedata.normalize('NFKC', html.unescape(str(value or ''))).translate(UNICODE_PUNCTUATION)
|
|
75
|
+
doi = doi.translate(INVISIBLE_CHARACTERS).strip()
|
|
76
|
+
|
|
77
|
+
url_prefix = DOI_URL_PREFIX.match(doi)
|
|
78
|
+
if url_prefix:
|
|
79
|
+
doi = unquote(doi[url_prefix.end():])
|
|
80
|
+
doi = re.split(r'[?#]', doi, maxsplit=1)[0]
|
|
81
|
+
else:
|
|
82
|
+
doi = DOI_LABEL_PREFIX.sub('', doi, count=1)
|
|
83
|
+
doi = doi.strip()
|
|
84
|
+
|
|
85
|
+
while doi:
|
|
86
|
+
final_character = doi[-1]
|
|
87
|
+
if final_character in TRAILING_SENTENCE_PUNCTUATION or final_character in {'"', "'"}:
|
|
88
|
+
doi = doi[:-1]
|
|
89
|
+
continue
|
|
90
|
+
opening_character = TRAILING_DELIMITERS.get(final_character)
|
|
91
|
+
if opening_character and doi.count(final_character) > doi.count(opening_character):
|
|
92
|
+
doi = doi[:-1]
|
|
93
|
+
continue
|
|
94
|
+
break
|
|
95
|
+
return doi.casefold()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _normalize_metadata_text(value: object) -> str:
|
|
99
|
+
"""Normalize text from a metadata provider.
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
value : object
|
|
104
|
+
Metadata value to convert to plain text. ``None`` represents missing
|
|
105
|
+
text.
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
str
|
|
110
|
+
Whitespace-normalized text with HTML removed and Unicode punctuation
|
|
111
|
+
and super/subscripts flattened.
|
|
112
|
+
"""
|
|
113
|
+
if value is None:
|
|
114
|
+
return ''
|
|
115
|
+
text = html.unescape(str(value))
|
|
116
|
+
text = re.sub(r'</?(?:sub|sup)>', '', text, flags=re.IGNORECASE)
|
|
117
|
+
text = re.sub(r'<[^>]+>', '', text)
|
|
118
|
+
text = unicodedata.normalize('NFKC', text)
|
|
119
|
+
text = text.translate(UNICODE_PUNCTUATION)
|
|
120
|
+
text = ''.join(_normalize_punctuation_char(character) for character in text)
|
|
121
|
+
text = re.sub(r'\s+', ' ', text)
|
|
122
|
+
return text.strip()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _normalize_punctuation_char(character: str) -> str:
|
|
126
|
+
"""Approximate a Unicode punctuation character in ASCII.
|
|
127
|
+
|
|
128
|
+
Parameters
|
|
129
|
+
----------
|
|
130
|
+
character : str
|
|
131
|
+
Single character to normalize.
|
|
132
|
+
|
|
133
|
+
Returns
|
|
134
|
+
-------
|
|
135
|
+
str
|
|
136
|
+
ASCII approximation when available, an empty string for unsupported
|
|
137
|
+
punctuation, or the original non-punctuation character.
|
|
138
|
+
"""
|
|
139
|
+
if ord(character) < 128:
|
|
140
|
+
return character
|
|
141
|
+
category = unicodedata.category(character)
|
|
142
|
+
name = unicodedata.name(character, '').lower()
|
|
143
|
+
if category == 'Pd' or 'dash' in name or 'hyphen' in name or 'minus' in name:
|
|
144
|
+
return '-'
|
|
145
|
+
if 'apostrophe' in name or 'single quotation' in name:
|
|
146
|
+
return "'"
|
|
147
|
+
if 'quotation mark' in name or 'double quotation' in name:
|
|
148
|
+
return '"'
|
|
149
|
+
if category.startswith('P'):
|
|
150
|
+
return unicodedata.normalize('NFKD', character).encode('ascii', 'ignore').decode('ascii')
|
|
151
|
+
return character
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _is_article_doi(doi: str) -> bool:
|
|
155
|
+
"""Check whether a DOI candidate appears to identify an article.
|
|
156
|
+
|
|
157
|
+
Parameters
|
|
158
|
+
----------
|
|
159
|
+
doi : str
|
|
160
|
+
DOI candidate.
|
|
161
|
+
|
|
162
|
+
Returns
|
|
163
|
+
-------
|
|
164
|
+
bool
|
|
165
|
+
``True`` for a non-empty DOI that does not identify ISSN metadata.
|
|
166
|
+
"""
|
|
167
|
+
return bool(doi) and '(issn)' not in doi.lower()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _rank_doi_candidates(candidates: Iterable[str]) -> list[str]:
|
|
171
|
+
"""Rank canonical DOI candidates by frequency.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
candidates : Iterable[str]
|
|
176
|
+
DOI presentation values to clean and rank.
|
|
177
|
+
|
|
178
|
+
Returns
|
|
179
|
+
-------
|
|
180
|
+
list[str]
|
|
181
|
+
Unique article DOI candidates ordered by descending frequency, with
|
|
182
|
+
first appearance breaking ties.
|
|
183
|
+
"""
|
|
184
|
+
cleaned = []
|
|
185
|
+
for candidate in candidates:
|
|
186
|
+
doi = clean_doi(candidate)
|
|
187
|
+
if _is_article_doi(doi):
|
|
188
|
+
cleaned.append(doi)
|
|
189
|
+
counts = Counter(cleaned)
|
|
190
|
+
first_seen = {}
|
|
191
|
+
for index, doi in enumerate(cleaned):
|
|
192
|
+
first_seen.setdefault(doi, index)
|
|
193
|
+
return sorted(counts, key=lambda doi: (-counts[doi], first_seen[doi]))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def extract_dois_from_text(text: str) -> list[str]:
|
|
197
|
+
"""Extract DOI candidates from text.
|
|
198
|
+
|
|
199
|
+
Parameters
|
|
200
|
+
----------
|
|
201
|
+
text : str
|
|
202
|
+
Text that may contain DOI values and common PDF extraction artifacts.
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
list[str]
|
|
207
|
+
Canonical DOI candidates ranked by frequency.
|
|
208
|
+
"""
|
|
209
|
+
normalized = unicodedata.normalize('NFKC', html.unescape(str(text or ''))).translate(UNICODE_PUNCTUATION)
|
|
210
|
+
normalized = normalized.translate(INVISIBLE_CHARACTERS)
|
|
211
|
+
# A soft hyphen marks a word-wrap rather than part of the identifier. PDF
|
|
212
|
+
# extractors may retain both it and the following line break.
|
|
213
|
+
normalized = re.sub(r'\u00ad[ \t]*(?:\r?\n)?[ \t]*', '', normalized)
|
|
214
|
+
# Joining immediately after the mandatory prefix slash is unambiguous. Do
|
|
215
|
+
# not join arbitrary DOI-looking lines: a DOI can legitimately end there.
|
|
216
|
+
normalized = re.sub(r'(10\.\d{4,9}/)[ \t]*\r?\n[ \t]*', r'\1', normalized, flags=re.IGNORECASE)
|
|
217
|
+
normalized = re.sub(r'\s+', ' ', normalized)
|
|
218
|
+
return _rank_doi_candidates(match.group(0) for match in DOI_PATTERN.finditer(normalized))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def extract_doi_from_text(text: str) -> str | None:
|
|
222
|
+
"""Extract the most likely DOI from text.
|
|
223
|
+
|
|
224
|
+
Parameters
|
|
225
|
+
----------
|
|
226
|
+
text : str
|
|
227
|
+
Text that may contain a DOI.
|
|
228
|
+
|
|
229
|
+
Returns
|
|
230
|
+
-------
|
|
231
|
+
str or None
|
|
232
|
+
Highest-ranked canonical DOI, or ``None`` when no candidate exists.
|
|
233
|
+
"""
|
|
234
|
+
candidates = extract_dois_from_text(text)
|
|
235
|
+
if not candidates:
|
|
236
|
+
return None
|
|
237
|
+
return candidates[0]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def extract_dois_from_pdf_metadata(pdf_path: str | PathLike[str]) -> list[str]:
|
|
241
|
+
"""Extract DOI candidates from embedded PDF metadata.
|
|
242
|
+
|
|
243
|
+
Parameters
|
|
244
|
+
----------
|
|
245
|
+
pdf_path : str or os.PathLike[str]
|
|
246
|
+
Path to the PDF file.
|
|
247
|
+
|
|
248
|
+
Returns
|
|
249
|
+
-------
|
|
250
|
+
list[str]
|
|
251
|
+
Unique DOI candidates in metadata field order.
|
|
252
|
+
"""
|
|
253
|
+
reader = PdfReader(pdf_path)
|
|
254
|
+
metadata = reader.metadata or {}
|
|
255
|
+
candidates = []
|
|
256
|
+
preferred_fields = [
|
|
257
|
+
'/WPS-ARTICLEDOI',
|
|
258
|
+
'/prism:doi',
|
|
259
|
+
'/doi',
|
|
260
|
+
'/DOI',
|
|
261
|
+
'/dc:identifier',
|
|
262
|
+
'/Subject',
|
|
263
|
+
]
|
|
264
|
+
for field in preferred_fields:
|
|
265
|
+
value = metadata.get(field)
|
|
266
|
+
if not value:
|
|
267
|
+
continue
|
|
268
|
+
candidates.extend(extract_dois_from_text(str(value)))
|
|
269
|
+
for key, value in metadata.items():
|
|
270
|
+
if 'journaldoi' in str(key).lower():
|
|
271
|
+
continue
|
|
272
|
+
candidates.extend(extract_dois_from_text(str(value)))
|
|
273
|
+
return list(dict.fromkeys(candidates))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def extract_doi_from_pdf_metadata(pdf_path: str | PathLike[str]) -> str | None:
|
|
277
|
+
"""Extract the best DOI from embedded PDF metadata.
|
|
278
|
+
|
|
279
|
+
Parameters
|
|
280
|
+
----------
|
|
281
|
+
pdf_path : str or os.PathLike[str]
|
|
282
|
+
Path to the PDF file.
|
|
283
|
+
|
|
284
|
+
Returns
|
|
285
|
+
-------
|
|
286
|
+
str or None
|
|
287
|
+
First metadata DOI candidate, or ``None`` when no candidate exists.
|
|
288
|
+
"""
|
|
289
|
+
candidates = extract_dois_from_pdf_metadata(pdf_path)
|
|
290
|
+
if not candidates:
|
|
291
|
+
return None
|
|
292
|
+
return candidates[0]
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def doi_candidates_from_pdf(pdf_path: str | PathLike[str]) -> list[str]:
|
|
296
|
+
"""Collect metadata-first DOI candidates from a PDF.
|
|
297
|
+
|
|
298
|
+
Parameters
|
|
299
|
+
----------
|
|
300
|
+
pdf_path : str or os.PathLike[str]
|
|
301
|
+
Path to the PDF file.
|
|
302
|
+
|
|
303
|
+
Returns
|
|
304
|
+
-------
|
|
305
|
+
list[str]
|
|
306
|
+
Unique metadata candidates followed by ranked page-text candidates.
|
|
307
|
+
"""
|
|
308
|
+
candidates = extract_dois_from_pdf_metadata(pdf_path)
|
|
309
|
+
text_candidates = extract_dois_from_text(read_pdf_text(pdf_path))
|
|
310
|
+
candidates.extend(candidate for candidate in text_candidates if candidate not in candidates)
|
|
311
|
+
return candidates
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def extract_doi_from_pdf(pdf_path: str | PathLike[str]) -> str | None:
|
|
315
|
+
"""Extract the most likely DOI from a PDF.
|
|
316
|
+
|
|
317
|
+
Parameters
|
|
318
|
+
----------
|
|
319
|
+
pdf_path : str or os.PathLike[str]
|
|
320
|
+
Path to the PDF file.
|
|
321
|
+
|
|
322
|
+
Returns
|
|
323
|
+
-------
|
|
324
|
+
str or None
|
|
325
|
+
First metadata or page-text candidate, or ``None`` when none exists.
|
|
326
|
+
"""
|
|
327
|
+
candidates = doi_candidates_from_pdf(pdf_path)
|
|
328
|
+
if not candidates:
|
|
329
|
+
return None
|
|
330
|
+
return candidates[0]
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _date_from_parts(parts: Sequence[Sequence[int]] | None) -> str:
|
|
334
|
+
"""Format a Crossref ``date-parts`` value.
|
|
335
|
+
|
|
336
|
+
Parameters
|
|
337
|
+
----------
|
|
338
|
+
parts : Sequence[Sequence[int]] or None
|
|
339
|
+
Crossref date components, with the first nested sequence representing
|
|
340
|
+
the date.
|
|
341
|
+
|
|
342
|
+
Returns
|
|
343
|
+
-------
|
|
344
|
+
str
|
|
345
|
+
Date formatted as ``YYYY``, ``YYYY-MM``, or ``YYYY-MM-DD``; an empty
|
|
346
|
+
string when no date is available.
|
|
347
|
+
"""
|
|
348
|
+
if not parts:
|
|
349
|
+
return ''
|
|
350
|
+
date = parts[0]
|
|
351
|
+
if not date:
|
|
352
|
+
return ''
|
|
353
|
+
if len(date) >= 3:
|
|
354
|
+
return f'{date[0]:04d}-{date[1]:02d}-{date[2]:02d}'
|
|
355
|
+
if len(date) == 2:
|
|
356
|
+
return f'{date[0]:04d}-{date[1]:02d}'
|
|
357
|
+
return f'{date[0]:04d}'
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _published_date(message: Mapping[str, Any]) -> str:
|
|
361
|
+
"""Select the best publication date from a Crossref message.
|
|
362
|
+
|
|
363
|
+
Parameters
|
|
364
|
+
----------
|
|
365
|
+
message : Mapping[str, Any]
|
|
366
|
+
Crossref work message containing optional date fields.
|
|
367
|
+
|
|
368
|
+
Returns
|
|
369
|
+
-------
|
|
370
|
+
str
|
|
371
|
+
First available publication date in preference order, or an empty
|
|
372
|
+
string.
|
|
373
|
+
"""
|
|
374
|
+
for key in ['published-print', 'published-online', 'published', 'issued', 'created']:
|
|
375
|
+
date = _date_from_parts(message.get(key, {}).get('date-parts'))
|
|
376
|
+
if date:
|
|
377
|
+
return date
|
|
378
|
+
return ''
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _crossref_issn(message: Mapping[str, Any]) -> str:
|
|
382
|
+
"""Join a Crossref work's ISSNs, print issues first.
|
|
383
|
+
|
|
384
|
+
Parameters
|
|
385
|
+
----------
|
|
386
|
+
message : Mapping[str, Any]
|
|
387
|
+
Crossref work message.
|
|
388
|
+
|
|
389
|
+
Returns
|
|
390
|
+
-------
|
|
391
|
+
str
|
|
392
|
+
Semicolon-separated ISSNs, or an empty string when none are deposited.
|
|
393
|
+
"""
|
|
394
|
+
typed = message.get('issn-type') or []
|
|
395
|
+
ordered = [entry.get('value') for entry in typed if (entry or {}).get('type') == 'print']
|
|
396
|
+
ordered.extend(entry.get('value') for entry in typed if (entry or {}).get('type') != 'print')
|
|
397
|
+
if not typed:
|
|
398
|
+
ordered = list(message.get('ISSN') or [])
|
|
399
|
+
return ';'.join(dict.fromkeys(str(value).strip() for value in ordered if value))
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _crossref_pages(message: Mapping[str, Any]) -> str:
|
|
403
|
+
"""Read a Crossref work's page range or article number.
|
|
404
|
+
|
|
405
|
+
Journals that number articles rather than pages, such as those published by
|
|
406
|
+
the American Physical Society, deposit ``article-number`` and no ``page``,
|
|
407
|
+
so the article number is used as the locator when no range is present.
|
|
408
|
+
|
|
409
|
+
Parameters
|
|
410
|
+
----------
|
|
411
|
+
message : Mapping[str, Any]
|
|
412
|
+
Crossref work message.
|
|
413
|
+
|
|
414
|
+
Returns
|
|
415
|
+
-------
|
|
416
|
+
str
|
|
417
|
+
Page range or article number as deposited, or an empty string.
|
|
418
|
+
"""
|
|
419
|
+
return str(message.get('page') or message.get('article-number') or '').strip()
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def crossref_fields(message: Mapping[str, Any], doi: str = '') -> dict[str, Any]:
|
|
423
|
+
"""Map a Crossref work message onto corpus column names.
|
|
424
|
+
|
|
425
|
+
Every returned key is either a corpus column or the explicitly named raw
|
|
426
|
+
payload, so no fetched value is silently discarded downstream.
|
|
427
|
+
|
|
428
|
+
Parameters
|
|
429
|
+
----------
|
|
430
|
+
message : Mapping[str, Any]
|
|
431
|
+
Crossref work message.
|
|
432
|
+
doi : str, default=''
|
|
433
|
+
DOI used when the message does not carry one.
|
|
434
|
+
|
|
435
|
+
Returns
|
|
436
|
+
-------
|
|
437
|
+
dict[str, Any]
|
|
438
|
+
Corpus metadata fields plus the raw ``crossref_message``.
|
|
439
|
+
"""
|
|
440
|
+
return {
|
|
441
|
+
'doi': message.get('DOI', doi),
|
|
442
|
+
'publication_date': _published_date(message),
|
|
443
|
+
'title': _normalize_metadata_text((message.get('title') or [''])[0]),
|
|
444
|
+
'journal': _normalize_metadata_text((message.get('container-title') or [''])[0]),
|
|
445
|
+
'publisher': _normalize_metadata_text(message.get('publisher', '')),
|
|
446
|
+
'work_type': str(message.get('type') or ''),
|
|
447
|
+
'volume': str(message.get('volume') or ''),
|
|
448
|
+
'issue': str(message.get('issue') or ''),
|
|
449
|
+
'pages': _crossref_pages(message),
|
|
450
|
+
'issn': _crossref_issn(message),
|
|
451
|
+
'language': str(message.get('language') or ''),
|
|
452
|
+
'crossref_message': dict(message),
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def get_crossref_metadata(doi: str, timeout: int = 30, email: str | None = None) -> dict[str, Any]:
|
|
457
|
+
"""Fetch normalized paper metadata from Crossref.
|
|
458
|
+
|
|
459
|
+
The contact address is sent both as the ``mailto`` query parameter and in
|
|
460
|
+
the user agent, which is what Crossref asks automated clients to do.
|
|
461
|
+
|
|
462
|
+
Parameters
|
|
463
|
+
----------
|
|
464
|
+
doi : str
|
|
465
|
+
DOI to look up.
|
|
466
|
+
timeout : int, default=30
|
|
467
|
+
HTTP request timeout in seconds.
|
|
468
|
+
email : str or None, optional
|
|
469
|
+
Contact email. Defaults to the stored ``crossref_email`` setting.
|
|
470
|
+
|
|
471
|
+
Returns
|
|
472
|
+
-------
|
|
473
|
+
dict[str, Any]
|
|
474
|
+
Corpus metadata columns plus the raw ``crossref_message`` payload.
|
|
475
|
+
|
|
476
|
+
Raises
|
|
477
|
+
------
|
|
478
|
+
ValueError
|
|
479
|
+
If no contact email is available.
|
|
480
|
+
RuntimeError
|
|
481
|
+
If the Crossref request exhausts its retries.
|
|
482
|
+
"""
|
|
483
|
+
from paperminertoolkit.providers.crossref import work_by_doi
|
|
484
|
+
|
|
485
|
+
work = work_by_doi(doi, email=email or None, timeout=timeout)
|
|
486
|
+
return crossref_fields(work or {}, doi)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def metadata_from_pdf(
|
|
490
|
+
pdf_path: str | PathLike[str],
|
|
491
|
+
use_crossref: bool = True,
|
|
492
|
+
) -> tuple[dict[str, Any], Literal['imported', 'doi_found', 'enriched'], str]:
|
|
493
|
+
"""Extract and optionally enrich DOI metadata from a PDF.
|
|
494
|
+
|
|
495
|
+
Parameters
|
|
496
|
+
----------
|
|
497
|
+
pdf_path : str or os.PathLike[str]
|
|
498
|
+
Path to the PDF file.
|
|
499
|
+
use_crossref : bool, default=True
|
|
500
|
+
Whether to validate candidates and fetch bibliographic metadata from
|
|
501
|
+
Crossref.
|
|
502
|
+
|
|
503
|
+
Returns
|
|
504
|
+
-------
|
|
505
|
+
metadata : dict[str, Any]
|
|
506
|
+
Extracted metadata, empty when the PDF cannot be read or has no DOI.
|
|
507
|
+
status : {'imported', 'doi_found', 'enriched'}
|
|
508
|
+
Furthest successful metadata stage.
|
|
509
|
+
error : str
|
|
510
|
+
Human-readable failure details, or an empty string after success.
|
|
511
|
+
"""
|
|
512
|
+
try:
|
|
513
|
+
doi_candidates = doi_candidates_from_pdf(pdf_path)
|
|
514
|
+
except Exception as e:
|
|
515
|
+
return {}, 'imported', f'Could not read PDF metadata text: {e}'
|
|
516
|
+
if not doi_candidates:
|
|
517
|
+
return {}, 'imported', 'No DOI found in PDF metadata or text.'
|
|
518
|
+
doi = doi_candidates[0]
|
|
519
|
+
metadata = {'doi': doi}
|
|
520
|
+
if not use_crossref:
|
|
521
|
+
return metadata, 'doi_found', ''
|
|
522
|
+
last_error = None
|
|
523
|
+
for candidate in doi_candidates:
|
|
524
|
+
try:
|
|
525
|
+
enriched = get_crossref_metadata(candidate)
|
|
526
|
+
except requests.RequestException as e:
|
|
527
|
+
last_error = e
|
|
528
|
+
continue
|
|
529
|
+
metadata = {'doi': candidate}
|
|
530
|
+
metadata.update(enriched)
|
|
531
|
+
return metadata, 'enriched', ''
|
|
532
|
+
return metadata, 'doi_found', f'Crossref lookup failed for DOI candidates {", ".join(doi_candidates)}: {last_error}'
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Recipe-driven language and vision model extraction tools."""
|