Files
lyxy-document/scripts/readers/docx/__init__.py
lanyuanxiaoyao b80c635f07 refactor: 完善降级链的异常捕获机制
为所有 Reader 的 parser 循环添加 try-except 防护层,确保即使 parser
抛出意外异常,降级链也能继续尝试下一个 parser。

主要变更:
- 所有 Reader (DocxReader/PdfReader/XlsxReader/PptxReader/HtmlReader)
  的 parse 方法中添加防护层,捕获意外异常并标记为 [意外异常]
- cleaner.clean_html_content() 添加异常处理,返回 (content, error) 元组
- HtmlReader.parse() 更新 cleaner 调用方式,处理新的返回值格式
- BaseReader 添加详细的异常处理规范文档

设计原则:双层异常保护
- Parser 层:捕获预期的解析失败(库未安装、格式不支持)
- Reader 层:捕获意外的编程错误(NoneType、索引越界等)
2026-03-09 00:26:51 +08:00

57 lines
1.5 KiB
Python

"""DOCX 文件阅读器,支持多种解析方法。"""
import os
from typing import List, Optional, Tuple
from scripts.readers.base import BaseReader
from scripts.utils import is_valid_docx
from . import docling
from . import unstructured
from . import markitdown
from . import pypandoc
from . import python_docx
from . import native_xml
PARSERS = [
("docling", docling.parse),
("unstructured", unstructured.parse),
("pypandoc-binary", pypandoc.parse),
("MarkItDown", markitdown.parse),
("python-docx", python_docx.parse),
("XML 原生解析", native_xml.parse),
]
class DocxReader(BaseReader):
"""DOCX 文件阅读器"""
def supports(self, file_path: str) -> bool:
return file_path.lower().endswith('.docx')
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_docx(file_path):
return None, ["不是有效的 DOCX 文件"]
content = None
for parser_name, parser_func in PARSERS:
try:
content, error = parser_func(file_path)
if content is not None:
return content, failures
else:
failures.append(f"- {parser_name}: {error}")
except Exception as e:
failures.append(f"- {parser_name}: [意外异常] {type(e).__name__}: {str(e)}")
return None, failures