Files
lyxy-document/readers/base.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

49 lines
1.4 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.
"""Reader 基类,定义所有文档阅读器的公共接口。"""
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional, Tuple
class BaseReader(ABC):
"""文档阅读器基类。"""
@property
@abstractmethod
def supported_extensions(self) -> List[str]:
"""返回支持的文件扩展名列表(如 ['.docx', '.doc'])。"""
pass
@abstractmethod
def supports(self, file_path: str) -> bool:
"""
判断是否支持给定的输入(轻量检查)。
仅做初步判断如扩展名、URL 模式),不进行完整验证。
完整验证(文件存在、格式有效性)在 parse() 中进行。
不访问文件系统,不打开文件。
Args:
file_path: 文件路径或 URL
Returns:
True 如果可能支持False 否则
"""
pass
@abstractmethod
def parse(self, file_path: str) -> Tuple[Optional[str], List[str]]:
"""
解析文件并返回 Markdown 内容。
需要检查文件存在和格式有效性,然后执行实际解析逻辑。
Args:
file_path: 文件路径或 URL
Returns: (content, failures)
- content: 成功时返回 Markdown 内容,失败时返回 None
- failures: 各解析器的失败原因列表
"""
pass