1414logger = 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+
1721class 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.
0 commit comments