From 63209dab1d26e4cba0ae217fa68a0db77fdeb769 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:08:22 +0800 Subject: [PATCH] refactor(files): share document extraction and stream cleanup --- nanobot/agent/tools/filesystem.py | 14 ++-- nanobot/agent/tools/search.py | 10 ++- nanobot/utils/document.py | 110 ++++++++++++------------------ tests/test_document_parsing.py | 15 +++- 4 files changed, 63 insertions(+), 86 deletions(-) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index 8615fa6ca..13c785bcf 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -466,7 +466,7 @@ class ReadFileTool(_FsTool): return result def _read_pdf(self, source: ReadableFile, pages: str | None) -> str: - from nanobot.utils.document import PdfPageRangeError, PdfSafetyError + from nanobot.utils.document import PdfPageRangeError try: extraction = source.pdf_pages( @@ -476,8 +476,6 @@ class ReadFileTool(_FsTool): ) except PdfPageRangeError as e: 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: return ToolResult.error(f"Error reading PDF: {e}") @@ -508,12 +506,11 @@ class ReadFileTool(_FsTool): fp = file.path offset = max(1, offset) requested_limit = limit or self._DEFAULT_LIMIT - source_iterator = None + source = None try: source = file.document_lines() if source is None: return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}") - source_iterator = source.lines numbered: list[str] = [] output_chars = 0 total_seen = 0 @@ -521,7 +518,7 @@ class ReadFileTool(_FsTool): has_more = False line_was_clipped = False - for line in source_iterator: + for line in source.lines: total_seen = line.extracted_line if line.extracted_line < offset: continue @@ -574,9 +571,8 @@ class ReadFileTool(_FsTool): except Exception as e: return ToolResult.error(f"Error reading {fp.suffix.upper()} file: {e!s}") finally: - close = getattr(source_iterator, "close", None) - if close is not None: - close() + if source is not None: + source.close() @tool_parameters( diff --git a/nanobot/agent/tools/search.py b/nanobot/agent/tools/search.py index c772dfac9..04b86274d 100644 --- a/nanobot/agent/tools/search.py +++ b/nanobot/agent/tools/search.py @@ -783,7 +783,7 @@ class GrepTool(_SearchTool): with suppress(ValueError): 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 file_matches = 0 try: @@ -811,12 +811,11 @@ class GrepTool(_SearchTool): if source is None: skipped_binary += 1 continue - source_iterator = source.lines if source.continuation and len(document_continuations) < 10: document_continuations.append( 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": 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}" continue finally: - close = getattr(source_iterator, "close", None) - if close is not None: - close() + if source is not None: + source.close() # A document can fail after yielding matches. Keep the count # of those lines even though the failed file is not ranked. if file_matches and output_mode == "count": diff --git a/nanobot/utils/document.py b/nanobot/utils/document.py index 3d5ea09d1..bfdd6b692 100644 --- a/nanobot/utils/document.py +++ b/nanobot/utils/document.py @@ -3,13 +3,16 @@ import mimetypes from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from zipfile import BadZipFile, ZipFile from loguru import logger from nanobot.utils.helpers import detect_image_mime +if TYPE_CHECKING: + from pypdf import PdfReader + _MAX_TEXT_LENGTH = 200_000 _MAX_EXTRACT_FILE_SIZE = 50 * 1024 * 1024 _MAX_OFFICE_ARCHIVE_MEMBERS = 10_000 @@ -97,6 +100,11 @@ class DocumentLineSource: lines: Iterator[LocatedDocumentLine] 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: """Extract text from a file. @@ -118,12 +126,8 @@ def extract_text(path: str | Path) -> str | None: # retain their import cost (see issue #3422). if ext == ".pdf": return _extract_pdf(path) - elif ext == ".docx": - return _extract_docx(path) - elif ext == ".xlsx": - return _extract_xlsx(path) - elif ext == ".pptx": - return _extract_pptx(path) + elif ext in _OFFICE_LINE_READERS: + return _extract_office(path, ext) elif _is_text_extension(ext): return _extract_text_file(path) 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. path = Path(path) 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 if error := _extraction_path_error(path): raise DocumentExtractionError(_clean_extraction_error(error)) if ext == ".pdf": return _open_pdf_line_source(path, pages) - if ext == ".docx": - return _open_docx_line_source(path) - if ext == ".xlsx": - return _open_xlsx_line_source(path) - return _open_pptx_line_source(path) + return _OFFICE_LINE_READERS[ext](path) def _clean_extraction_error(error: str) -> str: @@ -173,6 +173,19 @@ def _check_office_archive(path: Path) -> None: 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: try: from pypdf import PdfReader @@ -197,19 +210,7 @@ def _open_pdf_line_source(path: Path, pages: str | None) -> DocumentLineSource: def iter_lines() -> Iterator[LocatedDocumentLine]: extracted_line = 0 wrote_page = False - for index in range(start, end + 1): - 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 + for index, text in _iter_pdf_page_text(reader, start, end): if wrote_page: extracted_line += 1 yield LocatedDocumentLine("", extracted_line, "", searchable=False) @@ -473,19 +474,7 @@ def extract_pdf_pages( start, end = _parse_pdf_page_range(pages, total_pages) end = min(end, start + max_pages - 1) collector = _TextCollector(max_chars) - for index in range(start, end + 1): - 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 + for index, text in _iter_pdf_page_text(reader, start, end): page_text = f"--- Page {index + 1} ---\n{text}" 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. @@ -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: collector = _TextCollector(_MAX_TEXT_LENGTH) - iterator = source.lines first_line = True try: - for line in iterator: + for line in source.lines: if not first_line and not collector.add("\n"): break first_line = False @@ -531,41 +519,27 @@ def _render_document_preview(source: DocumentLineSource) -> str: break return collector.render() finally: - close = getattr(iterator, "close", None) - if close is not None: - close() + source.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: - return _render_document_preview(_open_docx_line_source(path)) + return _render_document_preview(_OFFICE_LINE_READERS[suffix](path)) except DocxSafetyError as e: return f"[error: unsafe DOCX: {e!s}]" except DocumentExtractionError as e: return f"[error: {e!s}]" except Exception as e: - logger.exception("Failed to extract DOCX {}", path) - return f"[error: failed to extract DOCX: {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}]" + format_name = suffix[1:].upper() + logger.exception("Failed to extract {} {}", format_name, path) + return f"[error: failed to extract {format_name}: {e!s}]" def _collect_pptx_shape_text(shape: Any, out: list[str]) -> None: diff --git a/tests/test_document_parsing.py b/tests/test_document_parsing.py index 1805b59dd..4042586d3 100644 --- a/tests/test_document_parsing.py +++ b/tests/test_document_parsing.py @@ -483,7 +483,8 @@ class TestExtractText: assert "truncated at 80 chars" in result 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: @staticmethod def get_data(): @@ -505,8 +506,16 @@ class TestExtractText: monkeypatch.setattr("pypdf.PdfReader", _Reader) monkeypatch.setattr("nanobot.utils.document._MAX_PDF_CONTENT_STREAM_SIZE", 16) - with pytest.raises(PdfSafetyError, match="content stream exceeds"): - extract_pdf_pages(tmp_path / "large.pdf") + path = 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): missing_pdf = tmp_path / "nonexistent.pdf"