Files
lyxy-document/readers/pdf/__init__.py
lanyuanxiaoyao 750ef50a8d refactor: 重构解析器架构并添加编码检测和配置管理
简化 parse_input() 为纯调度器,通过遍历 readers 的 supports() 方法识别输入类型,移除 URL 特殊处理和文件检查逻辑。各 reader 的 parse() 方法负责完整验证(文件存在、格式有效性)。

新增功能:
- 添加 chardet 编码自动检测,支持多种中文编码回退机制
- 创建统一配置类管理编码、下载超时、日志等级等配置项
- HTML reader 支持本地文件编码检测和 URL 统一处理

安全性改进:
- 修复 safe_open_zip() 路径遍历漏洞,使用 pathlib 规范化路径
- 添加边界检查,search_markdown() 检查负数参数

其他改进:
- 修复类型注解(argparse.Namespace)
- 日志系统仅输出 ERROR 级别,避免干扰 Markdown 输出
- 更新 BaseReader 接口文档,明确 supports() 和 parse() 职责划分
- 同步 delta specs 到主 specs(document-reading、html-reader、configuration、encoding-detection)
2026-03-08 16:33:40 +08:00

58 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""PDF 文件阅读器支持多种解析方法OCR 优先)。"""
import os
from typing import List, Optional, Tuple
from readers.base import BaseReader
from utils import is_valid_pdf
from . import docling_ocr
from . import unstructured_ocr
from . import docling
from . import unstructured
from . import markitdown
from . import pypdf
PARSERS = [
("docling OCR", docling_ocr.parse),
("unstructured OCR", unstructured_ocr.parse),
("docling", docling.parse),
("unstructured", unstructured.parse),
("MarkItDown", markitdown.parse),
("pypdf", pypdf.parse),
]
class PdfReader(BaseReader):
"""PDF 文件阅读器"""
@property
def supported_extensions(self) -> List[str]:
return [".pdf"]
def supports(self, file_path: str) -> bool:
return file_path.endswith('.pdf')
def parse(self, file_path: str) -> Tuple[Optional[str], List[str]]:
failures = []
# 检查文件是否存在
if not os.path.exists(file_path):
return None, ["文件不存在"]
# 验证文件格式
if not is_valid_pdf(file_path):
return None, ["不是有效的 PDF 文件"]
content = None
for parser_name, parser_func in PARSERS:
content, error = parser_func(file_path)
if content is not None:
return content, failures
else:
failures.append(f"- {parser_name}: {error}")
return None, failures