十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

docling-rag-agent 项目 Docling 入门实战:从 PDF 转换到混合分块的 RAG 文档处理全指南

docling-rag-agent 项目 Docling 入门实战:从 PDF 转换到混合分块的 RAG 文档处理全指南 docling-rag-agent 项目 Docling 入门实战从 PDF 转换到混合分块的 RAG 文档处理全指南【免费下载链接】ottomator-agentsAll the open source AI Agents hosted on the oTTomator Live Agent Studio platform!项目地址: https://gitcode.com/GitHub_Trending/ot/ottomator-agents本文以 docling-rag-agent 仓库中的 docling_basics 渐进式教程 为骨架系统讲解 Docling 文档处理库的核心能力单 PDF 转 Markdown、多格式统一转换、Whisper 语音转写与 HybridChunker 混合分块。读完本文你将掌握一套从原始文档PDF/Word/PPT/Excel/HTML/音频到 RAG 就绪知识库的完整技术路径并能对照仓库源码理解其在实际 RAG Agent 中的落地方式。Docling 是什么为什么 RAG 系统需要它Docling是一个面向复杂文档格式的文档处理库。对 RAG检索增强生成系统而言最耗时的部分往往不是模型本身而是把形态各异的业务文档变成可检索的文本。如果没有 Docling开发者需要自己实现 OCR、版面分析、表格抽取以及各种格式专有的解析器Docling 将这些能力开箱即用地整合在一起。docling-rag-agent仓库将其定位为整个知识库管线的地基——仓库主 README 明确建议新用户先学习docling_basics/教程再进入完整 RAG Agent 实现。其核心优势可概括为无需自定义 OCR内置 OCR 能力支持 EasyOCR扫描件也能处理保留文档结构表格、章节、层级关系不会在转换中丢失多格式支持PDF、Word、PowerPoint、Excel、HTML、图片乃至音频均可处理RAG 就绪内置针对 Embedding 模型优化的智能分块HybridChunker统一的 Markdown 输出无论输入什么格式输出都是干净一致的 Markdown便于下游统一处理。仓库在 docling_basics/01_simple_pdf.py 的脚本头注释中对这套能力给出了同样描述可作为事实依据。教程总览四个渐进示例docling_basics/目录提供了一条从零到一的渐进学习路径四个脚本各解决一个独立主题脚本主题核心 API01_simple_pdf.py单个 PDF 转 MarkdownDocumentConverter、export_to_markdown()02_multiple_formats.py多格式统一批量转换DocumentConverter可复用实例、异常处理03_audio_transcription.py音频转写Whisper ASRAsrPipeline、AsrPipelineOptions、AudioFormatOption04_hybrid_chunking.pyRAG 混合分块HybridChunker、AutoTokenizer、contextualize()推荐学习顺序与 README 的 Learning Path 一致先跑通基础转换 → 扩展到多格式 → 加入音频 → 最后用混合分块为 RAG 做准备再进入完整 Agent。第一步单个 PDF 转 Markdown最小可用代码01_simple_pdf.py 是 Docling 使用的最简示范完整逻辑如下from docling.document_converter import DocumentConverter # 指向仓库 documents/ 目录下的示例 PDF pdf_path ../documents/technical-architecture-guide.pdf # 1. 初始化转换器主入口 converter DocumentConverter() # 2. 转换 PDF得到 ConversionResult result converter.convert(pdf_path) # 3. 导出为标准 Markdown markdown result.document.export_to_markdown() # 4. 保存结果 with open(output/output_simple.md, w, encodingutf-8) as f: f.write(markdown)运行方式python 01_simple_pdf.py脚本会在终端打印 Markdown 的前 1000 个字符作为预览并将完整结果写入docling_basics/output/output_simple.md。输出质量为什么复杂 PDF 也能扛住Docling 的价值在复杂版面下才会完全显现。查看仓库中真实生成的 output_simple.md 可以看到一份包含文档头信息、章节编号、无序列表、代码块配置示例和 Markdown 表格的 PDF 被完整还原为结构化 Markdown例如表格被转成了标准管道符表格、代码块保留了围栏格式。也就是说表格、多栏布局、复杂排版都由 Docling 自动处理无需任何配置得到的干净 Markdown 可以直接进入下游分块和检索环节。第二步多格式统一转换与批量处理统一 API 处理异构文档02_multiple_formats.py 演示了 Docling 的核心设计理念所有格式共享同一套 API不需要为每种格式编写专门的解析代码。脚本定义的process_document()函数展示了通用处理模式def process_document(file_path: str, converter: DocumentConverter) - dict: try: # 统一转换 result converter.convert(file_path) # 统一导出 markdown result.document.export_to_markdown() # 记录元信息并保存 output_file foutput/output_{Path(file_path).stem}.md with open(output_file, w, encodingutf-8) as f: f.write(markdown) return {file: Path(file_path).name, status: Success, markdown_length: len(markdown), output_file: output_file} except Exception as e: return {file: Path(file_path).name, status: Failed, error: str(e)}主流程一次性处理四种文档documents [ ../documents/technical-architecture-guide.pdf, ../documents/q4-2024-business-review.pdf, ../documents/meeting-notes-2025-01-08.docx, ../documents/company-overview.md, ] converter DocumentConverter() # 只初始化一次全程复用两个关键实践点复用转换器实例DocumentConverter初始化后可在整个批处理中复用避免重复加载模型与配置这是批量处理大量文档时的性能关键逐文件异常隔离process_document用try/except包裹单个文件失败只记录该文件的status: Failed与错误信息不影响后续文件主流程最后会打印汇总成功数量、每份文档的 Markdown 长度与预览。这种批量 容错 汇总的结构与仓库主管线 ingestion/ingest.py 中_find_document_files()支持的通配格式*.md、*.pdf、*.docx、*.pptx、*.xlsx、*.html、*.mp3等以及逐文件try/except记录IngestionResult的容错思路一脉相承。第三步音频转写Whisper ASR让知识库听得到ASR 管线配置03_audio_transcription.py 演示了如何把音频MP3、WAV、M4A、FLAC变成带时间戳的文本使播客、访谈、会议录音可被语义检索。核心配置代码from docling.document_converter import DocumentConverter, AudioFormatOption from docling.datamodel.pipeline_options import AsrPipelineOptions from docling.datamodel import asr_model_specs from docling.datamodel.base_models import InputFormat from docling.pipeline.asr_pipeline import AsrPipeline pipeline_options AsrPipelineOptions() pipeline_options.asr_options asr_model_specs.WHISPER_TURBO # Whisper Turbo 模型 converter DocumentConverter( format_options{ InputFormat.AUDIO: AudioFormatOption( pipeline_clsAsrPipeline, # 音频走专用 ASR 管线 pipeline_optionspipeline_options, ) } ) result converter.convert(Path(audio_path).resolve()) # 注意音频需传 Path 对象 transcript result.document.export_to_markdown() # 导出带时间戳的 Markdown前置条件FFmpeg音频处理依赖 FFmpeg按操作系统安装WindowsChocolateychoco install ffmpegWindowsCondaconda install -c conda-forge ffmpegmacOSbrew install ffmpegLinuxDebian/Ubuntuapt-get install ffmpegLinuxRedHat/CentOSyum install ffmpeg脚本运行python 03_audio_transcription.py时间戳输出与容错提示仓库真实输出 output_transcript.md 展示了时间戳格式[time: 0.0-5.96] Welcome to Neuroflow AI, where were transforming how businesses work through intelligent automation. [time: 6.26-11.44] Founded in 2023, we specialize in practical AI solutions that deliver measurable results.脚本还会统计[time:前缀出现的次数即带时间戳的片段数量。若 FFmpeg 未安装converter.convert()会抛出FileNotFoundError脚本会打印安装指引其他异常则会提示检查 FFmpeg 是否在 PATH、音频文件是否存在、格式是否受支持。主管线 ingestion/ingest.py 中的_transcribe_audio()方法使用了完全相同的配置模式WHISPER_TURBOAsrPipelinePath对象传参并在转写失败时返回错误占位文本而不是中断整个摄取流程。仓库主 README 补充说明该模型为openai/whisper-large-v3-turbo多语言支持 90 种语言输出格式即[time: 0.0-4.0] Transcribed text here。第四步HybridChunker 混合分块——RAG 检索质量的基石为什么不能直接按字符切分朴素文本切分按固定字符数截断会切断句子、段落乃至表格的语义边界导致 Embedding 结果语义混乱、检索召回质量下降。HybridChunker的解决思路是在尊重文档结构段落、章节、表格的前提下做 token 感知切分既保证语义连贯又确保每个 chunk 落在 Embedding 模型的 token 上限内。完整分块流程04_hybrid_chunking.py 的四步流程from docling.chunking import HybridChunker from transformers import AutoTokenizer # Step 1: 先转换文档得到 DoclingDocument结构信息保留在这里 converter DocumentConverter() doc converter.convert(file_path).document # Step 2: 初始化 tokenizer与 Embedding 模型配套 model_id sentence-transformers/all-MiniLM-L6-v2 tokenizer AutoTokenizer.from_pretrained(model_id) # Step 3: 创建 HybridChunkermax_tokens 默认 512 chunker HybridChunker( tokenizertokenizer, max_tokens512, # 典型 Embedding 模型上限 merge_peersTrue # 合并相邻的小块避免碎片化 ) # Step 4: 生成 chunkschunk 对象含 text 与 meta chunk_iter chunker.chunk(dl_docdoc) chunks list(chunk_iter)运行python 04_hybrid_chunking.py上下文注入contextualize()教程脚本的save_chunks()展示了另一个关键 API——chunker.contextualize(chunkchunk)它会把该 chunk 的标题层级heading hierarchy和文档上下文注入文本使每个 chunk 独立成文时依然携带来源章节信息。仓库真实输出 output_chunks.txt 可以看到每个 CHUNK 都以1. System Overview3.1 API Gateway这类章节标题开头表格内容被完整保留在所属 chunk 中——这正是metadata preservation for context的直接体现。块级统计分析脚本的analyze_chunks()会对结果做统计总 chunk 数、总 token 数、平均 token、最小/最大 token以及按0-128、128-256、256-384、384-512区间的 token 分布帮助判断分块是否契合 Embedding 模型限制。这类量化验证对调优 RAG 检索质量非常实用。生产实现从教程到完整管线教程中的 HybridChunker 用法在 ingestion/chunker.py 中被封装为生产级实现DoclingHybridChunker初始化时加载sentence-transformers/all-MiniLM-L6-v2tokenizer并以max_tokens512、merge_peersTrue创建HybridChunkerchunker.py分块后调用chunker.contextualize()生成带标题上下文的文本再统计真实 token 数并写入DocumentChunk元数据chunk_method: hybrid、has_context: true、token_count等当没有 DoclingDocument如纯文本、转写失败的音频或 HybridChunker 抛错时会降级到_simple_fallback_chunk()的滑动窗口切分字符上限 1000、重叠 200、按句号/问号/感叹号/换行找边界保证管线永不中断工厂函数create_chunker()依据use_semantic_splitting在DoclingHybridChunker与SimpleChunker按段落聚合之间切换。这正是 README 所说的教程展示的是构建块完整管线展示的是全貌。进阶特性让文档理解更进一步README 还介绍了三个可选的增强配置均通过PdfPipelineOptions打开。图片分类与描述IBM Granite Vision为 PDF 增加视觉理解能力自动生成图片、图表与示意图的描述文本from docling.datamodel.pipeline_options import ( PdfPipelineOptions, granite_picture_description ) from docling.datamodel.base_models import InputFormat from docling.document_converter import DocumentConverter, PdfFormatOption pipeline_options PdfPipelineOptions() pipeline_options.do_picture_description True pipeline_options.picture_description_options granite_picture_description converter DocumentConverter( format_options{ InputFormat.PDF: PdfFormatOption(pipeline_optionspipeline_options) } )价值在于视觉内容架构图、图表在 RAG 系统中变得可被文本检索弥补了纯文本转换对图片内容无能为力的短板。代码理解面向含代码的技术文档pipeline_options PdfPipelineOptions() pipeline_options.do_code_enrichment True # 启用代码语法理解启用后保留语法高亮、识别代码块并做语言检测适合处理技术手册、API 文档类 PDF。表格结构识别TableFormer用 TableFormer 提升复杂表格解析精度from docling.datamodel.pipeline_options import TableFormerMode pipeline_options PdfPipelineOptions() pipeline_options.table_structure_mode.mode TableFormerMode.ACCURATE适用于复杂表格抽取、单元格关系保留与跨页表格处理场景。注意 README 原文此处写作table_structure_options.mode实际参数名以所安装 Docling 版本的PdfPipelineOptions定义为准代码中的模式枚举名为TableFormerMode。从 Docling 基础到完整 RAG Agent教程演示的每个能力都能在完整 RAG Agent 中找到对应位置学习路径可概括为学习 → 理解 → 应用 → 定制摄取阶段ingestion/ingest.py 的_find_document_files()按扩展名自动发现文档_read_document()依据格式分流——Docling 支持的格式PDF、Office、HTML走DocumentConverter转 Markdown音频走 Whisper ASR 转写纯文本直接读取分块阶段DoclingHybridChunker使用与教程相同的HybridChunker tokenizer 组合输出带上下文的 chunk向量化与存储embedder.py 生成 OpenAI Embedding写入 PostgreSQL 的documents/chunks表schema.sql 定义了 1536 维向量列与match_chunks()相似度检索函数检索问答rag_agent.py 中search_knowledge_base工具对查询生成 Embedding 后调用match_chunks($1::vector, $2)返回带来源引用的结果cli.py 提供流式交互界面。安装与环境准备所有示例都需要 Docling 及其依赖可按需选择安装粒度# 安装基础 Docling pip install docling # 混合分块与 ASR 所需对应示例 3、4 pip install transformers openai-whisper hf-xet # 或一次性全装 pip install docling transformers openai-whisper hf-xet仓库还提供基于uv的完整环境见根目录pyproject.toml与uv.lock主项目可执行uv run python -m ingestion.ingest --documents documents/摄取文档、uv run python cli.py启动问答 CLI。示例文件与预期输出结构教程使用的示例文档位于仓库 documents/ 目录PDFtechnical-architecture-guide.pdf、q4-2024-business-review.pdf、client-review-globalfinance.pdfWordmeeting-notes-2025-01-08.docx、meeting-notes-2025-01-15.docxMarkdowncompany-overview.md、team-handbook.md、mission-and-goals.md、implementation-playbook.md音频Recording1.mp3~Recording4.mp3运行示例后输出统一落在 docling_basics/output/output_simple.mdPDF 转换、output_company-overview.md、output_meeting-notes-2025-01-08.md、output_q4-2024-business-review.md、output_technical-architecture-guide.md多格式转换、output_transcript.md音频转写、output_chunks.txt分块结果与 README 中 Expected File Structure 描述一致。关键要点回顾为什么选 Docling免去自研文档处理代码能处理传统文本抽取会失效的复杂格式所有格式输出统一何时使用 Docling构建含多种文档类型的 RAG 系统、处理复杂版面 PDF、需要把音频纳入知识库、在自动化管线中处理 Office 文档Docling 如何融入 RAG统一转成干净 Markdown →HybridChunker按结构做 token 感知分块 → 保留结构、元数据与标题上下文 → 跨所有文档类型实现语义检索。下一步建议直接运行四个示例脚本然后对照 ingestion/ingest.py、rag_agent.py 与 cli.py 阅读完整实现把教程中的每个构建块放到生产管线的真实位置中验证。【免费下载链接】ottomator-agentsAll the open source AI Agents hosted on the oTTomator Live Agent Studio platform!项目地址: https://gitcode.com/GitHub_Trending/ot/ottomator-agents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表