
微软官方开源了一款文献格局诊疗用具——MarkItDown!

它不仅不错将常见的 Office 文档(Word、PowerPoint、Excel)、PDF、图像、音频等诊疗为对大模子更友好的Markdown格局。
况兼还因循集成像 GPT-4o 这么的多模态 LLM,不错平直对图片、音频文献进行更高档的贬责,比如快速输出生意评释。
以后设置者们上传锻练数据、微调 LLM 欺骗皆更轻便了。
发布仅两个月,它的 GitHub 保藏数就逾越了3 万。

具体来说,它因循的文献格局包括:
PowerPoint
Word
Excel
图像(含 OCR 和 EXIF 元数据)
音频(含 EXIF 元数据和转录)
HTML
其他基于文本的格局 ( CSV, JSON, XML )
压缩包
使用方式上,MarkItDown 提供了号令行、Python API以及Docker三种花式。

关切网友 Aark Kodur 还制作了在线版的网页欺骗,点开网址就能平直试用。

可接多模态 LLM 平直生成评释
哥伦比亚大学讲师Tharsis 用一个证券评释分析任务测试了 MarkItDown 的性能,同期也将它与 IBM 的热点 Markdown 诊疗库Docling进行了对比,沿路来望望吧。
率先望望两个库的基本信息。
MarkItDown 是由微软 AutoGen 团队设置的 Python 包和 CLI,用于将各式文献格局诊疗为 Markdown。
它因循包括 PDF、PowerPoint、Word、Excel、图像(含 OCR 和 EXIF 元数据)、音频(含转录)、HTML 以过甚他基于文本的格局,是文档索引和构建基于 LLM 欺骗门径的有服从具。
主要特色:
轻佻号令行和 Python API 接口
因循多种文献格局
可集成 LLM增强图像形色
因循批贬责智商
因循Docker容器化使用
使用示例:
from markitdown import MarkItDown
md = MarkItDown ( ) result = md.convert ( "test.xlsx" ) print ( result.text_content )
Docling 是由 IBM 盘问院设置的 Python 包,用于默契和将文档诊疗为各式格局。
它提供高档文档交融智商,重心在于保抓文档结构和格局。
因循多种文档格局(PDF、DOCX、PPTX、XLSX、图片、HTML 等)
高档 PDF 默契,包括布局分析和表格提真金不怕火
调处的文档暗意格局
集成LlamaIndex 和 LangChain
因循 OCR 分析扫描文档
轻佻号令行界面
from docling.document_converter import DocumentConverter
converter = DocumentConverter ( ) result = converter.convert ( "document.pdf" ) print ( result.document.export_to_markdown ( ) )
本案例盘问将主要从好意思林证券(Merrill Lynch)于 2024 年 12 月 16 日发布的首席信息官本钱阛阓瞻望中提真金不怕火经济预测。
咱们将主要关注该文档的第 7 页,其中包含多个经济变量,这些变量以表格、文本和图像的搀杂花式组织。

FORECAST_FILE_PATH = "../data/input/forecast.pdf"
率先,咱们将使用 MarkItDown 从文档中提真金不怕火文本内容。
from markitdown import MarkItDown
md = MarkItDown ( ) result_md = md.convert ( FORECAST_FILE_PATH ) .text_content
接下来,咱们使用 Docling 进行相同的操作。
from docling.document_converter import DocumentConverter
converter = DocumentConverter ( ) forecast_result_docling = converter.convert ( source ) .document.export_to_markdown ( )
这两个效果有多相似?
咱们不错使用Levenshtein 距离来揣测两个效果之间的相似度。
还不错使用 difflib 包中的SequenceMatcher来计较一个轻佻的分数,这是基于最长宇宙子序列中匹配数来揣测两个字符串相似度的一个轻佻度量。
import Levenshteindef levenshtein_similarity ( text1: str, text2: str ) -> float: """ Calculate normalized Levenshtein distance Returns value between 0 ( completely different ) and 1 ( identical ) """ distance = Levenshtein.distance ( text1, text2 ) max_len = max ( len ( text1 ) , len ( text2 ) ) return 1 - ( distance / max_len )
from difflib import SequenceMatcherdef simple_similarity ( text1: str, text2: str ) -> float: """ Calculate similarity ratio using SequenceMatcher Returns value between 0 ( completely different ) and 1 ( identical ) """ return SequenceMatcher ( None, text1, text2 ) .ratio ( )
底下是 Levenshtein 和 SequenceMatcher 的具体分数:
levenshtein_similarity ( forecast_result_md, forecast_result_docling )
0.13985705461925346
simple_similarity ( forecast_result_md, forecast_result_docling )
0.17779960707269155
效果剖析,这两个效果相配不同,Levenshtein 和 SequenceMatcher 的相似度得分辨认为约 13.98% 和 17.77%。
Docling 的效果是一份格外易读的 Markdown,展示了要道经济变量过甚预测。
相背,MarkItDown 的效果有些絮叨,难以阅读,但信息如实存在,仅仅莫得以结构化的格局呈现。
然而,这伏击吗?
先来望望 Docling 的效果:
display ( Markdown ( forecast_result_docling ) )

MarkItDown 的效果:
from IPython.display import display, Markdowndisplay ( Markdown ( forecast_result_md [ :500 ] ) )

目下,让咱们看一下经济预测的效果,主要关注提真金不怕火 CIO 的 2025E 预测。

咱们将界说一个 Forecast pydantic 模子来暗意由 financial_variable 和 financial_forecast 构成的经济预测。
界说另外一个 EconForecast pydantic 模子来暗意咱们念念要从文档中提真金不怕火的经济预测列表。
from pydantic import BaseModelclass Forecast ( BaseModel ) : financial_variable: str financial_forecast: floatclass EconForecast ( BaseModel ) : forecasts: list [ Forecast ]
以下为领导模板,其中 extract_prompt 是用户但愿提真金不怕火的数据, doc 是待分析的输入文档。
BASE_PROMPT = f""" ROLE: You are an expert at structured data extraction. TASK: Extract the following data {extract_prompt} from input DOCUMENT FORMAT: The output should be a JSON object with 'financial_variable' as key and 'financial_forecast' as value. """prompt = f"{BASE_PROMPT} nn DOCUMENT: {doc}"
咱们编写了一个轻佻的函数,使用 LLM 模子(具有结构化输出)从文档中提真金不怕火经济预测
def extract_from_doc ( extract_prompt: str, doc: str, client ) -> EconForecast: """ Extract data of a financial document using an LLM model. Args: doc: The financial document text to analyze client: The LLM model to use for analysis extract_prompt: The prompt to use for extraction Returns: EconForecasts object containing sentiment analysis results """
BASE_PROMPT = f""" ROLE: You are an expert at structured data extraction. TASK: Extract the following data {extract_prompt} from input DOCUMENT FORMAT: The output should be a JSON object with 'financial_variable' as key and 'financial_forecast' as value. """ prompt = f"{BASE_PROMPT} nn DOCUMENT: {doc}" completion = client.beta.chat.completions.parse ( model="gpt-4o-mini", messages= [ { "role": "system", "content": prompt }, {"role": "user", "content": doc} ] , response_format=EconForecast ) return completion.choices [ 0 ] .message.parsed
from dotenv import load_dotenvimport os
# Load environment variables from .env fileload_dotenv ( override=True ) from openai import OpenAIclient = OpenAI ( )
然后,用户调用 extract_from_doc 函数,轻佻地界说" 2025E 经济预测"是他们念念要从文档中提真金不怕火的数据。
咱们扩充提真金不怕火两次,一次使用 MarkItDown,一次使用 Docling。
extract_prompt = "Economic Forecasts for 2025E"md_financials = extract_from_doc ( extract_prompt, forecast_result_md, client ) docling_financials = extract_from_doc ( extract_prompt, forecast_result_docling, client )
反映是一个包含 Forecast 对象列表的 EconForecast 对象,如 pydantic 模子中界说的那样。
md_financials
EconForecast ( forecasts= [ Forecast ( financial_variable='Real global GDP ( % y/y annualized ) ', financial_forecast=3.2 ) , Forecast ( financial_variable='Real U.S. GDP ( % q/q annualized ) ', financial_forecast=2.4 ) , Forecast ( financial_variable='CPI inflation ( % y/y ) ', financial_forecast=2.5 ) , Forecast ( financial_variable='Core CPI inflation ( % y/y ) ', financial_forecast=3.0 ) , Forecast ( financial_variable='Unemployment rate ( % ) ', financial_forecast=4.3 ) , Forecast ( financial_variable='Fed funds rate, end period ( % ) ', financial_forecast=3.88 ) ] )
然后咱们不错将反映诊疗为 pandas DataFrame 格局,以便于比拟。
df_md_forecasts = pd.DataFrame ( [ ( f.financial_variable, f.financial_forecast ) for f in md_financials.forecasts ] , columns= [ 'Variable', 'Forecast' ] ) df_docling_forecasts = pd.DataFrame ( [ ( f.financial_variable, f.financial_forecast ) for f in docling_financials.forecasts ] , columns= [ 'Variable', 'Forecast' ] )
df_md_forecasts

df_docling_forecasts

MarkItDown 和 Docling 的效果统统调换,与文档中的真正值准确匹配。
这标明,尽管从东说念主类阅读的角度来看,MarkItDown 的输出看起来不太易读,但在此特定情况下,两种步调皆使 LLM 以调换的准确性告成提真金不怕火经济预测数据。
目下,让咱们关注钞票类别权重。
咱们将从文档中提真金不怕火钞票类别权重,并比拟 MarkItDown 和 Docling 的效果。
目下信息呈现的结构格外不同。CIO 的不雅点信息以" underweight "运行,历程" neutral ",达到" overweight "。
本色信息在图表中以一些彩色点标出。让咱们望望咱们是否不错从文档中提真金不怕火这些信息。

用户只需界说以下数据以提真金不怕火:"死心 2024 年 12 月 3 日的钞票类别权重(-2 至 2 的刻度)"。
这么,咱们预计" underweight "将映射为 -2," neutral "映射为 0," overweight "映射为 2,之间还有一些数值。
extract_prompt = "Asset Class Weightings ( as of 12/3/2024 ) in a scale from -2 to 2"asset_class_docling = extract_from_doc ( extract_prompt, forecast_result_docling, client ) asset_class_md = extract_from_doc ( extract_prompt, forecast_result_md, client )
df_md = pd.DataFrame ( [ ( f.financial_variable, f.financial_forecast ) for f in asset_class_md.forecasts ] , columns= [ 'Variable', 'Forecast' ] ) df_docling = pd.DataFrame ( [ ( f.financial_variable, f.financial_forecast ) for f in asset_class_docling.forecasts ] , columns= [ 'Variable', 'Forecast' ] )
目下咱们构建一个 DataFrame 来比拟 MarkItDown 和 Docling 的效果,并添加一个包含从文档中手动提真金不怕火的真正值的" true_value "列。
# Create DataFrame with specified columnsdf_comparison = pd.DataFrame ( { 'variable': df_docling [ 'Variable' ] .iloc [ :-1 ] , 'markitdown': df_md [ 'Forecast' ] , 'docling': df_docling [ 'Forecast' ] .iloc [ :-1 ] , # Drop last row 'true_value': [ 1.0, 0.0, 1.0, 1.0, 1.0, -1.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, -1.0, 0.0, -1.0 ] } )
display ( df_comparison )

然后咱们计较出 Docling 和 MarkItDown 的准确率:
# Calculate accuracy for markitdown and doclingmarkitdown_accuracy = ( df_comparison [ 'markitdown' ] == df_comparison [ 'true_value' ] ) .mean ( ) docling_accuracy = ( df_comparison [ 'docling' ] == df_comparison [ 'true_value' ] ) .mean ( )
print ( f"Markitdown accuracy: {markitdown_accuracy:.2%}" ) print ( f"Docling accuracy: {docling_accuracy:.2%}" )
Markitdown accuracy: 53.33%Docling accuracy: 93.33%
Docling 的准确率达到了93.33%,仅缺失一个值。MarkItDown 的准确率为 53.33%,在微小的钞票类别权重进展较差。
在这种情况下,LLM 从 Docling 的结构化默契的输出如实比从 MarkItDown 的无结构化输出中提真金不怕火了更精准的信息。
更肃穆的分析将需要在大批样本数据上运行屡次数据提真金不怕火以料到不实率。
若是咱们念念系统地从文档中提真金不怕火统共表格呢?
咱们不错通过轻佻地走访 DocumentConverter 对象的 tables 属性来使用 Docling 罢了这小数。
import timefrom pathlib import Pathimport pandas as pdfrom docling.document_converter import DocumentConverter
def convert_and_export_tables ( file_path: Path ) -> list [ pd.DataFrame ] : """ Convert document and export tables to DataFrames. Args: file_path: Path to input document Returns: List of pandas DataFrames containing the tables """ doc_converter = DocumentConverter ( ) start_time = time.time ( ) conv_res = doc_converter.convert ( file_path ) tables = [ ] # Export tables for table in conv_res.document.tables: table_df: pd.DataFrame = table.export_to_dataframe ( ) tables.append ( table_df )
end_time = time.time ( ) - start_time print ( f"Document converted in {end_time:.2f} seconds." ) return tables
# Convert and export tablestables = convert_and_export_tables ( Path ( FORECAST_FILE_PATH ) )
咱们不雅察到 Docling 从文档中提真金不怕火了 7 个表格。按照文档中出现的章程,从上到下、从左到右导出表格。
len ( tables )
7
底下,咱们不错看到告成提真金不怕火的第一个表格是对于股票预测的,第二个是对于固定收益预测的,以及终末一个包含首席投资官股票行业不雅点的表格。
display ( tables [ 0 ] )

display ( tables [ 1 ] )

display ( tables [ 6 ] )

回到 MarkItDown,它的一个伏击秉性是不错集成一个多模态 LLM,从图像中提真金不怕火信息并进行分析与形色。
md_llm = MarkItDown ( llm_client=client, llm_model="gpt-4o-mini" )
result = md_llm.convert ( "../data/input/forecast.png" )
以下是咱们从输入文档的图像中赢得的形色。
display ( Markdown ( result.text_content ) )

总体而言,该形色在某种进度上是准确的,但包含了一些不准确之处,包括:
对于板块权重,形色中提到"在好意思国小盘成长股方面存在低配头寸",但从钞票类别权重图表来看,好意思国小盘成长股本色上剖析为超配头寸(绿色圆圈)。
形色中提到"在公用行状和金融等某些板块存在超配头寸",但从首席投资官股票板块不雅点来看,这两个板块皆剖析为中立头寸,而非超配头寸。
对于固定收益,形色中提到" 10 年期(4.03%)"收益率,但图片剖析的是 30 年期收益率为 4.03%,而本色上 10 年期收益率为 4.40%。
不错说,形色中的这些不准确之处可能是底层大型说话模子无法贬责图像的效果。需要进一步盘问来驯服是否如实如斯。
更多好用的诊疗库
网友们还共享了其他好用的格局诊疗库,比如MinerU和Pandoc等。
MinerU 保藏数逾越2.4万,还加多了对 json 格局的因循。

而 Pandoc 保藏数逾越3.5万,因循的文献类型更鄙俚,以致还包括输出 epub、ipynb 等等。
下次需要将文献诊疗成 LLM 容易贬责的数据格局的时分,皆不错试试哦!

在线版:https://www.getmarkdown.com/
MarkltDown 库地址:github.com/microsoft/markitdown
参考纠合:
[ 1 ] https://www.tamingllms.com/notebooks/input.html#structured-extraction网赌足球app
