當您想讓 LLM 讀取內部文件時,無法直接將 Word 或 Excel 檔案交給它。手動複製貼上可能會破壞標題層級和表格結構。markitdown 是 Microsoft 的工具,可將 Office 文件、PDF 和其他檔案格式轉換為 LLM 能讀取的 Markdown。我安裝了這個工具,並測試停用網路時能否進行轉換。
markitdown 可將多種檔案格式轉換為 Markdown,包括 Word、Excel、PowerPoint、PDF 和 HTML,並保留其結構。Microsoft 以 MIT 授權發布原始碼 (*1)。
1. 安裝工具
安裝 markitdown 時加上 [all] 額外選項,即可使用所有支援的格式。我安裝 python-docx 來建立測試用的 Word 文件;markitdown 本身不依賴它。
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'markitdown[all]==0.1.6' 'python-docx==1.2.0'
WORKDIR /work
podman build -t markitdown-sandbox .
2. 將 Word 文件轉換為 Markdown
我建立了一份包含標題、段落和表格的 Word 測試文件,未經修改就交給 markitdown。我在停用網路的情況下執行轉換。
# make_docx.py
from docx import Document
doc = Document()
doc.add_heading("Quarterly Report", level=1)
doc.add_paragraph("This report summarizes rootless container adoption across three teams.")
doc.add_heading("Findings", level=2)
doc.add_paragraph("Teams that switched to rootless Podman reported fewer permission issues.")
table = doc.add_table(rows=3, cols=2)
table.rows[0].cells[0].text = "Team"
table.rows[0].cells[1].text = "Adoption"
table.rows[1].cells[0].text = "Platform"
table.rows[1].cells[1].text = "100%"
table.rows[2].cells[0].text = "Infra"
table.rows[2].cells[1].text = "60%"
doc.save("/work/report.docx")
# convert_demo.py
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("/work/report.docx")
print(result.text_content)
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work markitdown-sandbox \
bash -c "python make_docx.py && python convert_demo.py"
-v 讓容器可以讀寫指定的目錄。請在專為實驗準備的空目錄中執行,並且不要在其中放置未公開的文件或其他機密資料。
輸出結果如下:
# Quarterly Report
This report summarizes rootless container adoption across three teams.
## Findings
Teams that switched to rootless Podman reported fewer permission issues.
| | |
| --- | --- |
| Team | Adoption |
| Platform | 100% |
| Infra | 60% |
標題層級(# 和 ##)及段落都維持完整。markitdown 將表格轉換為 Markdown 表格語法,但沒有把應包含 Team 和 Adoption 標題的第一列視為表頭,而是在其上方產生了空白表頭列。使用此工具前,請以實際資料檢查轉換後的表格,確認表頭列符合您的用意。
複製貼上時保持文件結構完整
將含有標題和表格的文件複製貼上到 LLM 時,無法保留其結構。使用 markitdown 這類轉換工具,您可以將文件交給 LLM,並在 Markdown 中保留標題層級和表格分隔符號。轉換細節可能因格式而異,因此交給 LLM 之前請先檢查輸出結果。
來源
*1 markitdown (GitHub), https://github.com/microsoft/markitdown, MIT License