关于 alterlab-markitdown
alterlab-markitdown 是使用 Microsoft 的 MarkItDown Python 包和命令行工具,将文档、媒体及网页内容转换为 Markdown 的技能,面向 LLM 和文本分析流程,并支持按格式提取内容及可选图像描述和 OCR。
主要功能
- 01将文档和媒体转换为 Markdown
- 02处理 Office 文件、网页和压缩包
- 03提取音频及 YouTube 转录文本
- 04添加基于 LLM 的图像描述
- 05通过插件扩展转换能力
适用场景
- 01批量转换混合格式文档
- 02将电子表格转为 Markdown 表格
- 03为演示文稿生成图像描述
- 04提取 YouTube 视频转录文本
MCP 相关
相关的 markitdown-mcp MCP 服务提供 convert_to_markdown(uri) 工具,支持 http:、https:、file: 和 data: URI。启用后可使用已安装的插件。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-markitdown安装后在 Claude Code 中输入/alterlab-markitdown确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/example_usage.mdevals/evals.jsonreferences/api_reference.mdfile_formats.mdscripts/batch_convert.pyconvert_literature.pyconvert_with_ai.py详细介绍
MarkItDown - 文件转 Markdown
概述
MarkItDown 是 Microsoft 提供的 Python 包和 CLI,可将文档、媒体和网页内容转换为 Markdown,以用于 LLM 和文本分析工作流。它会保留对模型有用的结构(标题、列表、表格、链接),但并非用于高保真、面向用户的文档转换。本技能面向 markitdown 0.1.x(当前版本为 0.1.8,2026 年 9 月;Python 3.10–3.14)。
何时使用本技能
当用户希望执行以下操作时,使用本技能:
- 将 PDF、Word、PowerPoint、Excel、EPUB、HTML 或 Outlook 文件转换为 Markdown,以用于 LLM 提示词、RAG 索引或文本分析
- 批量转换包含多种文档格式的文件夹
- 获取 YouTube 字幕稿或音频转录文本,并转换为 Markdown
- 添加由 LLM 编写的图像描述,或从扫描件和嵌入图像中识别 OCR 文本
- 通过
markitdown-mcp服务向 Agent 提供文件转换功能
不适用场景
| 场景 | 改用 |
|---|---|
| 将大量来源导入可自托管的笔记本,并使用聊天、搜索或播客功能 | alterlab-open-notebook |
| 针对一份 PDF 的章节、图表和表格回答问题 | alterlab-pdf-explore |
| 根据多份 PDF 构建每篇论文占一行的证据表 | alterlab-pdf-extract |
| 管理参考文献、DOI 或 BibTeX 文献库 | alterlab-pyzotero |
支持的格式
| 格式 | 描述 | 备注 |
|---|---|---|
| Portable Document Format | 提取文本层([pdf]);扫描件需要 OCR(见下文) | |
| DOCX | Microsoft Word | 标题、列表、表格([docx]) |
| PPTX | PowerPoint | 幻灯片文本、表格、备注;可选的 LLM 图像描述([pptx]) |
| XLSX / XLS | Excel 电子表格 | 每张工作表生成一个 Markdown 表格([xlsx]、[xls]) |
| 图像 | JPEG、PNG | EXIF 元数据(需要 exiftool);设置 llm_client 后可生成 LLM 描述 |
| 音频 | WAV、MP3、M4A、MP4 | 元数据 + 语音转录([audio-transcription]) |
| HTML | 网页 | 转换结果简洁;Wikipedia 和 Bing 结果页有专门的处理方式 |
| CSV / JSON / XML | 基于文本的数据 | CSV 转为表格;JSON、JSONL 和 XML 直接作为文本传递;RSS/Atom 订阅源会被解析 |
| ZIP | 压缩文件 | 遍历其中的内容 |
| EPUB | 电子书 | 提取全文 |
| Outlook MSG | 电子邮件 | 标题和正文([outlook]) |
| Jupyter | .ipynb 笔记本 | Markdown 和代码单元格 |
| YouTube | 视频 URL | 获取字幕稿([youtube-transcription]) |
快速开始
安装
# Install with all features (uv-first; uv pip works inside an active venv)
uv pip install 'markitdown[all]'
# Or run the CLI ad hoc without installing into the project env
uvx --from 'markitdown[all]' markitdown document.pdf -o output.md
# Or from source
git clone https://github.com/microsoft/markitdown.git
cd markitdown
uv pip install -e 'packages/markitdown[all]'
命令行用法
# Basic conversion
markitdown document.pdf > output.md
# Specify output file
markitdown document.pdf -o output.md
# Pipe content (give a type hint when reading from stdin)
cat document.pdf | markitdown -x pdf > output.md
# Keep embedded images as data URIs instead of truncating them
markitdown slides.pptx --keep-data-uris -o slides.md
# Plugins
markitdown --list-plugins # list installed plugins
markitdown --use-plugins document.pdf -o output.md
Python API
from markitdown import MarkItDown, StreamInfo
md = MarkItDown()
result = md.convert("document.pdf")
print(result.markdown) # result.text_content is a soft-deprecated alias
print(result.title) # may be None
# Local files only (narrower than convert(), which also fetches URIs)
result = md.convert_local("document.pdf")
# From a binary stream; stream_info replaces the deprecated file_extension= keyword
with open("document.pdf", "rb") as f:
result = md.convert_stream(f, stream_info=StreamInfo(extension=".pdf"))
高级功能
1. AI 增强型图像描述
通过 OpenRouter 使用 LLM 描述图像(内置支持图像文件和 PPTX 中的图片):
import os
from markitdown import MarkItDown
from openai import OpenAI
# OpenRouter takes the dotted slug of an Anthropic model ID (claude-opus-5-5 -> anthropic/claude-opus-5.5);
# scripts/convert_with_ai.py derives it from $ALTERLAB_MODEL (skills/core/shared/model_env.md).
model = "anthropic/claude-opus-5.5"
# Initialize OpenRouter client (OpenAI-compatible API)
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1"
)
md = MarkItDown(
llm_client=client,
llm_model=model, # recommended for scientific vision
llm_prompt="Describe this image in detail for scientific documentation"
)
result = md.convert("presentation.pptx")
print(result.markdown)
2. 扫描件和嵌入图像的 OCR
MarkItDown 没有本地 OCR 引擎;转换器会读取现有的文本层。以下两种受支持的方式可添加 OCR:
-
markitdown-ocr插件(Microsoft,0.1.x):使用 LLM 视觉功能对 PDF、DOCX、PPTX 和 XLSX 中的图像进行 OCR,并对扫描版 PDF 执行整页 OCR。它会复用图像描述所用的llm_client/llm_model;如果没有客户端,则会静默回退到常规转换器。uv pip install markitdown-ocr openaimd_ocr = MarkItDown(enable_plugins=True, llm_client=client, llm_model=model) # client/model as above result = md_ocr.convert("scanned_paper.pdf") -
Azure Document Intelligence(云端 OCR 和版面分析)——见下一节。
如需完全本地的 OCR,请先添加文本层(例如,使用 Tesseract 执行 ocrmypdf scan.pdf searchable.pdf),然后再转换结果。
3. Azure Document Intelligence 和 Content Understanding
# Document Intelligence (endpoint on the command line or in MARKITDOWN_DOCINTEL_ENDPOINT)
markitdown document.pdf -o output.md -d -e "<document_intelligence_endpoint>"
# Content Understanding (documents, images, audio, video; needs the [az-content-understanding] extra)
markitdown recording.mp4 --use-cu --cu-endpoint "<content_understanding_endpoint>"
from markitdown import MarkItDown
md = MarkItDown(docintel_endpoint="<document_intelligence_endpoint>")
result = md.convert("complex_document.pdf")
print(result.markdown)
如果设置了 AZURE_API_KEY 环境变量,则使用该变量进行身份验证;否则使用 DefaultAzureCredential(Azure CLI 登录、托管标识等);也可以传入 docintel_credential= 显式提供凭据。这两项服务都会将文档发送到 Azure,请确认处理的数据允许这样做。
4. 插件系统
插件默认处于禁用状态。使用 CLI 中的 --use-plugins 或在 Python 中设置 MarkItDown(enable_plugins=True) 来启用插件。使用 GitHub 主题标签 #markitdown-plugin 查找第三方插件;编写插件请参阅 references/api_reference.md。
5. MCP 服务
markitdown-mcp(0.0.1 alpha 系列)提供一个工具 convert_to_markdown(uri),用于处理 http:、https:、file: 和 data: URI。
uv pip install markitdown-mcp
markitdown-mcp # STDIO transport (default)
markitdown-mcp --http --host 127.0.0.1 --port 3001 # Streamable HTTP + SSE on localhost
# Register with Claude Code
claude mcp add markitdown -- uvx markitdown-mcp
在服务环境中设置 MARKITDOWN_ENABLE_PLUGINS=true,即可使用已安装的插件。该服务没有身份验证,并且可以读取其运行用户有权读取的任何文件,因此请仅在 localhost 上运行(上游建议 Claude Desktop 使用 Docker 镜像)。
可选依赖项
控制要支持的文件格式:
# Install specific formats (no spaces inside the bracket — pip parses 'pdf, docx' as bad names)
uv pip install 'markitdown[pdf,docx,pptx]'
# All available options:
# [all] - All optional dependencies
# [pptx] - PowerPoint files
# [docx] - Word documents
# [xlsx] - Excel spreadsheets
# [xls] - Older Excel files
# [pdf] - PDF documents
# [outlook] - Outlook messages
# [az-doc-intel] - Azure Document Intelligence
# [az-content-understanding] - Azure Content Understanding
# [audio-transcription] - WAV and MP3 transcription
# [youtube-transcription] - YouTube video transcription
常见用例
1. 转换一个论文文件夹
from pathlib import Path
from markitdown import MarkItDown
md = MarkItDown()
pdf_dir, output_dir = Path("papers/"), Path("markdown_output/")
output_dir.mkdir(exist_ok=True)
for pdf_file in pdf_dir.glob("*.pdf"):
try:
result = md.convert_local(pdf_file)
except Exception as e: # keep going; report failures at the end
print(f"✗ {pdf_file.name}: {e}")
continue
(output_dir / f"{pdf_file.stem}.md").write_text(result.markdown)
对于需要日志记录和并行处理的大型任务,请使用 scripts/batch_convert.py。
2. 提取 Excel 数据以供分析
from markitdown import MarkItDown
result = MarkItDown().convert("data.xlsx")
print(result.markdown) # one Markdown table per sheet
3. 使用 AI 描述转换 PowerPoint
import os
from markitdown import MarkItDown
from openai import OpenAI
# OpenRouter takes the dotted slug of an Anthropic model ID (claude-opus-5-5 -> anthropic/claude-opus-5.5);
# scripts/convert_with_ai.py derives it from $ALTERLAB_MODEL (skills/core/shared/model_env.md).
model = "anthropic/claude-opus-5.5"
# Use OpenRouter for access to multiple AI models
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1"
)
md = MarkItDown(
llm_client=client,
llm_model=model, # recommended for presentations
llm_prompt="Describe this slide image in detail, focusing on key visual elements and data"
)
result = md.convert("presentation.pptx")
with open("presentation.md", "w") as f:
f.write(result.markdown)
4. 提取 YouTube 视频转录文本
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("https://www.youtube.com/watch?v=VIDEO_ID")
print(result.markdown)
Docker 用法
# Build image (from the repository root)
docker build -t markitdown:latest .
# Run conversion
docker run --rm -i markitdown:latest < ~/document.pdf > output.md
最佳实践
1. 选择合适的转换方法
- 简单文档:使用基本的
MarkItDown() - 复杂布局或扫描版 PDF:使用 Azure Document Intelligence 或
markitdown-ocr插件 - 视觉内容:启用 AI 图像描述
- 不可信输入:使用
convert_local()或convert_stream(),而不是convert()
2. 妥善处理错误
from markitdown import MarkItDown, FileConversionException, UnsupportedFormatException
md = MarkItDown()
try:
result = md.convert_local("document.pdf")
print(result.markdown)
except FileNotFoundError:
print("File not found")
except UnsupportedFormatException:
print("No converter for this format (is the matching extra installed?)")
except FileConversionException as e:
print(f"Conversion error: {e}")
3. 优化 Token 效率
Markdown 输出的 Token 效率已经很高,但你可以合并空行,并删除不需要的元数据:
import re
clean_text = re.sub(r"\n{3,}", "\n\n", result.markdown).strip()
与科研工作流集成
转换文献以供评审
from markitdown import MarkItDown
from pathlib import Path
md = MarkItDown()
# Convert all papers in literature folder
papers_dir = Path("literature/pdfs")
output_dir = Path("literature/markdown")
output_dir.mkdir(exist_ok=True)
for paper in papers_dir.glob("*.pdf"):
result = md.convert(str(paper))
# Save with metadata
output_file = output_dir / f"{paper.stem}.md"
content = f"# {paper.stem}\n\n"
content += f"**Source**: {paper.name}\n\n"
content += "---\n\n"
content += result.markdown
output_file.write_text(content)
# For AI-enhanced conversion with figures
import os
from openai import OpenAI
# Model ID via the ALTERLAB_MODEL convention (skills/core/shared/model_env.md).
model = "anthropic/claude-opus-5.5" # OpenRouter slug of the ALTERLAB_MODEL default (skills/core/shared/model_env.md)
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1"
)
md_ai = MarkItDown(
llm_client=client,
llm_model=model,
llm_prompt="Describe scientific figures with technical precision"
)
安全
MarkItDown 会以当前进程的权限读取文件和获取 URL。当输入的任何部分来自不可信用户(托管工具、处理网页内容的 Agent)时,请先验证路径和 URL,屏蔽私有地址和元数据服务地址,并调用范围最窄的方法(convert_local()、convert_stream(),或对自行获取的响应调用 convert_response()),而不是 convert()。
故障排除
常见问题
-
缺少依赖项(
MissingDependencyException):安装相应的功能额外依赖uv pip install 'markitdown[pdf]' # For PDF support -
二进制文件错误:
convert_stream()需要二进制流with open("file.pdf", "rb") as f: # Note the "rb" result = md.convert_stream(f, stream_info=StreamInfo(extension=".pdf")) -
扫描版 PDF 或图像输出为空:MarkItDown 未找到文本层。请使用
markitdown-ocr插件、Azure Document Intelligence,或在转换前使用ocrmypdf在本地添加文本层。仅安装 Tesseract 并不能在 MarkItDown 中启用 OCR。 -
图像或音频没有 EXIF 元数据:安装
exiftool(或将EXIFTOOL_PATH指向它)。
性能注意事项
- PDF 文件:大型 PDF 需要较长时间处理;没有页面范围选项,因此必要时请先拆分超大型文件
- 重复使用同一个
MarkItDown()实例处理多个文件;创建实例时会加载文件类型检测器 - 音频转录:通过
speech_recognition包将音频发送到 Google Web Speech API(需要网络;处理较长文件时速度较慢);除非伦理审批允许第三方处理,否则不要将其用于包含参与者访谈等机密研究录音 - AI 图像描述 / OCR 插件:每张图像会调用一次 API(可能产生费用并受速率限制)
后续步骤
- 查看
references/api_reference.md,了解完整 API 文档、自定义转换器和插件 - 查看
references/file_formats.md,了解特定格式的详细信息 - 查看
scripts/batch_convert.py,了解自动化示例 - 探索
scripts/convert_with_ai.py,了解 AI 增强转换
资源
- MarkItDown GitHub:https://github.com/microsoft/markitdown
- PyPI:https://pypi.org/project/markitdown/(也包括
markitdown-ocr、markitdown-mcp) - OpenRouter:https://openrouter.ai(用于 AI 增强转换)
- OpenRouter API Keys:https://openrouter.ai/keys
- OpenRouter Models:https://openrouter.ai/models
- 插件开发:请参阅 MarkItDown 仓库中的
packages/markitdown-sample-plugin
属于 AlterLab Academic Skills 套件的一部分。