如何用 Docling Parse 建立版面感知的文件智慧解析流程
重點摘要
本教學將帶領您使用 Docling Parse 建立一套流程,以精細的結構層級分析 PDF 文件。我們首先準備穩定的 Python 環境,處理常見的 Colab 相依性問題,並產生一份包含文字、欄位、表格內容、向量圖形及內嵌圖片的自訂多頁 PDF。接著利用 Docling Parse 提取具有頁面座標的字詞、字元與行,繪製視覺疊加層,並將結果儲存為結構化的 JSON 與 CSV 檔案。透過這套流程,我們將瞭解低階 PDF 解析如何支援文件 AI 任務,例如版面分析、閱讀順序重建、表格感知處理,以及可檢索的文件準備。設定 Docling Parse Colab 環境與相依性 複製程式碼 已複製 使用差異
In this tutorial, we build a workflow for using Docling Parse to analyze PDF documents at a detailed structural level. We start by preparing a stable Python environment, handling common Colab dependency issues, and generating a custom multi-page PDF with text, columns, table-like content, vector shapes, and an embedded image. We then use Docling Parse to extract words, characters, and lines with page-level coordinates, render visual overlays, and save the results into structured JSON and CSV files. Through this workflow, we see how low-level PDF parsing can support document AI tasks such as layout analysis, reading-order reconstruction, table-aware processing, and retrieval-ready document preparation. Setting Up the Docling Parse Colab Environment and Dependencies Copy CodeCopiedUse a different Browserimport os, sys, subprocess, textwrap, json, time, shutil from pathlib import Path def run(cmd): print(f"\n$ {cmd}") return subprocess.run(cmd, shell=True, text=True, capture_output=False) run(f'{sys.executable} -m pip install -q --no-cache-dir -U "pillow>=10.4.0,<12" reportlab pandas matplotlib docling-core docling-parse') try: from PIL import Image, ImageDraw except ImportError: print("\nPillow import failed because Colab has a mixed PIL installation.") print("Reinstalling Pillow and restarting runtime. After restart, run this same cell again.") run(f'{sys.executable} -m pip uninstall -y pillow PIL') run(f'{sys.executable} -m pip install -q --no-cache-dir --force-reinstall "pillow>=10.4.0,<12"') os.kill(os.getpid(), 9) import pandas as pd import matplotlib.pyplot as plt from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.platypus import Table, TableStyle from reportlab.pdfgen import canvas from docling_core.types.doc.page import TextCellUnit from docling_parse.pdf_parser import DoclingPdfParser print("Environment ready.") print("Python:", sys.version.split()[0]) WORKDIR = Path("/content/docling_parse_advanced_tutorial") WORKDIR.mkdir(parents=True, exist_ok=True) PDF_PATH = WORKDIR / "advanced_docling_parse_demo.pdf" OUT_DIR = WORKDIR / "outputs" OUT_DIR.mkdir(exist_ok=True) DEMO_IMAGE_PATH = WORKDIR / "demo_bitmap.png" We set up the Colab environment by installing Docling Parse, Docling Core, Pillow, ReportLab, Pandas, and Matplotlib. We also handle the Pillow import issue safely so the notebook can recover if Colab has a broken or mixed PIL installation. We then define the working directory, output folder, PDF path, and image path that we use throughout the tutorial. Generating a Multi-Element Test PDF for Parser Evaluation Copy CodeCopiedUse a different Browserdef create_demo_image(path): img = Image.new("RGB", (320, 180), "white") draw = ImageDraw.Draw(img) draw.rectangle([20, 20, 300, 160], outline="black", width=3) draw.ellipse([55, 45, 145, 135], outline="black", width=4) draw.line([180, 140, 285, 45], fill="black", width=4) draw.text((45, 145), "Embedded bitmap image", fill="black") img.save(path) create_demo_image(DEMO_IMAGE_PATH) def build_pdf(pdf_path): c = canvas.Canvas(str(pdf_path), pagesize=A4) width, height = A4 c.setFont("Helvetica-Bold", 20) c.drawString(60, height - 70, "Docling Parse Advanced PDF Parsing Tutorial") c.setFont("Helvetica", 11) intro = ( "This generated document is designed for testing text extraction, coordinate parsing, " "line grouping, vector path detection, bitmap resources, and layout-aware reconstruction." ) text_obj = c.beginText(60, height - 105) text_obj.setLeading(15) for line in textwrap.wrap(intro, width=90): text_obj.textLine(line) c.drawText(text_obj) c.setFont("Helvetica-Bold", 14) c.drawString(60, height - 170, "1. Two-column text region") left_para = ( "The left column contains compact explanatory text. A parser should expose words, " "characters, and line-level cells along with coordinates. These coordinates allow us " "to reconstruct reading order and inspect the spatial structure of a page." ) right_para = ( "The right column contains a separate paragraph. In document AI pipelines, layout " "features are useful for retrieval, table extraction, chunking, and downstream RAG " "applications where page position can matter." ) y_start = height - 200 left_text = c.beginText(60, y_start) left_text.setFont("Helvetica", 10) left_text.setLeading(13) for line in textwrap.wrap(left_para, width=42): left_text.textLine(line) c.drawText(left_text) right_text = c.beginText(325, y_start) right_text.setFont("Helvetica", 10) right_text.setLeading(13) for line in textwrap.wrap(right_para, width=42): right_text.textLine(line) c.drawText(right_text) c.setStrokeColor(colors.darkblue) c.setLineWidth(2) c.rect(55, height - 315, 225, 130, stroke=1, fill=0) c.rect(320, height - 315, 225, 130, stroke=1, fill=0) c.setStrokeColor(colors.darkgreen) c.setLineWidth(3) c.circle(140, height - 390, 40, stroke=1, fill=0) c.line(220, height - 430, 310, height - 355) c.setFont("Helvetica-Bold", 14) c.setFillColor(colors.black) c.drawString(60, height - 470, "2. Simple table-like structure") data = [ ["Section", "Signal", "Expected parser behavior"], ["Text", "Words and lines", "Return text cells with coordinates"], ["Vector", "Boxes and lines", "Expose page path/vector resources"], ["Bitmap", "Embedded image", "Expose or render image resources"], ] table = Table(data, colWidths=[100, 130, 260]) table.setStyle(TableStyle([ ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), ("GRID", (0, 0), (-1, -1), 0.7, colors.black), ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), ("FONTSIZE", (0, 0), (-1, -1), 9), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ])) table.wrapOn(c, width, height) table.drawOn(c, 60, height - 590) c.setFont("Helvetica", 9) c.drawString(60, 55, "Page 1: generated programmatic PDF with text, table-like layout, and vector paths.") c.showPage() c.setFont("Helvetica-Bold", 18) c.drawString(60, height - 70, "Page 2: Bitmap, Dense Text, and Reading Order") c.setFont("Helvetica", 10) dense = ( "This page includes an embedded bitmap image and several short blocks of text. " "We use it to test whether rendering works, whether the parser preserves page-level " "coordinates, and whether our own reconstruction logic can group words into lines." ) y = height - 105 for para_idx in range(4): tx = c.beginText(60, y) tx.setFont("Helvetica", 10) tx.setLeading(13) for line in textwrap.wrap(f"Block {para_idx + 1}: {dense}", width=92): tx.textLine(line) c.drawText(tx) y -= 70 c.drawImage(str(DEMO_IMAGE_PATH), 110, height - 510, width=320, height=180, preserveAspectRatio=True) c.setStrokeColor(colors.red) c.setLineWidth(2) c.roundRect(95, height - 525, 350, 210, 10, stroke=1, fill=0) c.setFillColor(colors.black) c.setFont("Helvetica-Bold", 12) c.drawString(60, height - 570, "Coordinate-aware extraction lets us keep page, text, and position together.") c.setFont("Helvetica", 9) c.drawString(60, 55, "Page 2: embedded bitmap image and multiple text blocks.") c.save() build_pdf(PDF_PATH) print("Created PDF:", PDF_PATH) We generate a small bitmap image and create a custom two-page PDF for testing Docling Parse. We add text blocks, two-column content, vector shapes, table-like content, and an embedded image so the parser has multiple document elements to process. We use the generated PDF as a controlled input to check text extraction, layout structure, rendering, and coordinate-aware parsing. Extracting Word, Character, and Line Cells with Docling Parse Copy CodeCopiedUse a different Browserdef safe_to_dict(obj, max_depth=2): if obj is None: return None if isinstance(obj, (str, int, float, bool)): return obj if isinstance(obj, (list, tuple)): return [safe_to_dict(x, max_depth=max_depth - 1) for x in obj[:50]] if isinstance(obj, dict): return { str(k): safe_to_dict(v, max_depth=max_depth - 1) for k, v in list(obj.items())[:50] } if hasattr(obj, "model_dump"): try: return obj.model_dump() except Exception: pass if hasattr(obj, "__dict__") and max_depth > 0: try: return { k: safe_to_dict(v, max_depth=max_depth - 1) for k,
Related
相關文章
Liquid AI Introduces LFM2.5-Embedding-350M and LFM2.5-ColBERT-350M: Dense Bi-Encoder and Late-Interaction Models for Fast Multilingual Search Across 11 Languages
This week, Liquid AI released two new retrieval models. They are LFM2.5-ColBERT-350M and LFM2.5-Embedding-350M. Both hold 350M parameters. Both are the first bidirectional members of the LFM family. They build on LFM2.5-350M-Base, released in March. The pair targets fast multilingual and cross-lingual search across 11 languages. Their footprint is small enough to run almost anywhere. Both are available now on Hugging Face under the LFM Open License v1.0. LFM2.5 Retrievers The two models share one backbone but represent text differently. LFM2.5-Embedding-350M is a dense bi-encoder. It turns each document into a single vector. Pick it when you want the fastest search and the smallest, cheapest index. LFM2.5-ColBERT-350M is a late-interaction model. It converts each token into a vector rather
Perplexity Launches Brain, a Self-Improving Memory System That Builds a Context Graph of an Agent’s Work and Learns Overnight
Most AI memory remembers the user. It stores your preferences, your tastes, and your role. Perplexity is taking a different path. Today, Perplexity launched Brain, a self-improving memory system for its agent product, Computer. Brain does not focus on remembering you. It remembers what the agent did. That reframes what memory in AI is for. What is Perplexity‘s Brain Brain is a self-improving memory system. It builds a context graph of the work Computer performs. At set intervals, such as overnight, Brain reviews that graph. It then teaches itself how to do the work better. The idea is straightforward. The more work you do, the more efficient Brain makes your Computer. Brain is rolling out today to Perplexity Max and Enterprise Max subscribers in Research Preview. Two Axes of AI Memory Perp

智譜新高,MiniMax承壓,“大模型雙雄”命運殊途
這篇消息聚焦「智譜新高,MiniMax承壓,“大模型雙雄”命運殊途」。原始導語提到:大模型在被市場重新定價 從 AI 情報角度來看,這類內容值得關注其背後的技術進展、產品落地、產業競爭與後續市場影響。

華為昇騰 0 Day 支持智譜 GLM-5.2 模型,提供全面推理優化
華為昇騰 AI 宣佈在智譜開源 GLM-5.2 大模型當天即完成深度推理優化。通過 MOE 大融合算子、通信計算融合、高併發調度等七項關鍵技術,顯著提升編程和長程任務的處理效率,現已支持 A3 系列產品部署。#AI 大模型# #國產算力#
企業AI轉型再添利器:青雲科技算力雲接入 MiniMax-M3 模型
企業AI落地面臨高效低成本難題。青雲科技旗下基石智算平臺接入國產開源大模型MiniMax-M3,提供新算力支持。MiniMax-M3以卓越上下文處理能力等三大核心技術見長,依託自研架構,助企業便捷部署AI業務。
阿里開源統一科學大模型 LOGOS,僅用五十六分之一參數超越微軟
阿里 ATH-Token Foundry 聯閤中國人民大學高瓴人工智能學院開源科學基礎模型 LOGOS。該模型採用統一科學語法與純序列建模範式,在六大科學任務上匹配或超越傳統專用方法。其中 LOGOS-1B 僅 1B 參數,即展現出極高效率,性能超越參數量達 8×7B 的微軟模型。