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)
This commit is contained in:
62
encoding_detection.py
Normal file
62
encoding_detection.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""文件编码自动检测模块。"""
|
||||
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from config import Config
|
||||
|
||||
|
||||
def detect_encoding(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
检测文件编码。
|
||||
|
||||
Args:
|
||||
file_path: 文件路径
|
||||
|
||||
Returns:
|
||||
(encoding, error): 成功时返回 (编码名称, None),失败时返回 (None, 错误信息)
|
||||
"""
|
||||
try:
|
||||
import chardet
|
||||
except ImportError:
|
||||
return None, "chardet 库未安装"
|
||||
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
raw_data = f.read()
|
||||
result = chardet.detect(raw_data)
|
||||
return result['encoding'], None
|
||||
except Exception as e:
|
||||
return None, f"编码检测失败: {str(e)}"
|
||||
|
||||
|
||||
def read_text_file(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
读取文本文件,自动检测编码。
|
||||
|
||||
首先使用 chardet 检测编码,如果失败则尝试配置的回退编码列表。
|
||||
|
||||
Args:
|
||||
file_path: 文件路径
|
||||
|
||||
Returns:
|
||||
(content, error): 成功时返回 (文件内容, None),失败时返回 (None, 错误信息)
|
||||
"""
|
||||
# 尝试使用 chardet 检测编码
|
||||
encoding, error = detect_encoding(file_path)
|
||||
|
||||
if error:
|
||||
# chardet 失败,使用回退编码列表
|
||||
for enc in Config.FALLBACK_ENCODINGS:
|
||||
try:
|
||||
with open(file_path, 'r', encoding=enc) as f:
|
||||
return f.read(), None
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return None, "无法识别文件编码"
|
||||
|
||||
# 使用检测到的编码读取文件
|
||||
try:
|
||||
with open(file_path, 'r', encoding=encoding) as f:
|
||||
return f.read(), None
|
||||
except Exception as e:
|
||||
return None, f"读取文件失败: {str(e)}"
|
||||
Reference in New Issue
Block a user