Files
2026-09-01 13:00:36 +08:00

31 lines
1004 B
Python

"""MarkItDown 解析器(优先)。"""
from app.core.logging import get_logger
logger = get_logger(__name__)
def parse_with_markitdown(file_content: bytes, filename: str) -> str | None:
"""用 MarkItDown 解析文档,返回 Markdown 或 None(失败时)。"""
try:
from markitdown import MarkItDown
md = MarkItDown()
# MarkItDown 需要文件路径或文件对象,用临时文件
import tempfile
from pathlib import Path
suffix = Path(filename).suffix.lower()
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(file_content)
tmp_path = tmp.name
try:
result = md.convert(tmp_path)
return result.text_content if result and result.text_content else None
finally:
Path(tmp_path).unlink(missing_ok=True)
except Exception as e:
logger.warning("MarkItDown 解析失败 (%s): %s", filename, e)
return None