datawhalechina/hello-agents · error · ImportError

请安装 PyPDF2: pip install PyPDF2

Error message

请安装 PyPDF2: pip install PyPDF2

What it means

Lazy-import guard in the PDF tool: `from PyPDF2 import PdfReader` inside `_extract_raw_text` raises ImportError('Please install PyPDF2: pip install PyPDF2') when the PyPDF2 package is absent from the active environment. The tool defers the dependency so the rest of the assistant works without it, but any PDF-to-Markdown request fails here.

Source

Thrown at Co-creation-projects/chengH425-PaperAssistant/src/pdf_tool.py:55

    ]

    def __init__(self):
        super().__init__(
            name="pdf_extract",
            description="从 PDF 文件中提取文本并转换为 Markdown 格式。"
                        "自动识别论文结构(标题、章节、段落),"
                        "清理 PDF 断行和页码等噪声。"
                        "支持本地 PDF 文件路径或 PDF URL。"
                        "适合将论文 PDF 转为 Markdown 后用于进一步分析。"
        )

    def _extract_raw_text(self, file_path: str, start_page: int = 1,
                           end_page: int = -1) -> str:
        """使用 PyPDF2 提取原始文本"""
        try:
            from PyPDF2 import PdfReader
        except ImportError:
            raise ImportError("请安装 PyPDF2: pip install PyPDF2")

        reader = PdfReader(file_path)
        total_pages = len(reader.pages)

        if end_page == -1 or end_page > total_pages:
            end_page = total_pages

        all_text = []
        for i in range(start_page - 1, min(end_page, total_pages)):
            page = reader.pages[i]
            text = page.extract_text()
            if text:
                all_text.append(text)

        if not all_text:
            return ""

        return "\n".join(all_text)

View on GitHub (pinned to 606a07d341)

Solutions

  1. Install the exact requested package: `pip install PyPDF2` (ideally `pip install PyPDF2>=3.0`).
  2. Verify it imports in the same interpreter the app runs under: `python -c "from PyPDF2 import PdfReader"`.
  3. If requirements.txt exists, add PyPDF2 so deployments install it automatically.
  4. Alternative: migrate to `pypdf` (maintained successor) and change the import to `from pypdf import PdfReader`.

Example fix

// before
try:
    from PyPDF2 import PdfReader
except ImportError:
    raise ImportError("请安装 PyPDF2: pip install PyPDF2")

# after
try:
    from pypdf import PdfReader  # maintained successor, same API
except ImportError:
    raise ImportError("请安装 pypdf: pip install pypdf")
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util

def pdf_tool_ready() -> bool:
    return importlib.util.find_spec("PyPDF2") is not None

if not pdf_tool_ready():
    print("Run: pip install PyPDF2")  # or migrate to pypdf

Try / catch

try:
    markdown = pdf_tool.run({"file_path": p})
except ImportError as e:
    if "PyPDF2" in str(e):
        subprocess.run([sys.executable, "-m", "pip", "install", "PyPDF2"])
        markdown = pdf_tool.run({"file_path": p})
    raise

Prevention

When it happens

Trigger: Calling the pdf parsing tool in an environment where PyPDF2 was never installed, was uninstalled, or where a different PDF library (pypdf, PyMuPDF) is installed instead — the import name `PyPDF2` is checked specifically.

Common situations: Installing only the assistant's core requirements and skipping optional extras; Python 3.12+ environments where old PyPDF2 wheels are unavailable; confusion between the legacy `PyPDF2` package and its successor `pypdf` (different import name).

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/05edf8d1623d647d. Report an issue: GitHub.