*大家好,我是AI拉呱,一个专注于人工智领域与网络安全方面的博主,现任资深算法研究员一职,热爱机器学习和深度学习算法应用,拥有丰富的AI项目经验,希望和你一起成长交流。关注AI拉呱一起学习更多AI知识。
什么是 MarkItDown?
MarkItDown 是一个轻量级 Python 工具,用于将各种文件转换为 Markdown,以便与大型语言模型(LLM)和相关文本分析管道配合使用。它与 [textract] 最为相似,但专注于保留文档结构和内容(包括标题、列表、表格、链接等)。虽然输出通常具有一定可读性,但主要用于文本分析工具,而非面向人类的高保真文档转换。
当前支持的格式:
- PowerPoint
- Word
- Excel
- 图像(EXIF 元数据和 OCR)
- 音频(EXIF 元数据和语音转写)
- HTML
- 文本格式(CSV、JSON、XML)
- ZIP 文件(遍历内容)
- YouTube 链接
- EPubs
- ……更多格式!
为什么选择 Markdown?
Markdown 接近纯文本,标记极少,但仍能表示重要的文档结构。主流 LLM(如 OpenAI 的 GPT-4o)原生“理解”Markdown,且常无需提示即可在响应中使用 Markdown。这表明它们在大量 Markdown 格式文本上训练,能够很好地理解这种格式。此外,Markdown 语法对 token 非常友好。
安装
使用 pip 安装:
pip install 'markitdown[all]'
或从源代码安装:
git clone git@github.com:microsoft/markitdown.git
cd markitdown
pip install -e packages/markitdown[all]
用法
命令行
直接输出到文件:
markitdown path-to-file.pdf > document.md
指定输出文件:
markitdown path-to-file.pdf -o document.md
管道输入:
cat path-to-file.pdf | markitdown
可选依赖项
MarkItDown 的不同文件格式支持通过可选依赖项激活。前文使用 [all]
安装了所有依赖,也可单独安装以精确控制。例如:
pip install markitdown[pdf, docx, pptx]
当前可用的可选依赖项:
[all]
:安装所有可选依赖[pptx]
:PowerPoint 文件依赖[docx]
:Word 文件依赖[xlsx]
:Excel 文件(新格式)依赖[xls]
:Excel 文件(旧格式)依赖[pdf]
:PDF 文件依赖[outlook]
:Outlook 邮件依赖[az-doc-intel]
:Azure Document Intelligence 依赖[audio-transcription]
:音频(WAV/MP3)转写依赖[youtube-transcription]
:YouTube 视频字幕获取依赖
插件
MarkItDown 支持第三方插件(默认禁用)。
列出已安装插件:
markitdown --list-plugins
启用插件:
markitdown --use-plugins path-to-file.pdf
查找可用插件:在 GitHub 搜索 #markitdown-plugin
。开发插件请参考 packages/markitdown-sample-plugin
。
Azure Document Intelligence
使用微软文档智能服务转换:
markitdown path-to-file.pdf -o document.md -d -e "<document_intelligence_endpoint>"
如何设置 Azure Document Intelligence 资源:点击此处
Python API
基础用法:
from markitdown import MarkItDown
md = MarkItDown(enable_plugins=False) # 设为 True 启用插件
result = md.convert("test.xlsx")
print(result.text_content)
使用 Document Intelligence 转换:
from markitdown import MarkItDown
md = MarkItDown(docintel_endpoint="<document_intelligence_endpoint>")
result = md.convert("test.pdf")
print(result.text_content)
使用大语言模型生成图像描述(需提供 LLM 客户端和模型):
from markitdown import MarkItDown
from openai import OpenAI
client = OpenAI()
md = MarkItDown(llm_client=client, llm_model="gpt-4o")
result = md.convert("example.jpg")
print(result.text_content)
Docker
构建镜像:
docker build -t markitdown:latest .
运行转换:
docker run --rm -i markitdown:latest < ~/your-file.pdf > output.md
运行测试和检查
-
进入 MarkItDown 包目录:
cd packages/markitdown
-
安装
hatch
并运行测试:pip install hatch # 其他安装方式:https://hatch.pypa.io/dev/install/ hatch shell hatch test
(可选)使用预配置依赖的 Devcontainer:
# 在 Devcontainer 中重新打开项目并运行: hatch test
-
提交 PR 前运行预提交检查:
pre-commit run --all-files
贡献第三方插件
您也可以通过创建和分享第三方插件参与贡献。详情参考 packages/markitdown-sample-plugin
。
关注“AI拉呱公众号”一起学习更多AI知识!