当前位置: 首页 > news >正文

Docling将pdf转markdown以及与AI生态集成

Docling 简化了文档处理,解析各种格式(包括高级 PDF 理解),并提供与 gen AI 生态系统的无缝集成。

特征

  • 解析多种文档格式 ,包括 PDF、DOCX、PPTX、XLSX、HTML、WAV、MP3、图像(PNG、TIFF、JPEG 等)等;
  • 高级 PDF 理解,包括页面布局、阅读顺序、表格结构、代码、公式、图像分类等;
  • 统一、富有表现力的 DoclingDocument 表示格式;
  • 各种导出格式和选项,包括 Markdown、HTML、 DocTags 和无损 JSON;
  • 敏感数据和隔离环境的本地执行能力;
  • 即插即用集成, 包括 LangChain、LlamaIndex、Crew AI 和用于代理 AI 的 Haystack;
  • 对扫描的 PDF 和图像提供广泛的 OCR 支持;
  • 支持多种可视化语言模型;
  • 支持自动语音识别 (ASR) 模型的音频;
  • 简单便捷的 CLI。

一、简单Demo

安装包

pip install docling

官方提供的demo代码,

from docling.document_converter import DocumentConvertersource = "https://arxiv.org/pdf/2206.01062"  # document per local path or URLconverter = DocumentConverter()
result = converter.convert(source)
print(result.document.export_to_markdown())  # output: "## Docling Technical Report[...]"

几行代码就可以将pdf文档转成markdown格式的文档,表格也转换的很成功。

注意:

1、若未科学上网,代码执行可能会失败;因为代码中会自动下载docling运行所依赖的模型以及默认的easyocr的模型文件;下载好的文件会放$HOME/.cache/docling/models 目录。

2、一般我们都会事先从huggface或modelscope下载好模型文件,下载如下文件,放同一个目录下。

二、pdf转markdown,图片本地存储

指定本地模型文件,图片保存到本地。

import pathlib
import logging
import time
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions, EasyOcrOptions
from docling.document_converter import PdfFormatOption, DocumentConverter, ImageFormatOption, PowerpointFormatOption, \WordFormatOption, ExcelFormatOption, HTMLFormatOption
from docling_core.types.doc import ImageRefMode, PictureItem, TableItem# # 指定模型路径
# easyocr_model_storage_directory = r"D:\Test\LLMTrain\DoclingTest\models_file\easyocr\Ceceliachenen\easyocr"  # 使用绝对路径
# # 指定OCR模型
# easyocr_options = EasyOcrOptions()
# # 可以不设置,默认语言:["fr", "de", "es", "en"]
# easyocr_options.lang = ['ch_sim', 'en']  # 中英文
# easyocr_options.model_storage_directory = easyocr_model_storage_directoryartifacts_path = r"C:\Users\muxue\.cache\docling\models"  # 使用绝对路径
pipeline_options = PdfPipelineOptions(artifacts_path=artifacts_path)
# 设置支持OCR
pipeline_options.do_ocr = True
# 设置支持表结构
pipeline_options.do_table_structure = TrueIMAGE_RESOLUTION_SCALE = 2.0
pipeline_options.images_scale = IMAGE_RESOLUTION_SCALE
#pipeline_options.generate_page_images = True
#生成图片,必须要改配置为True
pipeline_options.generate_picture_images = True# 指定OCR模型
#pipeline_options.ocr_options = easyocr_optionsdoc_converter  = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options),InputFormat.IMAGE: ImageFormatOption(pipeline_options=pipeline_options),InputFormat.PPTX: PowerpointFormatOption(pipeline_options=pipeline_options),InputFormat.DOCX: WordFormatOption(pipeline_options=pipeline_options),InputFormat.XLSX: ExcelFormatOption(pipeline_options=pipeline_options),InputFormat.HTML: HTMLFormatOption(pipeline_options=pipeline_options)}
)input_doc_path = r"D:\Test\test.pdf"
start_time = time.time()conv_res = doc_converter.convert(input_doc_path)
output_dir = pathlib.Path("scratch")
output_dir.mkdir(parents=True, exist_ok=True)
doc_filename = conv_res.input.file.stem# Save markdown with externally referenced pictures
md_filename = output_dir / f"{doc_filename}-with-image-refs.md"
conv_res.document.save_as_markdown(md_filename, image_mode=ImageRefMode.REFERENCED)end_time = time.time() - start_time
print(f"Time taken: {end_time} seconds")

三、批量pdf转markdown

将多个pdf批量装成 markdown是常见操作。我们来实现一下吧。

import logging
import time
from collections.abc import Iterable
from pathlib import Path
import yaml
from docling_core.types.doc import ImageRefMode
from docling.datamodel.base_models import ConversionStatus, InputFormat
from docling.datamodel.document import ConversionResult
from docling.datamodel.pipeline_options import PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOptiondef export2md(conv_results: Iterable[ConversionResult], output_dir: Path):output_dir.mkdir(parents=True, exist_ok=True)success_count = 0for conv_res in conv_results:if conv_res.status == ConversionStatus.SUCCESS:success_count += 1doc_filename = conv_res.input.file.stemconv_res.document.save_as_markdown(output_dir / f"{doc_filename}.md",image_mode=ImageRefMode.REFERENCED,)logging.info(f"Converted {doc_filename} to Markdown successfully.")def main():artifacts_path = r"D:\muxue\model_file\docling_all"  # 模型文件使用绝对路径pipeline_options = PdfPipelineOptions(artifacts_path=artifacts_path)# 设置支持OCRpipeline_options.do_ocr = True# 设置支持表结构pipeline_options.do_table_structure = TrueIMAGE_RESOLUTION_SCALE = 2.0pipeline_options.images_scale = IMAGE_RESOLUTION_SCALE#pipeline_options.generate_page_images = True#生成图片,必须要改配置为Truepipeline_options.generate_picture_images = Truedoc_converter  = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)})data_folder = Path(r"D:\muxue\orginal_file")input_doc_paths = [data_folder / "test.pdf",data_folder / "2206.01062v1.pdf",]start_time = time.time()conv_results = doc_converter.convert_all(input_doc_paths,raises_on_error=False,  # to let conversion run through all and examine results at the end)export2md(conv_results, Path("scratch"))end_time = time.time() - start_timeprint(f"Time taken: {end_time} seconds")if __name__ == '__main__':logging.basicConfig(level=logging.INFO)main()

四、PDF无损转Json

import pathlib
import logging
import time
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions, EasyOcrOptions
from docling.document_converter import PdfFormatOption, DocumentConverter, ImageFormatOption, PowerpointFormatOption, \WordFormatOption, ExcelFormatOption, HTMLFormatOption
from docling_core.types.doc import ImageRefMode, PictureItem, TableItemartifacts_path = r"D:\muxue\model_file\docling_all"  # 使用绝对路径
pipeline_options = PdfPipelineOptions(artifacts_path=artifacts_path)
# 设置支持OCR
pipeline_options.do_ocr = True
# 设置支持表结构
pipeline_options.do_table_structure = TrueIMAGE_RESOLUTION_SCALE = 2.0
pipeline_options.images_scale = IMAGE_RESOLUTION_SCALE
#pipeline_options.generate_page_images = True
#生成图片,必须要改配置为True
pipeline_options.generate_picture_images = True# 指定OCR模型
#pipeline_options.ocr_options = easyocr_optionsdoc_converter  = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options),InputFormat.IMAGE: ImageFormatOption(pipeline_options=pipeline_options),InputFormat.PPTX: PowerpointFormatOption(pipeline_options=pipeline_options),InputFormat.DOCX: WordFormatOption(pipeline_options=pipeline_options),InputFormat.XLSX: ExcelFormatOption(pipeline_options=pipeline_options),InputFormat.HTML: HTMLFormatOption(pipeline_options=pipeline_options)}
)input_doc_path = r"D:\muxue\test.pdf"
start_time = time.time()conv_res = doc_converter.convert(input_doc_path)
output_dir = pathlib.Path("scratch")
output_dir.mkdir(parents=True, exist_ok=True)
doc_filename = conv_res.input.file.stem# Save markdown with externally referenced pictures
md_filename = output_dir / f"{doc_filename}.json"
conv_res.document.save_as_json(md_filename, image_mode=ImageRefMode.REFERENCED)end_time = time.time() - start_time
print(f"Time taken: {end_time} seconds")
  • “无损 JSON” 在 Docling 中意味着:将文档的内在数据结构与详细元信息完整转到 JSON,并保证可以从 JSON 完整还原为同一个文档模型。

  • Markdown/HTML 导出是“有损” 的,因为这些格式省略了很多底层结构与元数据,只是适合人类阅读和简单内容展示。

五、Docling与第3方平台集成

 Docling 与众多领先框架和工具的集成,比如LangChain、LlamaIndex和Crew AI等。

在LlamaIndex中,可以直接使用Docling作为阅读器,和DoclingNodeParser 可将DoclingReader 生成的 JSON/MarkDown 格式文档解析为 LlamaIndex 的节点。

from llama_index.readers.docling import DoclingReader
from llama_index.node_parser.docling import DoclingNodeParser
from llama_index.core import VectorStoreIndex
reader = DoclingReader(export_type=DoclingReader.ExportType.JSON)
node_parser = DoclingNodeParser()
documents = reader.load_data("your_file.pdf")
index = VectorStoreIndex.from_documents(documents=documents,transformations=[node_parser],embed_model=EMBED_MODEL,
)

参考网址

 github地址:https://github.com/docling-project/docling

官方文档:https://docling-project.github.io/docling/

安装和使用docling-CSDN博客

Docling本地部署-CSDN博客

LlamaIndex相关文档:https://docs.llamaindex.ai/en/stable/examples/data_connectors/DoclingReaderDemo/

https://docs.llamaindex.ai/en/stable/api_reference/node_parser/docling/


文章转载自:

http://18P0MOGI.scjtr.cn
http://UhJrcgja.scjtr.cn
http://iHbsPpsY.scjtr.cn
http://U2Nu8F2U.scjtr.cn
http://fPtlkz1p.scjtr.cn
http://p4TKNErc.scjtr.cn
http://zLrZpWIe.scjtr.cn
http://EF4rJ4Xa.scjtr.cn
http://8UrioWfS.scjtr.cn
http://fPWUOGS5.scjtr.cn
http://SPP9mCZs.scjtr.cn
http://Ib8RF6b1.scjtr.cn
http://0jX3OKRc.scjtr.cn
http://8yPjqreW.scjtr.cn
http://UyeMUYz8.scjtr.cn
http://nnYq1saJ.scjtr.cn
http://aSRVd6vk.scjtr.cn
http://q1Mpnhjm.scjtr.cn
http://VmB2gVmq.scjtr.cn
http://0FKWPeL2.scjtr.cn
http://hqyoBScU.scjtr.cn
http://aEdOyYd1.scjtr.cn
http://grCmbPBi.scjtr.cn
http://V0sv8DMJ.scjtr.cn
http://pYSI7rqL.scjtr.cn
http://GaghvEad.scjtr.cn
http://2VDRE3vn.scjtr.cn
http://vJvrEaAk.scjtr.cn
http://fkG5q39M.scjtr.cn
http://B5s2Xr7b.scjtr.cn
http://www.dtcms.com/a/368809.html

相关文章:

  • GD32入门到实战35--485实现OTA
  • 别再看人形机器人了!真正干活的机器人还有这些!
  • C++编程——异步处理、事件驱动编程和策略模式
  • 【分享】AgileTC测试用例管理平台使用分享
  • cargs: 一个轻量级跨平台命令行参数解析库
  • 高级 ACL 有多强?一个规则搞定 “IP + 端口 + 协议” 三重过滤
  • 人大金仓:创建数据库分区
  • 【大数据专栏】大数据框架-Apache Druid Overview
  • Java中的多态有什么用?
  • 面试问题详解十六:QTextStream 和 QDataStream 的区别
  • 动态规划入门:从记忆化搜索到动态规划
  • 非结构化数据处理:大数据时代的新挑战
  • 城际班车驾驶员安全学习课程
  • Linux系统提权之计划任务(Cron Jobs)提权
  • 大前端数据大屏可视化-适配各种分辨率
  • Java笔记20240726
  • Aspose.Words for .NET 25.7:支持自建大语言模型(LLM),实现更安全灵活的AI文档处理功能
  • 怎样利用AE统计数据优化安防芯片ISP的图像质量?
  • 基于Python读取多个excel竖向拼接为一个excel
  • 深入解析汇编语言的奥秘
  • C++语言程序设计——06 字符串
  • 十二、软件系统分析与设计
  • flink 伪代码
  • AGENTS.md: AI编码代理的开放标准
  • 代码可读性的详细入门
  • 单元测试:Jest 与 Electron 的结合
  • 02-Media-5-mp4demuxer.py 从MP4文件中提取视频和音频流的示例
  • K8s访问控制(一)
  • 动物专家?单词测试!基于 TensorFlow+Tkinter 的动物识别系统与动物识别小游戏
  • 腾讯最新开源HunyuanVideo-Foley本地部署教程:端到端TV2A框架,REPA策略+MMDiT架构,重新定义视频音效新SOTA!