fix(detect): warn when a PDF cannot be read instead of returning "" silently (#4527)
extract_pdf_text wrapped the whole PdfReader loop in except Exception: return "", so a malformed or encrypted PDF looked exactly like a PDF with no text and dropped out of the graph with no trace. Keep returning "" (callers rely on it), but print a warning naming the file and the error first. Warn once per path, since detect() and the semantic pass both read the same file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a31f6d83f2
commit
bf3aac0e28
2 files changed
+91
-2
No files matched your search
+19
-2
@@ -557,10 +557,18 @@ def classify_file(path: Path) -> FileType | None:
|
||||
# Missing-pypdf is a process-global condition, not per-file, so warn at most
|
||||
# once per run — a corpus of many PDFs must not print the same hint N times.
|
||||
_pypdf_missing_warned = False
|
||||
# Unreadable PDFs are per-file, so warn once per path: detect() counts words and
|
||||
# the semantic pass reads the text again, and the same file must not warn twice.
|
||||
_pdf_failed_warned: set[str] = set()
|
||||
|
||||
|
||||
def extract_pdf_text(path: Path) -> str:
|
||||
"""Extract plain text from a PDF file using pypdf."""
|
||||
"""Extract plain text from a PDF file using pypdf.
|
||||
|
||||
Returns ``""`` when the file cannot be read (malformed, encrypted, ...), the
|
||||
same as for a PDF with no text, but warns on stderr naming the file and the
|
||||
error first (#4527), so a failed read is not mistaken for an empty document.
|
||||
"""
|
||||
if not _file_within_size_cap(path):
|
||||
return ""
|
||||
try:
|
||||
@@ -583,7 +591,16 @@ def extract_pdf_text(path: Path) -> str:
|
||||
if text:
|
||||
pages.append(text)
|
||||
return "\n".join(pages)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
key = str(path)
|
||||
if key not in _pdf_failed_warned:
|
||||
_pdf_failed_warned.add(key)
|
||||
print(
|
||||
f"[graphify] WARNING: could not extract text from {path} "
|
||||
f"({type(exc).__name__}: {exc}); it contributes no content to "
|
||||
"the graph.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
@@ -43,3 +43,75 @@ def test_extract_pdf_text_missing_pypdf_warns_once_across_many_pdfs(
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert captured.err.count("PDF text extraction skipped") == 1
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _reset_failed_warned(monkeypatch):
|
||||
monkeypatch.setattr(detect, "_pdf_failed_warned", set(), raising=False)
|
||||
|
||||
|
||||
def test_extract_pdf_text_unreadable_pdf_warns(tmp_path: Path, capsys, _reset_failed_warned):
|
||||
"""#4527: a PDF pypdf cannot read still returns "", but must say so on
|
||||
stderr instead of looking exactly like a PDF with no text."""
|
||||
pytest.importorskip("pypdf")
|
||||
pdf = tmp_path / "broken.pdf"
|
||||
pdf.write_bytes(b"this is not a pdf")
|
||||
|
||||
assert detect.extract_pdf_text(pdf) == ""
|
||||
|
||||
err = capsys.readouterr().err
|
||||
assert "could not extract text from" in err
|
||||
assert "broken.pdf" in err
|
||||
|
||||
|
||||
def test_extract_pdf_text_encrypted_pdf_warns(tmp_path: Path, capsys, _reset_failed_warned):
|
||||
"""An encrypted PDF opened without its password is a failed read, not an
|
||||
empty document (#4527)."""
|
||||
pypdf = pytest.importorskip("pypdf")
|
||||
writer = pypdf.PdfWriter()
|
||||
writer.add_blank_page(width=72, height=72)
|
||||
writer.encrypt(user_password="secret", algorithm="RC4-128")
|
||||
pdf = tmp_path / "locked.pdf"
|
||||
with pdf.open("wb") as fh:
|
||||
writer.write(fh)
|
||||
|
||||
assert detect.extract_pdf_text(pdf) == ""
|
||||
|
||||
err = capsys.readouterr().err
|
||||
assert "could not extract text from" in err
|
||||
assert "locked.pdf" in err
|
||||
|
||||
|
||||
def test_extract_pdf_text_unreadable_pdf_warns_once_per_file(
|
||||
tmp_path: Path, capsys, _reset_failed_warned
|
||||
):
|
||||
"""detect() and the semantic pass both read the same PDF; one bad file
|
||||
must warn once, while a second bad file still gets its own warning."""
|
||||
pytest.importorskip("pypdf")
|
||||
first = tmp_path / "a.pdf"
|
||||
second = tmp_path / "b.pdf"
|
||||
first.write_bytes(b"garbage")
|
||||
second.write_bytes(b"garbage")
|
||||
|
||||
for _ in range(3):
|
||||
assert detect.extract_pdf_text(first) == ""
|
||||
assert detect.extract_pdf_text(second) == ""
|
||||
|
||||
err = capsys.readouterr().err
|
||||
assert err.count("could not extract text from") == 2
|
||||
|
||||
|
||||
def test_extract_pdf_text_empty_but_valid_pdf_does_not_warn(
|
||||
tmp_path: Path, capsys, _reset_failed_warned
|
||||
):
|
||||
"""A readable PDF with no text layer is not a failure and stays silent."""
|
||||
pypdf = pytest.importorskip("pypdf")
|
||||
writer = pypdf.PdfWriter()
|
||||
writer.add_blank_page(width=72, height=72)
|
||||
pdf = tmp_path / "blank.pdf"
|
||||
with pdf.open("wb") as fh:
|
||||
writer.write(fh)
|
||||
|
||||
assert detect.extract_pdf_text(pdf) == ""
|
||||
|
||||
assert "could not extract text from" not in capsys.readouterr().err
|
||||
Reference in new issue
Block a user