{"record":{"id":"05edf8d1623d647d","repo":"datawhalechina/hello-agents","slug":"pypdf2-pip-install-pypdf2","errorCode":null,"errorMessage":"请安装 PyPDF2: pip install PyPDF2","messagePattern":"请安装 PyPDF2: pip install PyPDF2","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/chengH425-PaperAssistant/src/pdf_tool.py","lineNumber":55,"sourceCode":"    ]\n\n    def __init__(self):\n        super().__init__(\n            name=\"pdf_extract\",\n            description=\"从 PDF 文件中提取文本并转换为 Markdown 格式。\"\n                        \"自动识别论文结构（标题、章节、段落），\"\n                        \"清理 PDF 断行和页码等噪声。\"\n                        \"支持本地 PDF 文件路径或 PDF URL。\"\n                        \"适合将论文 PDF 转为 Markdown 后用于进一步分析。\"\n        )\n\n    def _extract_raw_text(self, file_path: str, start_page: int = 1,\n                           end_page: int = -1) -> str:\n        \"\"\"使用 PyPDF2 提取原始文本\"\"\"\n        try:\n            from PyPDF2 import PdfReader\n        except ImportError:\n            raise ImportError(\"请安装 PyPDF2: pip install PyPDF2\")\n\n        reader = PdfReader(file_path)\n        total_pages = len(reader.pages)\n\n        if end_page == -1 or end_page > total_pages:\n            end_page = total_pages\n\n        all_text = []\n        for i in range(start_page - 1, min(end_page, total_pages)):\n            page = reader.pages[i]\n            text = page.extract_text()\n            if text:\n                all_text.append(text)\n\n        if not all_text:\n            return \"\"\n\n        return \"\\n\".join(all_text)","sourceCodeStart":37,"sourceCodeEnd":73,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/chengH425-PaperAssistant/src/pdf_tool.py#L37-L73","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Install the exact requested package: `pip install PyPDF2` (ideally `pip install PyPDF2>=3.0`).","Verify it imports in the same interpreter the app runs under: `python -c \"from PyPDF2 import PdfReader\"`.","If requirements.txt exists, add PyPDF2 so deployments install it automatically.","Alternative: migrate to `pypdf` (maintained successor) and change the import to `from pypdf import PdfReader`."],"exampleFix":"// before\ntry:\n    from PyPDF2 import PdfReader\nexcept ImportError:\n    raise ImportError(\"请安装 PyPDF2: pip install PyPDF2\")\n\n# after\ntry:\n    from pypdf import PdfReader  # maintained successor, same API\nexcept ImportError:\n    raise ImportError(\"请安装 pypdf: pip install pypdf\")","handlingStrategy":"validation","validationCode":"import importlib.util\n\ndef pdf_tool_ready() -> bool:\n    return importlib.util.find_spec(\"PyPDF2\") is not None\n\nif not pdf_tool_ready():\n    print(\"Run: pip install PyPDF2\")  # or migrate to pypdf","typeGuard":null,"tryCatchPattern":"try:\n    markdown = pdf_tool.run({\"file_path\": p})\nexcept ImportError as e:\n    if \"PyPDF2\" in str(e):\n        subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"PyPDF2\"])\n        markdown = pdf_tool.run({\"file_path\": p})\n    raise","preventionTips":["Pin PDF deps in requirements.txt and reinstall after recreating venvs.","Prefer the maintained `pypdf` package for new code.","Add a dependency check at app startup for optional-format tools."],"tags":["dependency","importerror","pypdf2","pdf","python"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}