""" 文档加载模块 ============ 【功能说明】 把知识库原始素材(Markdown / Word / PDF)解析成统一切分前的文档对象。 覆盖《核心诉求》文档知识管理模块的「文档解析组件」职责。 【技术选型理由】 1. 按决策点 6「仅文档正文」:只解析 md/docx/pdf 三种正文格式, 图片与 zip 跳过(截图多是操作示意,OCR 噪声大、性价比低)。 2. 不引入 Unstructured 全家桶(决策点 6 已定):python-docx + pdfminer.six + 原生读取 md 足够,依赖轻、行为可预期、便于教学对照。 3. 解析产物统一为 LangChain Document(page_content + metadata), 与基准文档 9.3「文档加载器」同构,下游切分/向量化可直接复用生态能力。 【实现思路】 - detect_loader() 按扩展名分派到具体解析器; - 每个解析器产出 list[Document],metadata 统一带 source/文件名/类型; - 目录递归扫描,过滤出受支持扩展名,跳过图片与压缩包。 【潜在风险与应对】 风险1:pdfminer 解析扫描版 PDF 得到空文本。 应对:空文本的文档返回 0 个 chunk 并记 warning,不抛异常、不入库脏数据。 风险2:docx 中含表格/图片说明,纯段落提取会丢信息。 应对:一期提取段落文本(表格文本在 python-docx 中也算段落级内容), 在 metadata 标注 docx 类型,二期可升级结构化解析。 风险3:文件编码不是 UTF-8(历史 md 可能是 GBK)。 应对:优先 UTF-8 读取,失败后回退 GBK + errors=replace,避免解码崩溃。 """ from __future__ import annotations import logging from dataclasses import dataclass, field from pathlib import Path logger = logging.getLogger("agent.knowledge.loader") # 受支持的正文扩展名(决策点 6:仅文档正文,不含图片/压缩包) SUPPORTED_EXTENSIONS = {".md", ".markdown", ".docx", ".pdf", ".txt", ".csv", ".log"} @dataclass class LoadedDocument: """ 解析后的文档对象(对齐 LangChain Document 结构)。 【字段】 page_content:正文文本(后续会被切分) metadata:来源信息(source 文件路径、文件名、类型、序号) """ page_content: str metadata: dict = field(default_factory=dict) def _read_text_with_fallback(path: Path) -> str: """ 读取文本文件,UTF-8 优先、GBK 兜底。 【理由】历史文档可能混有 GBK 编码,直接 UTF-8 严格解码会抛异常; 回退 + errors=replace 保证「能读多少读多少」,不让单文件拖垮整批入库。 """ raw = path.read_bytes() for encoding in ("utf-8", "gbk"): try: return raw.decode(encoding) except UnicodeDecodeError: continue return raw.decode("utf-8", errors="replace") def _load_markdown(path: Path) -> list[LoadedDocument]: """解析 Markdown:整篇作为一个文档(切分阶段再按标题语义拆)。""" text = _read_text_with_fallback(path) return [ LoadedDocument( page_content=text, metadata={ "source": str(path), "filename": path.name, "file_type": "markdown", "section": "全文", }, ) ] def _load_text(path: Path) -> list[LoadedDocument]: """ 解析纯文本文件(.txt / .csv / .log)。 【实现】直接读取全文,与 Markdown 同构,切分阶段统一处理。 """ text = _read_text_with_fallback(path) return [ LoadedDocument( page_content=text, metadata={ "source": str(path), "filename": path.name, "file_type": "text", "section": "全文", }, ) ] def _load_docx(path: Path) -> list[LoadedDocument]: """ 解析 Word 文档(.docx)。 【实现】python-docx 提取全部段落文本,按空行保留段落边界。 """ try: from docx import Document as DocxDocument except ImportError as exc: # 依赖缺失时给出可执行的安装提示 raise RuntimeError( "缺少 python-docx 依赖,请执行:uv pip install python-docx" ) from exc doc = DocxDocument(str(path)) paragraphs = [p.text.strip() for p in doc.paragraphs if p.text and p.text.strip()] text = "\n\n".join(paragraphs) return [ LoadedDocument( page_content=text, metadata={ "source": str(path), "filename": path.name, "file_type": "docx", "section": "全文", }, ) ] def _load_pdf(path: Path) -> list[LoadedDocument]: """ 解析 PDF 文档。 【实现】pdfminer.six 按页提取文本,每页一个文档, metadata 记录页码,便于检索结果回溯到具体页。 【降级】pypdf 作为备选提取器(两者任一成功即可)。 """ pages_text: list[str] = [] extract_error: Exception | None = None # 首选 pdfminer.six try: from pdfminer.high_level import extract_text full = extract_text(str(path)) if full and full.strip(): # pdfminer 不直接给分页,按 \f(分页符)切 pages_text = [p.strip() for p in full.split("\f") if p.strip()] or [full.strip()] except Exception as exc: # noqa: BLE001 - 解析失败需降级而非中断 extract_error = exc logger.warning("pdfminer 解析失败,尝试 pypdf:%s %s", path.name, exc) # 备选 pypdf if not pages_text: try: from pypdf import PdfReader reader = PdfReader(str(path)) pages_text = [ (page.extract_text() or "").strip() for page in reader.pages ] pages_text = [p for p in pages_text if p] except Exception as exc: # noqa: BLE001 extract_error = exc logger.warning("pypdf 解析也失败:%s %s", path.name, exc) if not pages_text: logger.warning( "PDF 无可用文本(可能是扫描版):%s,原因=%s", path.name, extract_error ) return [] return [ LoadedDocument( page_content=t, metadata={ "source": str(path), "filename": path.name, "file_type": "pdf", "section": f"第{i + 1}页", "page": i + 1, }, ) for i, t in enumerate(pages_text) ] _LOADERS = { ".md": _load_markdown, ".markdown": _load_markdown, ".docx": _load_docx, ".pdf": _load_pdf, ".txt": _load_text, ".csv": _load_text, ".log": _load_text, } def load_file(path: Path) -> list[LoadedDocument]: """ 解析单个文件。 【返回】LoadedDocument 列表(PDF 按页返回多条,其余返回 1 条)。 【异常】未知扩展名抛 ValueError;解析器缺失依赖抛 RuntimeError。 """ suffix = path.suffix.lower() loader = _LOADERS.get(suffix) if loader is None: raise ValueError(f"不支持的文件类型:{suffix}(支持:{sorted(SUPPORTED_EXTENSIONS)})") return loader(path) def load_directory(directory: Path) -> tuple[list[LoadedDocument], list[str]]: """ 递归扫描目录并解析全部受支持文件。 【返回】(文档列表, 警告列表) 警告列表用于记录被跳过的文件与解析失败项,不中断整批流程(硬约束 5)。 """ docs: list[LoadedDocument] = [] warnings: list[str] = [] root = Path(directory) if not root.exists(): warnings.append(f"目录不存在:{root}") return docs, warnings for file_path in sorted(root.rglob("*")): if not file_path.is_file(): continue suffix = file_path.suffix.lower() if suffix in {".png", ".jpg", ".jpeg", ".gif", ".zip", ".doc"}: warnings.append(f"跳过不支持的文件类型:{file_path.name}") continue if suffix not in SUPPORTED_EXTENSIONS: warnings.append(f"跳过未知类型文件:{file_path.name}") continue try: docs.extend(load_file(file_path)) except Exception as exc: # noqa: BLE001 - 单文件失败不影响整批 warnings.append(f"解析失败:{file_path.name},原因:{exc}") logger.warning("解析失败:%s %s", file_path, exc) return docs, warnings