Skip to content

Commit 46dd616

Browse files
authored
Merge pull request #158 from linkml/ccr-65a5480d-pb91sk
Let DOI, JSON API and PDF sources degrade instead of raising on bad data
2 parents 817b6b0 + 4cec013 commit 46dd616

13 files changed

Lines changed: 502 additions & 67 deletions

‎src/linkml_reference_validator/etl/extract/pdf.py‎

Lines changed: 76 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,28 @@
1414
logger = logging.getLogger(__name__)
1515

1616

17+
class UnreadablePDFError(ValueError):
18+
"""The bytes are not a PDF a backend can read: truncated, corrupt or empty."""
19+
20+
1721
class PDFTextBackend(Protocol):
18-
"""Protocol for a PDF-to-text backend."""
22+
"""Protocol for a PDF-to-text backend.
23+
24+
PDF bytes come from the network, so they may be truncated or corrupt. A
25+
backend raises :class:`UnreadablePDFError` for those, whatever its parser
26+
raises, and never returns a title it could not read.
27+
"""
1928

2029
def extract_text(self, data: bytes) -> str:
21-
"""Return extracted plain text for the given PDF bytes."""
30+
"""Return extracted plain text for the given PDF bytes.
31+
32+
Raises:
33+
UnreadablePDFError: The bytes cannot be read as a PDF.
34+
"""
2235
...
2336

2437
def extract_title(self, data: bytes) -> Optional[str]:
25-
"""Return the embedded document title, or None if there is none."""
38+
"""Return the embedded document title, or None if there is none or it cannot be read."""
2639
...
2740

2841

@@ -35,10 +48,26 @@ class PypdfBackend:
3548
"""
3649

3750
def extract_text(self, data: bytes) -> str:
51+
"""Extract the text of every page.
52+
53+
Examples:
54+
>>> try:
55+
... PypdfBackend().extract_text(b"%PDF-1.7 truncated")
56+
... except UnreadablePDFError:
57+
... print("unreadable")
58+
unreadable
59+
"""
3860
from pypdf import PdfReader
3961

40-
reader = PdfReader(io.BytesIO(data))
41-
return "\n\n".join(page.extract_text() or "" for page in reader.pages)
62+
# External data. Damaged input raises PyPdfError, but also KeyError,
63+
# AttributeError, ValueError, TypeError or IndexError from deep inside
64+
# the parser (seen on a fuzzed corpus, pinned in the tests), so every
65+
# failure is caught here, as the fetcher's full-text path does (#122).
66+
try:
67+
reader = PdfReader(io.BytesIO(data))
68+
return "\n\n".join(page.extract_text() or "" for page in reader.pages)
69+
except Exception as e:
70+
raise UnreadablePDFError(f"{type(e).__name__}: {e}") from e
4271

4372
def extract_title(self, data: bytes) -> Optional[str]:
4473
"""Read ``/Title`` from the document information dictionary.
@@ -48,17 +77,16 @@ def extract_title(self, data: bytes) -> Optional[str]:
4877
True
4978
"""
5079
from pypdf import PdfReader
51-
from pypdf.errors import PyPdfError
5280

53-
try: # external data: a PDF can carry text yet have a broken trailer
81+
# External data: a PDF can carry text yet have a broken trailer, and,
82+
# as for the text, pypdf raises more than PyPdfError on damaged input.
83+
try:
5484
metadata = PdfReader(io.BytesIO(data)).metadata
55-
except PyPdfError as e:
56-
logger.debug(f"Could not read PDF metadata: {e}")
57-
return None
58-
if metadata is None:
85+
title = metadata.title if metadata is not None else None
86+
except Exception as e:
87+
logger.debug(f"Could not read PDF metadata: {type(e).__name__}: {e}")
5988
return None
6089
# pypdf returns /Title as whatever object it holds; only text is a title.
61-
title = metadata.title
6290
return str(title) if isinstance(title, str) else None
6391

6492

@@ -144,7 +172,42 @@ def extract(
144172
content_type: Optional[str] = None,
145173
source: Optional[str] = None,
146174
) -> Optional[str]:
147-
"""Extract text from PDF bytes; ``source`` (e.g. a URL) names it in logs."""
175+
"""Extract text from PDF bytes; ``source`` (e.g. a URL) names it in logs.
176+
177+
Returns None for a PDF with no text, and, with a warning, for bytes
178+
that cannot be read as one (a truncated download, a corrupt or empty
179+
file), so a generic :class:`Extractor` caller sees no text either way
180+
(#122). A caller that must tell those two apart, such as one that
181+
retries a damaged download, uses :meth:`read_text`.
182+
183+
Examples:
184+
>>> PDFExtractor().extract(b"%PDF-1.7 truncated") is None
185+
True
186+
"""
187+
try:
188+
return self.read_text(data, source=source)
189+
except UnreadablePDFError as e:
190+
origin = f" from {source}" if source else ""
191+
logger.warning(f"Could not read PDF{origin}: {e}")
192+
return None
193+
194+
def read_text(self, data: Union[bytes, str], *, source: Optional[str] = None) -> Optional[str]:
195+
"""Like :meth:`extract`, but raise for bytes that cannot be read as a PDF.
196+
197+
The full-text chain treats an unreadable download as a transient error
198+
worth retrying, not as "this article has no text", so it needs the
199+
difference.
200+
201+
Raises:
202+
UnreadablePDFError: The bytes cannot be read as a PDF.
203+
204+
Examples:
205+
>>> try:
206+
... PDFExtractor().read_text(b"")
207+
... except UnreadablePDFError:
208+
... print("unreadable")
209+
unreadable
210+
"""
148211
# The base accepts str for text formats, but a PDF is binary: decoded
149212
# text cannot be reparsed as one, so say so rather than failing deep
150213
# inside the backend.

‎src/linkml_reference_validator/etl/reference_fetcher.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,9 +1161,9 @@ def _materialize(
11611161
elif fmt == "pdf":
11621162
# Deliberately not extractor.extract(...): only the PDF extractor
11631163
# takes source=, which names the URL when it warns about lost glyphs.
1164-
text = self._pdf_extractor.extract(
1165-
data, content_type=content_type, source=location.url
1166-
)
1164+
# read_text raises for an unreadable download, so it is flagged
1165+
# below as a transient error and retried on a later run.
1166+
text = self._pdf_extractor.read_text(data, source=location.url)
11671167
else:
11681168
text = extractor.extract(data, content_type=content_type)
11691169
except Exception as exc:

‎src/linkml_reference_validator/etl/sources/doi.py‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from typing import Optional
1717

1818
from bs4 import BeautifulSoup # type: ignore
19-
import requests # type: ignore
2019

2120
from linkml_reference_validator.models import (
2221
ReferenceContent,
@@ -28,6 +27,7 @@
2827
from linkml_reference_validator.etl.sources.utils import (
2928
extract_extra_fields,
3029
format_extra_fields_for_content,
30+
get_json,
3131
)
3232

3333
logger = logging.getLogger(__name__)
@@ -106,17 +106,16 @@ def _fetch_from_crossref(
106106
"User-Agent": f"linkml-reference-validator/1.0 (mailto:{config.email})",
107107
}
108108

109-
response = requests.get(url, headers=headers, timeout=30)
110-
if response.status_code != 200:
111-
logger.debug(f"Crossref returned {response.status_code} for DOI:{doi}, will try DataCite")
112-
return None
113-
114-
data = response.json()
115-
if data.get("status") != "ok":
109+
# DEBUG: DataCite is tried next, and a miss there is a warning.
110+
data = get_json(url, f"DOI:{doi} from Crossref", headers, level=logging.DEBUG)
111+
if not isinstance(data, dict) or data.get("status") != "ok":
116112
logger.debug(f"Crossref API error for DOI:{doi}, will try DataCite")
117113
return None
118114

119-
message = data.get("message", {})
115+
message = data.get("message")
116+
if not isinstance(message, dict):
117+
logger.debug(f"Crossref returned no record for DOI:{doi}, will try DataCite")
118+
return None
120119

121120
title_list = message.get("title", [])
122121
title = title_list[0] if title_list else ""
@@ -209,13 +208,18 @@ def _fetch_from_datacite(
209208
"Accept": "application/json",
210209
}
211210

212-
response = requests.get(url, headers=headers, timeout=30)
213-
if response.status_code != 200:
211+
# DEBUG: the reason; the one warning is the miss from both, below.
212+
data = get_json(url, f"DOI:{doi} from DataCite", headers, level=logging.DEBUG)
213+
if not isinstance(data, dict):
214214
logger.warning(f"Failed to fetch DOI:{doi} from both Crossref and DataCite")
215215
return None
216216

217-
data = response.json()
218-
attributes = data.get("data", {}).get("attributes", {})
217+
record = data.get("data")
218+
attributes = record.get("attributes") if isinstance(record, dict) else None
219+
if not isinstance(attributes, dict):
220+
logger.debug(f"DataCite returned no data.attributes for DOI:{doi}")
221+
logger.warning(f"Failed to fetch DOI:{doi} from both Crossref and DataCite")
222+
return None
219223

220224
# Extract title
221225
titles = attributes.get("titles", [])
@@ -347,12 +351,13 @@ def _fetch_zenodo_files(
347351
"Accept": "application/json",
348352
}
349353

350-
response = requests.get(url, headers=headers, timeout=30)
351-
if response.status_code != 200:
352-
logger.debug(f"Failed to fetch Zenodo files for record {record_id}")
354+
# DEBUG: the file list is enrichment; the record is kept without it.
355+
data = get_json(
356+
url, f"Zenodo files for record {record_id}", headers, level=logging.DEBUG
357+
)
358+
if not isinstance(data, dict):
353359
return None
354360

355-
data = response.json()
356361
files_data = data.get("files", [])
357362

358363
if not files_data:

‎src/linkml_reference_validator/etl/sources/json_api.py‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@
2525
import time
2626
from typing import Optional
2727

28-
import requests
2928
from jsonpath_ng import parse as jsonpath_parse
3029
from jsonpath_ng.exceptions import JsonPathParserError
3130

3231
from linkml_reference_validator.etl.sources.base import (
3332
ReferenceSource,
3433
ReferenceSourceRegistry,
3534
)
35+
from linkml_reference_validator.etl.sources.utils import get_json
3636
from linkml_reference_validator.models import (
3737
JSONAPISourceConfig,
3838
ReferenceContent,
@@ -175,15 +175,10 @@ def fetch(
175175
if "Accept" not in headers:
176176
headers["Accept"] = "application/json"
177177

178-
response = requests.get(url, headers=headers, timeout=30)
179-
if response.status_code != 200:
180-
logger.warning(
181-
f"Failed to fetch {self._prefix}:{identifier} - status {response.status_code}"
182-
)
178+
data = get_json(url, f"{self._prefix}:{identifier}", headers)
179+
if data is None:
183180
return None
184181

185-
data = response.json()
186-
187182
# Extract fields using JSONPath
188183
extracted = self._extract_fields(data)
189184

‎src/linkml_reference_validator/etl/sources/url.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from linkml_reference_validator.etl.sources.base import ReferenceSource, ReferenceSourceRegistry
2222
from linkml_reference_validator.etl.acquire import ContentAcquirer, sniff_format
2323
from linkml_reference_validator.etl.extract.html import html_to_text
24-
from linkml_reference_validator.etl.extract.pdf import PDFExtractor
24+
from linkml_reference_validator.etl.extract.pdf import PDFExtractor, UnreadablePDFError
2525
from linkml_reference_validator.etl.rules import (
2626
LANDING_PAGE_RULES,
2727
is_bot_challenge_title,
@@ -101,9 +101,15 @@ def fetch(
101101
is_pdf = data[:5] == b"%PDF-" or "application/pdf" in content_type_header
102102

103103
if is_pdf:
104-
text = PDFExtractor(backend=config.pdf_backend).extract(
105-
data, content_type="application/pdf", source=url
106-
)
104+
try:
105+
text = PDFExtractor(backend=config.pdf_backend).read_text(data, source=url)
106+
except UnreadablePDFError as e:
107+
# A truncated download may be transient, so it is a failed fetch,
108+
# as for a bot-challenge page below: a cached copy is served,
109+
# nothing is written, and the next run downloads it again.
110+
# "unavailable" would be cached as a permanent absence (#122).
111+
logger.warning(f"Failed to fetch {url}: the PDF cannot be read ({e})")
112+
return None
107113
return ReferenceContent(
108114
reference_id=f"url:{url}",
109115
title=self._recover_pdf_title(url, data, config),

‎src/linkml_reference_validator/etl/sources/utils.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
"""
66

77
import logging
8+
from typing import Any, Optional
89

10+
import requests # type: ignore
911
from jsonpath_ng import parse as jsonpath_parse
1012
from jsonpath_ng.exceptions import JsonPathParserError
1113

@@ -104,3 +106,44 @@ def format_extra_fields_for_content(extra: dict[str, str]) -> str:
104106
if not extra:
105107
return ""
106108
return "\n\n".join(f"### {k}\n\n{v}" for k, v in extra.items())
109+
110+
111+
def get_json(
112+
url: str,
113+
label: str,
114+
headers: Optional[dict[str, str]] = None,
115+
level: int = logging.WARNING,
116+
) -> Optional[Any]:
117+
"""GET ``url`` and return its JSON body, or None if it cannot be had.
118+
119+
A network error, a timeout, a status other than 200, or a body that is not
120+
JSON (a maintenance page served on a 200) all give None, so the caller's
121+
"no result" path runs and the fetcher can fall back to a cached copy
122+
(#134). Each failure is logged at ``level``, naming ``label``.
123+
124+
Args:
125+
url: The URL to fetch.
126+
label: What is being fetched, such as ``"DOI:10.1/x from Crossref"``.
127+
headers: Request headers.
128+
level: Log level for a failure; DEBUG where another source is tried next.
129+
130+
Returns:
131+
The parsed JSON body, or None.
132+
133+
Examples:
134+
>>> get_json("not a url", "a test record") is None # no request is sent
135+
True
136+
"""
137+
try: # external system boundary: offline, DNS failure, timeout
138+
response = requests.get(url, headers=headers, timeout=30)
139+
except requests.RequestException as exc:
140+
logger.log(level, f"Failed to fetch {label}: {exc}")
141+
return None
142+
if response.status_code != 200:
143+
logger.log(level, f"Failed to fetch {label}: HTTP {response.status_code}")
144+
return None
145+
try: # external data: a 200 can still carry an HTML error page
146+
return response.json()
147+
except ValueError as exc:
148+
logger.log(level, f"Failed to fetch {label}: the response is not JSON ({exc})")
149+
return None

‎tests/test_doi_preprint.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def _crossref_response(message):
2626
return mock_response
2727

2828

29-
@patch("linkml_reference_validator.etl.sources.doi.requests.get")
29+
@patch("linkml_reference_validator.etl.sources.utils.requests.get")
3030
def test_posted_content_preprint_is_marked(mock_get, source, config):
3131
mock_get.return_value = _crossref_response(
3232
{
@@ -46,7 +46,7 @@ def test_posted_content_preprint_is_marked(mock_get, source, config):
4646
assert result.peer_review_status == "preprint"
4747

4848

49-
@patch("linkml_reference_validator.etl.sources.doi.requests.get")
49+
@patch("linkml_reference_validator.etl.sources.utils.requests.get")
5050
def test_posted_content_without_subtype_is_marked(mock_get, source, config):
5151
# Some posted-content records omit the explicit "preprint" subtype.
5252
mock_get.return_value = _crossref_response(
@@ -65,7 +65,7 @@ def test_posted_content_without_subtype_is_marked(mock_get, source, config):
6565
assert result.peer_review_status == "preprint"
6666

6767

68-
@patch("linkml_reference_validator.etl.sources.doi.requests.get")
68+
@patch("linkml_reference_validator.etl.sources.utils.requests.get")
6969
def test_journal_article_is_marked_not_preprint(mock_get, source, config):
7070
mock_get.return_value = _crossref_response(
7171
{
@@ -87,7 +87,7 @@ def test_journal_article_is_marked_not_preprint(mock_get, source, config):
8787
assert result.peer_review_status is None
8888

8989

90-
@patch("linkml_reference_validator.etl.sources.doi.requests.get")
90+
@patch("linkml_reference_validator.etl.sources.utils.requests.get")
9191
def test_typeless_crossref_record_leaves_preprint_unknown(mock_get, source, config):
9292
mock_get.return_value = _crossref_response(
9393
{

‎tests/test_doi_url_encoding.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def test_doi_url_path_keeps_the_slash_and_encodes_the_rest():
5050
def test_crossref_and_datacite_request_the_whole_doi(doi):
5151
config = ReferenceValidationConfig(rate_limit_delay=0)
5252
urls = _requested_urls(
53-
"linkml_reference_validator.etl.sources.doi", lambda: DOISource().fetch(doi, config)
53+
"linkml_reference_validator.etl.sources.utils", lambda: DOISource().fetch(doi, config)
5454
)
5555
assert [u.split("/")[2] for u in urls] == ["api.crossref.org", "api.datacite.org"]
5656
assert all(_keeps_whole_doi(u, doi) for u in urls)

‎tests/test_e2e_integration.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ def locate(self, ids, config):
404404
with patch.object(fetcher, "_load_from_disk", return_value=None), \
405405
patch("linkml_reference_validator.etl.reference_fetcher.ReferenceSourceRegistry.get_source") as mock_get_source, \
406406
patch.object(fetcher._acquirer, "fetch_bytes", return_value=(b"%PDF-bytes", "application/pdf")), \
407-
patch.object(fetcher._pdf_extractor, "extract", return_value="full text body " * 60):
407+
patch.object(fetcher._pdf_extractor, "read_text", return_value="full text body " * 60):
408408
mock_source_class = mock_get_source.return_value
409409
mock_source_class.return_value.fetch.return_value = metadata
410410

0 commit comments

Comments
 (0)