MarkTechPost新闻
使用deepDoctection构建端到端文档智能流水线
本教程介绍如何使用deepDoctection 1.2.x构建文档智能流水线,涵盖布局分析、OCR、表格识别、阅读顺序重建和结构化导出。通过配置DocLayNet布局模型、Table Transformer和DocTR OCR,并自定义实体识别组件,最终生成适合RAG系统的JSONL数据。
在本教程中,我们使用 deepDoctection 1.2.x 实现一个文档智能流水线,该流水线在单一工作流中整合了版面检测、表格结构识别、OCR、阅读顺序重建、标注链接和结构化导出。我们使用基于 DocLayNet 的版面检测、Table Transformer 结构识别和 DocTR OCR 显式配置分析器,然后检查生成的 Page 对象,以理解 deepDoctection 如何表示文本、图形、表格、关系、来源信息和阅读顺序。我们还通过注册自定义对象类型并实现我们自己的 PipelineComponent 来扩展框架,用于提取货币和日期实体,同时根据文档的表格特征对文档进行分类。最后,我们使用 ServiceFactory 手动组装自定义流水线,探索过滤和服务回滚,序列化处理后的页面,并将文档标注转换为适合下游 RAG 和检索系统的有序 JSONL 块。
!pip install -q "deepdoctection" "transformers>=5.2.0" "timm" "python-doctr" "pdfplumber" "networkx" "lxml"
import os
os.environ["DD_USE_TORCH"] = "True"
os.environ["DPI"] = "200"
os.environ["LOG_LEVEL"] = "INFO"
os.environ["ENABLE_DYNAMIC_OBJECT_TYPES"] = "False"
import json, re, textwrap
from pathlib import Path
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import HTML, display
import deepdoctection as dd
print("deepdoctection:", dd.__version__)
import transformers.integrations.peft as _hf_peft
if _hf_peft.is_peft_available():
_hf_peft.is_peft_available = lambda: False
print("patched: PEFT adapter lookup disabled for from_pretrained")
!mkdir -p /content/docs /content/imgs
!wget -q -O /content/docs/paper.pdf \
点击访问 2312.13560.pdf
!wget -q -O /content/imgs/finance.png \
https://raw.githubusercontent.com/deepdoctection/notebooks/main/sample/finance/1bcac3899c9cb1c0b0f650b1431d3d52_7.png
PDF = Path("/content/docs/paper.pdf")
PNG = Path("/content/imgs/finance.png")
OUT = Path("/content/out"); OUT.mkdir(exist_ok=True)
def show(img, w=16):
if img is None: return
plt.figure(figsize=(w, w * 1.3)); plt.axis("off"); plt.imshow(img); plt.show()
def analyze_any(pipe, path, **kw):
"""
根据输入是目录、PDF 还是单个图像文件进行正确分发。
DoctectionPipe 可以从磁盘流式处理目录或 PDF,但*单个*
图像没有读取器——path= 仅提供文件名/来源信息,而
像素必须通过 bytes= 传入。否则你会得到:
ValueError: When passing a path to a single image, bytes of the image
must be passed
"""
path = Path(path)
if path.is_dir():
kw.setdefault("file_type", [".jpg", ".png", ".jpeg", ".tif"])
return pipe.analyze(path=path, **kw)
if path.suffix.lower() == ".pdf":
return pipe.analyze(path=path, **kw)
if path.suffix.lower() in (".png", ".jpg", ".jpeg", ".tif"):
return pipe.analyze(path=path, bytes=path.read_bytes(), **kw)
raise ValueError(f"unsupported input: {path}")我们安装所需的 deepDoctection 依赖项,配置其运行时环境,并为 Transformers 和 PEFT 应用兼容性补丁。我们下载本教程中使用的示例 PDF 和图像文件,并准备输出目录。我们还定义了辅助函数,用于可视化图像以及一致地分析目录、PDF 和单个图像文件。
我们检查 deepDoctection 的模型注册表,以确认布局模型及其支持的文档类别。我们显式配置分析器,使其结合布局检测、表格分割、DocTR OCR、单词匹配、阅读顺序重建和布局链接。然后初始化分析器,并检查其流水线组件及生成的标注类型。
df = analyze_any(analyzer, PDF, session_id="tutorial01", max_datapoints=3)
df.reset_state()
pages = list(df)
print(f"\nparsed {len(pages)} pages")
page = pages[0]
show(page.viz(show_figures=True, show_residual_layouts=True, show_table_structure=True))
print("== narrative text ==")
print(textwrap.fill(page.text[:900], 110))
print("\n== layout blocks in reading order ==")
for doc_id, img_id, pno, ann_id, order, cat, txt in page.chunks[:12]:
print(f"[{order:>3}] {str(cat):<15} {txt[:70]!r}")
print("\n== category histogram ==")
print(Counter(a.category_name for a in page.get_annotation()))
for fig in page.figures:
linked = fig.get_relationship("layout_link")
print("figure", fig.annotation_id[:8], "-> caption ids:", [i[:8] for i in linked])
if page.words:
w = page.words[0]
print("\nword:", w.characters, "| service:", w.service_id,
"| model:", w.model_id, "| bbox:", [round(x) for x in w.bbox])
tbl_pages = [p for p in pages if p.tables]
if tbl_pages:
t = tbl_pages[0].tables[0]
print(f"table {t.number_of_rows}x{t.number_of_columns}, "
f"max_row_span={t.max_row_span}, max_col_span={t.max_col_span}")
display(HTML(t.html))
for row in t.csv[:5]:
print([c[:22] for c in row])
for c in t.cells[:5]:
print(f" r{c.row_number} c{c.column_number} "
f"(span {c.row_span}x{c.column_span}) {c.text[:40]!r}")
else:
print("no table on these pages — the finance.png sample below has one")我们在示例 PDF 上运行配置好的分析器,并从惰性数据流中物化生成的页面。我们检查叙述文本、阅读顺序块、标注类别、图形-标题关系、单词来源和边界框。我们还通过 HTML、CSV 和单个单元格表示访问检测到的表格,以检查其结构化输出。
我们注册自定义对象类型,用于提取货币提及、日期提及和文档风格分类。我们实现了一个自定义的 deepDoctection 流水线组件,用于分析页面文本和表格覆盖率,以生成这些页面级摘要。然后,我们将自定义摘要字段暴露为 Page 属性,以便可以直接从处理后的文档中访问它们。
from deepdoctection.analyzer import cfg, ServiceFactory
cfg.freeze(False)
cfg.USE_TABLE_SEGMENTATION = True
cfg.freeze(True)
components = []
layout_detector = ServiceFactory.build_layout_detector(cfg, mode="LAYOUT")
components.append(ServiceFactory.build_layout_service(cfg, detector=layout_detector, mode="LAYOUT"))
components.append(ServiceFactory.build_layout_nms_service(cfg))
item_detector = ServiceFactory.build_layout_detector(cfg, mode="ITEM")
components.append(ServiceFactory.build_sub_image_service(cfg, detector=item_detector, mode="ITEM"))
components.append(ServiceFactory.build_table_segmentation_service(cfg, detector=item_detector))
word_detector = ServiceFactory.build_doctr_word_detector(cfg)
components.append(ServiceFactory.build_doctr_word_detector_service(word_detector))
components.append(ServiceFactory.build_text_extraction_service(cfg, ServiceFactory.build_ocr_detector(cfg)))
components.append(ServiceFactory.build_word_matching_service(cfg))
components.append(ServiceFactory.build_text_order_service(cfg))
components.append(EntityAndFlavourService())
custom_pipe = dd.DoctectionPipe(pipeline_component_list=components)
print("\ncustom pipeline:", list(custom_pipe.get_pipeline_info().values()))
df2 = analyze_any(custom_pipe, PNG)
df2.reset_state()
fin_page = next(iter(df2))
print("flavour :", fin_page.doc_flavour)
print("money :", fin_page.money_mentions[:10])
print("dates :", fin_page.date_mentions[:10])
show(fin_page.viz(show_table_structure=True), w=13)
def skip_if_no_table(dp: dd.Image) -> bool:
return "table" not in {a.category_name for a in dp.get_annotation()}
components[-1].set_inbound_filter(skip_if_no_table)
det_sid = next(sid for sid, n in analyzer.get_pipeline_info().items()
if n.startswith("image_doctr"))
det_comp = analyzer.get_pipeline_component(service_id=det_sid)
df_undo = det_comp.undo(dd.DataFromList([p.base_image for p in pages]))
df_undo.reset_state()
undone = list(df_undo)
print("annotations before/after undo:",
len(pages[0].get_annotation()),
len(dd.Page.from_image(undone[0]).get_annotation()))我们使用ServiceFactory手动组装了一个deepDoctection流水线,将版面分析、表格处理、OCR、文本排序以及我们的自定义组件结合在一起。我们在金融文档图像上执行了这个自定义流水线,并检查了检测到的类别、货币金额、日期和表格结构。我们还应用了一个入站过滤器,并演示了如何撤销由所选DocTR服务生成的标注。
for i, p in enumerate(pages):
p.save(image_to_json=False, path=OUT / f"page_{i}.json")
restored = dd.Page.from_file(str(OUT / "page_0.json"))
print("round-trip:", len(restored.get_annotation()), "of",
len(pages[0].get_annotation()), "annotations restored")
records = []
for p in pages:
for doc_id, img_id, pno, ann_id, order, cat, txt in p.chunks:
if txt and txt.strip():
records.append({"document_id": doc_id, "page": pno, "order": order,
"category": str(cat), "annotation_id": ann_id, "text": txt})
for t in p.tables:
records.append({"document_id": p.document_id, "page": p.page_number,
"order": -1, "category": "table_html",
"annotation_id": t.annotation_id, "text": t.html})
(OUT / "chunks.jsonl").write_text("\n".join(json.dumps(r) for r in records))
print(f"\n{len(records)} chunks -> {OUT/'chunks.jsonl'}")
print(json.dumps(records[0], indent=2)[:400])我们将每个处理后的页面序列化为JSON,同时保留其结构标注,而不嵌入原始图像数据。我们重新加载了一个已保存的页面,并比较标注数量,以验证结构信息在序列化后是否完好。最后,我们将叙事性文本块和表格HTML转换为JSONL记录,这些记录可以直接用于RAG、检索以及下游文档处理流水线。
总之,我们深入理解了deepDoctection如何将多个文档分析模型和基于规则的服務编排成一个可配置的处理流水线。我们不再仅仅运行预定义的分析器,而是通过检查模型注册、控制各个服务、访问结构化的页面级标注、提取表格、创建自定义摘要元数据以及组合我们自己的流水线阶段,实现了更进一步的探索。我们还研究了服务过滤和撤销操作如何影响标注,从而对复杂的文档处理工作流有了更精细的控制。最后,我们将处理后的文档结构序列化,生成了可直接用于RAG的文本块,为构建文档搜索、知识提取、检索增强生成以及其他面向生产的文档AI应用奠定了可复用的基础。
想与我们合作推广您的GitHub仓库、Hugging Face页面、产品发布或网络研讨会吗?请联系我们。
Sana Hassan是Marktechpost的咨询实习生,也是印度马德拉斯理工学院(IIT Madras)的双学位学生,热衷于将技术和AI应用于解决现实世界的挑战。他对解决实际问题有着浓厚的兴趣,为AI与现实解决方案的交汇带来了全新的视角。
译文已达到本站中文翻译的字数上限,剩余内容请查看原文。