refactor(files): share document extraction and stream cleanup

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent c11c1a376f
commit 63209dab1d
4 files changed
+63 -86

No files matched your search

+5 -9
View File
@@ -466,7 +466,7 @@ class ReadFileTool(_FsTool):
return result return result
def _read_pdf(self, source: ReadableFile, pages: str | None) -> str: def _read_pdf(self, source: ReadableFile, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError from nanobot.utils.document import PdfPageRangeError
try: try:
extraction = source.pdf_pages( extraction = source.pdf_pages(
@@ -476,8 +476,6 @@ class ReadFileTool(_FsTool):
) )
except PdfPageRangeError as e: except PdfPageRangeError as e:
return ToolResult.error(f"Error: Invalid page range '{pages}': {e!s}.") return ToolResult.error(f"Error: Invalid page range '{pages}': {e!s}.")
except PdfSafetyError as e:
return ToolResult.error(f"Error reading PDF: {e}")
except Exception as e: except Exception as e:
return ToolResult.error(f"Error reading PDF: {e}") return ToolResult.error(f"Error reading PDF: {e}")
@@ -508,12 +506,11 @@ class ReadFileTool(_FsTool):
fp = file.path fp = file.path
offset = max(1, offset) offset = max(1, offset)
requested_limit = limit or self._DEFAULT_LIMIT requested_limit = limit or self._DEFAULT_LIMIT
source_iterator = None source = None
try: try:
source = file.document_lines() source = file.document_lines()
if source is None: if source is None:
return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}") return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}")
source_iterator = source.lines
numbered: list[str] = [] numbered: list[str] = []
output_chars = 0 output_chars = 0
total_seen = 0 total_seen = 0
@@ -521,7 +518,7 @@ class ReadFileTool(_FsTool):
has_more = False has_more = False
line_was_clipped = False line_was_clipped = False
for line in source_iterator: for line in source.lines:
total_seen = line.extracted_line total_seen = line.extracted_line
if line.extracted_line < offset: if line.extracted_line < offset:
continue continue
@@ -574,9 +571,8 @@ class ReadFileTool(_FsTool):
except Exception as e: except Exception as e:
return ToolResult.error(f"Error reading {fp.suffix.upper()} file: {e!s}") return ToolResult.error(f"Error reading {fp.suffix.upper()} file: {e!s}")
finally: finally:
close = getattr(source_iterator, "close", None) if source is not None:
if close is not None: source.close()
close()
@tool_parameters( @tool_parameters(
+4 -6
View File
@@ -783,7 +783,7 @@ class GrepTool(_SearchTool):
with suppress(ValueError): with suppress(ValueError):
display_path = file_path.relative_to(workspace).as_posix() display_path = file_path.relative_to(workspace).as_posix()
source_iterator: Iterator[LocatedDocumentLine] | None = None source: DocumentLineSource | None = None
is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
file_matches = 0 file_matches = 0
try: try:
@@ -811,12 +811,11 @@ class GrepTool(_SearchTool):
if source is None: if source is None:
skipped_binary += 1 skipped_binary += 1
continue continue
source_iterator = source.lines
if source.continuation and len(document_continuations) < 10: if source.continuation and len(document_continuations) < 10:
document_continuations.append( document_continuations.append(
f"({display_path}: continue PDF search with {source.continuation})" f"({display_path}: continue PDF search with {source.continuation})"
) )
source_lines = checked_lines(source_iterator) source_lines = checked_lines(source.lines)
if output_mode == "content": if output_mode == "content":
content_page.scan(display_path, source_lines, regex, context_before, context_after) content_page.scan(display_path, source_lines, regex, context_before, context_after)
@@ -845,9 +844,8 @@ class GrepTool(_SearchTool):
document_error = f"{display_path}: {e!s}" document_error = f"{display_path}: {e!s}"
continue continue
finally: finally:
close = getattr(source_iterator, "close", None) if source is not None:
if close is not None: source.close()
close()
# A document can fail after yielding matches. Keep the count # A document can fail after yielding matches. Keep the count
# of those lines even though the failed file is not ranked. # of those lines even though the failed file is not ranked.
if file_matches and output_mode == "count": if file_matches and output_mode == "count":
+42 -68
View File
@@ -3,13 +3,16 @@ import mimetypes
from collections.abc import Iterator from collections.abc import Iterator
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any from typing import TYPE_CHECKING, Any
from zipfile import BadZipFile, ZipFile from zipfile import BadZipFile, ZipFile
from loguru import logger from loguru import logger
from nanobot.utils.helpers import detect_image_mime from nanobot.utils.helpers import detect_image_mime
if TYPE_CHECKING:
from pypdf import PdfReader
_MAX_TEXT_LENGTH = 200_000 _MAX_TEXT_LENGTH = 200_000
_MAX_EXTRACT_FILE_SIZE = 50 * 1024 * 1024 _MAX_EXTRACT_FILE_SIZE = 50 * 1024 * 1024
_MAX_OFFICE_ARCHIVE_MEMBERS = 10_000 _MAX_OFFICE_ARCHIVE_MEMBERS = 10_000
@@ -97,6 +100,11 @@ class DocumentLineSource:
lines: Iterator[LocatedDocumentLine] lines: Iterator[LocatedDocumentLine]
continuation: str | None = None continuation: str | None = None
def close(self) -> None:
close = getattr(self.lines, "close", None)
if close is not None:
close()
def extract_text(path: str | Path) -> str | None: def extract_text(path: str | Path) -> str | None:
"""Extract text from a file. """Extract text from a file.
@@ -118,12 +126,8 @@ def extract_text(path: str | Path) -> str | None:
# retain their import cost (see issue #3422). # retain their import cost (see issue #3422).
if ext == ".pdf": if ext == ".pdf":
return _extract_pdf(path) return _extract_pdf(path)
elif ext == ".docx": elif ext in _OFFICE_LINE_READERS:
return _extract_docx(path) return _extract_office(path, ext)
elif ext == ".xlsx":
return _extract_xlsx(path)
elif ext == ".pptx":
return _extract_pptx(path)
elif _is_text_extension(ext): elif _is_text_extension(ext):
return _extract_text_file(path) return _extract_text_file(path)
elif ext in {".png", ".jpg", ".jpeg", ".gif", ".webp"}: elif ext in {".png", ".jpg", ".jpeg", ".gif", ".webp"}:
@@ -149,17 +153,13 @@ def open_document_line_source(
# Format can come from a displayed name; all I/O uses the supplied path. # Format can come from a displayed name; all I/O uses the supplied path.
path = Path(path) path = Path(path)
ext = (path.suffix if suffix is None else suffix).lower() ext = (path.suffix if suffix is None else suffix).lower()
if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}: if ext != ".pdf" and ext not in _OFFICE_LINE_READERS:
return None return None
if error := _extraction_path_error(path): if error := _extraction_path_error(path):
raise DocumentExtractionError(_clean_extraction_error(error)) raise DocumentExtractionError(_clean_extraction_error(error))
if ext == ".pdf": if ext == ".pdf":
return _open_pdf_line_source(path, pages) return _open_pdf_line_source(path, pages)
if ext == ".docx": return _OFFICE_LINE_READERS[ext](path)
return _open_docx_line_source(path)
if ext == ".xlsx":
return _open_xlsx_line_source(path)
return _open_pptx_line_source(path)
def _clean_extraction_error(error: str) -> str: def _clean_extraction_error(error: str) -> str:
@@ -173,6 +173,19 @@ def _check_office_archive(path: Path) -> None:
raise DocumentExtractionError(_clean_extraction_error(error)) raise DocumentExtractionError(_clean_extraction_error(error))
def _iter_pdf_page_text(reader: "PdfReader", start: int, end: int) -> Iterator[tuple[int, str]]:
for index in range(start, end + 1):
page = reader.pages[index]
contents = page.get_contents()
if contents is not None and len(contents.get_data()) > _MAX_PDF_CONTENT_STREAM_SIZE:
raise PdfSafetyError(
f"page {index + 1} content stream exceeds "
f"{_MAX_PDF_CONTENT_STREAM_SIZE // (1024 * 1024)} MB limit"
)
if text := (page.extract_text() or "").strip():
yield index, text
def _open_pdf_line_source(path: Path, pages: str | None) -> DocumentLineSource: def _open_pdf_line_source(path: Path, pages: str | None) -> DocumentLineSource:
try: try:
from pypdf import PdfReader from pypdf import PdfReader
@@ -197,19 +210,7 @@ def _open_pdf_line_source(path: Path, pages: str | None) -> DocumentLineSource:
def iter_lines() -> Iterator[LocatedDocumentLine]: def iter_lines() -> Iterator[LocatedDocumentLine]:
extracted_line = 0 extracted_line = 0
wrote_page = False wrote_page = False
for index in range(start, end + 1): for index, text in _iter_pdf_page_text(reader, start, end):
page = reader.pages[index]
contents = page.get_contents()
if contents is not None:
stream_size = len(contents.get_data())
if stream_size > _MAX_PDF_CONTENT_STREAM_SIZE:
raise PdfSafetyError(
f"page {index + 1} content stream exceeds "
f"{_MAX_PDF_CONTENT_STREAM_SIZE // (1024 * 1024)} MB limit"
)
text = (page.extract_text() or "").strip()
if not text:
continue
if wrote_page: if wrote_page:
extracted_line += 1 extracted_line += 1
yield LocatedDocumentLine("", extracted_line, "", searchable=False) yield LocatedDocumentLine("", extracted_line, "", searchable=False)
@@ -473,19 +474,7 @@ def extract_pdf_pages(
start, end = _parse_pdf_page_range(pages, total_pages) start, end = _parse_pdf_page_range(pages, total_pages)
end = min(end, start + max_pages - 1) end = min(end, start + max_pages - 1)
collector = _TextCollector(max_chars) collector = _TextCollector(max_chars)
for index in range(start, end + 1): for index, text in _iter_pdf_page_text(reader, start, end):
page = reader.pages[index]
contents = page.get_contents()
if contents is not None:
stream_size = len(contents.get_data())
if stream_size > _MAX_PDF_CONTENT_STREAM_SIZE:
raise PdfSafetyError(
f"page {index + 1} content stream exceeds "
f"{_MAX_PDF_CONTENT_STREAM_SIZE // (1024 * 1024)} MB limit"
)
text = (page.extract_text() or "").strip()
if not text:
continue
page_text = f"--- Page {index + 1} ---\n{text}" page_text = f"--- Page {index + 1} ---\n{text}"
if collector.parts and collector.length + 2 + len(page_text) > max_chars: if collector.parts and collector.length + 2 + len(page_text) > max_chars:
# Leave this page for the next read instead of returning only its prefix. # Leave this page for the next read instead of returning only its prefix.
@@ -520,10 +509,9 @@ def _parse_pdf_page_range(pages: str | None, total_pages: int) -> tuple[int, int
def _render_document_preview(source: DocumentLineSource) -> str: def _render_document_preview(source: DocumentLineSource) -> str:
collector = _TextCollector(_MAX_TEXT_LENGTH) collector = _TextCollector(_MAX_TEXT_LENGTH)
iterator = source.lines
first_line = True first_line = True
try: try:
for line in iterator: for line in source.lines:
if not first_line and not collector.add("\n"): if not first_line and not collector.add("\n"):
break break
first_line = False first_line = False
@@ -531,41 +519,27 @@ def _render_document_preview(source: DocumentLineSource) -> str:
break break
return collector.render() return collector.render()
finally: finally:
close = getattr(iterator, "close", None) source.close()
if close is not None:
close()
def _extract_docx(path: Path) -> str: _OFFICE_LINE_READERS = {
".docx": _open_docx_line_source,
".xlsx": _open_xlsx_line_source,
".pptx": _open_pptx_line_source,
}
def _extract_office(path: Path, suffix: str) -> str:
try: try:
return _render_document_preview(_open_docx_line_source(path)) return _render_document_preview(_OFFICE_LINE_READERS[suffix](path))
except DocxSafetyError as e: except DocxSafetyError as e:
return f"[error: unsafe DOCX: {e!s}]" return f"[error: unsafe DOCX: {e!s}]"
except DocumentExtractionError as e: except DocumentExtractionError as e:
return f"[error: {e!s}]" return f"[error: {e!s}]"
except Exception as e: except Exception as e:
logger.exception("Failed to extract DOCX {}", path) format_name = suffix[1:].upper()
return f"[error: failed to extract DOCX: {e!s}]" logger.exception("Failed to extract {} {}", format_name, path)
return f"[error: failed to extract {format_name}: {e!s}]"
def _extract_xlsx(path: Path) -> str:
try:
return _render_document_preview(_open_xlsx_line_source(path))
except DocumentExtractionError as e:
return f"[error: {e!s}]"
except Exception as e:
logger.exception("Failed to extract XLSX {}", path)
return f"[error: failed to extract XLSX: {e!s}]"
def _extract_pptx(path: Path) -> str:
try:
return _render_document_preview(_open_pptx_line_source(path))
except DocumentExtractionError as e:
return f"[error: {e!s}]"
except Exception as e:
logger.exception("Failed to extract PPTX {}", path)
return f"[error: failed to extract PPTX: {e!s}]"
def _collect_pptx_shape_text(shape: Any, out: list[str]) -> None: def _collect_pptx_shape_text(shape: Any, out: list[str]) -> None:
+12 -3
View File
@@ -483,7 +483,8 @@ class TestExtractText:
assert "truncated at 80 chars" in result assert "truncated at 80 chars" in result
assert visited < 100 assert visited < 100
def test_extract_pdf_pages_rejects_large_content_stream(self, tmp_path, monkeypatch): @pytest.mark.parametrize("streaming", [False, True], ids=["preview", "line-source"])
def test_pdf_rejects_large_content_stream(self, tmp_path, monkeypatch, streaming):
class _Contents: class _Contents:
@staticmethod @staticmethod
def get_data(): def get_data():
@@ -505,8 +506,16 @@ class TestExtractText:
monkeypatch.setattr("pypdf.PdfReader", _Reader) monkeypatch.setattr("pypdf.PdfReader", _Reader)
monkeypatch.setattr("nanobot.utils.document._MAX_PDF_CONTENT_STREAM_SIZE", 16) monkeypatch.setattr("nanobot.utils.document._MAX_PDF_CONTENT_STREAM_SIZE", 16)
with pytest.raises(PdfSafetyError, match="content stream exceeds"): path = tmp_path / "large.pdf"
extract_pdf_pages(tmp_path / "large.pdf") path.touch()
if streaming:
source = open_document_line_source(path)
assert source is not None
with pytest.raises(PdfSafetyError, match="content stream exceeds"):
list(source.lines)
else:
with pytest.raises(PdfSafetyError, match="content stream exceeds"):
extract_pdf_pages(path)
def test_extract_text_pdf_not_found(self, tmp_path: Path): def test_extract_text_pdf_not_found(self, tmp_path: Path):
missing_pdf = tmp_path / "nonexistent.pdf" missing_pdf = tmp_path / "nonexistent.pdf"