PyMuPDF4LLMLoader
本笔记本提供了快速入门 PyMuPDF4LLM 文档加载器 的概览。如需了解所有 PyMuPDF4LLMLoader 功能和配置的详细文档,请访问 GitHub 仓库。
概览
集成详情
| 类 | 包 | 本地 | 可序列化的 | JS 支持 |
|---|---|---|---|---|
| PyMuPDF4LLMLoader | langchain_pymupdf4llm | ✅ | ❌ | ❌ |
加载器功能
| 源 | 文档延迟加载 | 原生异步支持 | 提取图像 | 提取表格 |
|---|---|---|---|---|
| PyMuPDF4LLMLoader | ✅ | ❌ | ✅ | ✅ |
设置
要访问 PyMuPDF4LLM 文档加载器,您需要安装 langchain-pymupdf4llm 集成包。
凭据
使用 PyMuPDF4LLMLoader 无需任何凭证。
要启用模型调用的自动跟踪,请设置您的 LangSmith API 密钥:
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
安装
安装 langchain_community 和 langchain-pymupdf4llm。
%pip install -qU langchain_community langchain-pymupdf4llm
Note: you may need to restart the kernel to use updated packages.
初始化
现在我们可以实例化模型对象并加载文档:
from langchain_pymupdf4llm import PyMuPDF4LLMLoader
file_path = "./example_data/layout-parser-paper.pdf"
loader = PyMuPDF4LLMLoader(file_path)
加载
docs = loader.load()
docs[0]
Document(metadata={'producer': 'pdfTeX-1.40.21', 'creator': 'LaTeX with hyperref', 'creationdate': '2021-06-22T01:27:10+00:00', 'source': './example_data/layout-parser-paper.pdf', 'file_path': './example_data/layout-parser-paper.pdf', 'total_pages': 16, 'format': 'PDF 1.5', 'title': '', 'author': '', 'subject': '', 'keywords': '', 'moddate': '2021-06-22T01:27:10+00:00', 'trapped': '', 'modDate': 'D:20210622012710Z', 'creationDate': 'D:20210622012710Z', 'page': 0}, page_content='\`\`\`\nLayoutParser: A Unified Toolkit for Deep\n\n## Learning Based Document Image Analysis\n\n\`\`\`\n\nZejiang Shen[1] (�), Ruochen Zhang[2], Melissa Dell[3], Benjamin Charles Germain\nLee[4], Jacob Carlson[3], and Weining Li[5]\n\n1 Allen Institute for AI\n\`\`\`\n shannons@allenai.org\n\n\`\`\`\n2 Brown University\n\`\`\`\n ruochen zhang@brown.edu\n\n\`\`\`\n3 Harvard University\n_{melissadell,jacob carlson}@fas.harvard.edu_\n4 University of Washington\n\`\`\`\n bcgl@cs.washington.edu\n\n\`\`\`\n5 University of Waterloo\n\`\`\`\n w422li@uwaterloo.ca\n\n\`\`\`\n\n**Abstract. Recent advances in document image analysis (DIA) have been**\nprimarily driven by the application of neural networks. Ideally, research\noutcomes could be easily deployed in production and extended for further\ninvestigation. However, various factors like loosely organized codebases\nand sophisticated model configurations complicate the easy reuse of important innovations by a wide audience. Though there have been on-going\nefforts to improve reusability and simplify deep learning (DL) model\ndevelopment in disciplines like natural language processing and computer\nvision, none of them are optimized for challenges in the domain of DIA.\nThis represents a major gap in the existing toolkit, as DIA is central to\nacademic research across a wide range of disciplines in the social sciences\nand humanities. This paper introduces LayoutParser, an open-source\nlibrary for streamlining the usage of DL in DIA research and applications. The core LayoutParser library comes with a set of simple and\nintuitive interfaces for applying and customizing DL models for layout detection, character recognition, and many other document processing tasks.\nTo promote extensibility, LayoutParser also incorporates a community\nplatform for sharing both pre-trained models and full document digitization pipelines. We demonstrate that LayoutParser is helpful for both\nlightweight and large-scale digitization pipelines in real-word use cases.\n[The library is publicly available at https://layout-parser.github.io.](https://layout-parser.github.io)\n\n**Keywords: Document Image Analysis · Deep Learning · Layout Analysis**\n\n - Character Recognition · Open Source library · Toolkit.\n\n### 1 Introduction\n\n\nDeep Learning(DL)-based approaches are the state-of-the-art for a wide range of\ndocument image analysis (DIA) tasks including document image classification [11,\n\n')
import pprint
pprint.pp(docs[0].metadata)
{'producer': 'pdfTeX-1.40.21',
'creator': 'LaTeX with hyperref',
'creationdate': '2021-06-22T01:27:10+00:00',
'source': './example_data/layout-parser-paper.pdf',
'file_path': './example_data/layout-parser-paper.pdf',
'total_pages': 16,
'format': 'PDF 1.5',
'title': '',
'author': '',
'subject': '',
'keywords': '',
'moddate': '2021-06-22T01:27:10+00:00',
'trapped': '',
'modDate': 'D:20210622012710Z',
'creationDate': 'D:20210622012710Z',
'page': 0}
懒加载
pages = []
for doc in loader.lazy_load():
pages.append(doc)
if len(pages) >= 10:
# do some paged operation, e.g.
# index.upsert(page)
pages = []
len(pages)
6
from IPython.display import Markdown, display
part = pages[0].page_content[778:1189]
print(part)
# Markdown rendering
display(Markdown(part))
pprint.pp(pages[0].metadata)
{'producer': 'pdfTeX-1.40.21',
'creator': 'LaTeX with hyperref',
'creationdate': '2021-06-22T01:27:10+00:00',
'source': './example_data/layout-parser-paper.pdf',
'file_path': './example_data/layout-parser-paper.pdf',
'total_pages': 16,
'format': 'PDF 1.5',
'title': '',
'author': '',
'subject': '',
'keywords': '',
'moddate': '2021-06-22T01:27:10+00:00',
'trapped': '',
'modDate': 'D:20210622012710Z',
'creationDate': 'D:20210622012710Z',
'page': 10}
metadata 属性至少包含以下键:
- 源
- 页面(如果在页面模式下)
- total_page
- 创建日期
- 创建者
- 生产者
其他元数据特定于每个解析器。 这些信息可能会有所帮助(例如,用于对您的 PDF 进行分类)。
拆分模式与自定义页面分隔符
加载 PDF 文件时,您可以通过两种不同的方式对其进行拆分:
- 按页
- 作为单一文本流
默认情况下,PyMuPDF4LLMLoader 会按页拆分 PDF。
按页提取 PDF。每一页都被提取为一个 langchain Document 对象:
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="page",
)
docs = loader.load()
print(len(docs))
pprint.pp(docs[0].metadata)
16
{'producer': 'pdfTeX-1.40.21',
'creator': 'LaTeX with hyperref',
'creationdate': '2021-06-22T01:27:10+00:00',
'source': './example_data/layout-parser-paper.pdf',
'file_path': './example_data/layout-parser-paper.pdf',
'total_pages': 16,
'format': 'PDF 1.5',
'title': '',
'author': '',
'subject': '',
'keywords': '',
'moddate': '2021-06-22T01:27:10+00:00',
'trapped': '',
'modDate': 'D:20210622012710Z',
'creationDate': 'D:20210622012710Z',
'page': 0}
在此模式下,PDF 按页面拆分,生成的文档元数据包含 page(页码)。但在某些情况下,我们可能希望将 PDF 作为单个文本流进行处理(这样就不会把段落截断)。在这种情况下,您可以使用 single 模式:
将整个 PDF 提取为单个 LangChain Document 对象:
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="single",
)
docs = loader.load()
print(len(docs))
pprint.pp(docs[0].metadata)
1
{'producer': 'pdfTeX-1.40.21',
'creator': 'LaTeX with hyperref',
'creationdate': '2021-06-22T01:27:10+00:00',
'source': './example_data/layout-parser-paper.pdf',
'file_path': './example_data/layout-parser-paper.pdf',
'total_pages': 16,
'format': 'PDF 1.5',
'title': '',
'author': '',
'subject': '',
'keywords': '',
'moddate': '2021-06-22T01:27:10+00:00',
'trapped': '',
'modDate': 'D:20210622012710Z',
'creationDate': 'D:20210622012710Z'}
从逻辑上讲,在此模式下,page(page_number)元数据会消失。以下是明确识别文本流中页面结束位置的方法:
添加自定义 pages_delimiter 以识别single 模式下的页面结束位置:
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="single",
pages_delimiter="\n-------THIS IS A CUSTOM END OF PAGE-------\n\n",
)
docs = loader.load()
part = docs[0].page_content[10663:11317]
print(part)
display(Markdown(part))
默认值 pages_delimiter 是 \n-----\n\n。
但这也可以简单地设为 \n,或 \f 以明确指示页面变更,或 <!-- PAGE BREAK --> 以便在 Markdown 查看器中无缝注入而不产生视觉效果。
从 PDF 中提取图像
您可以使用三种不同的解决方案从 PDF 中提取图像(以文本形式):
- rapidOCR(轻量级光学字符识别工具)
- Tesseract(高精度 OCR 工具)
- 多模态语言模型
结果将插入到页面文本的末尾。
使用 rapidOCR 从 PDF 中提取图像:
%pip install -qU rapidocr-onnxruntime pillow
Note: you may need to restart the kernel to use updated packages.
from langchain_community.document_loaders.parsers import RapidOCRBlobParser
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="page",
extract_images=True,
images_parser=RapidOCRBlobParser(),
)
docs = loader.load()
part = docs[5].page_content[1863:]
print(part)
display(Markdown(part))
请注意,RapidOCR 专为中文和英文设计,不适用于其他语言。
使用 Tesseract 从 PDF 中提取图像:
%pip install -qU pytesseract
Note: you may need to restart the kernel to use updated packages.
from langchain_community.document_loaders.parsers import TesseractBlobParser
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="page",
extract_images=True,
images_parser=TesseractBlobParser(),
)
docs = loader.load()
print(docs[5].page_content[1863:])
使用多模态模型从 PDF 中提取图像:
%pip install -qU langchain_openai
Note: you may need to restart the kernel to use updated packages.
import os
from dotenv import load_dotenv
load_dotenv()
True
from getpass import getpass
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass("OpenAI API key =")
from langchain_community.document_loaders.parsers import LLMImageBlobParser
from langchain_openai import ChatOpenAI
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="page",
extract_images=True,
images_parser=LLMImageBlobParser(
model=ChatOpenAI(model="gpt-4o-mini", max_tokens=1024)
),
)
docs = loader.load()
print(docs[5].page_content[1863:])
从 PDF 中提取表格
使用 PyMUPDF4LLM,您可以从 PDF 中提取Markdown格式的表格:
loader = PyMuPDF4LLMLoader(
"./example_data/layout-parser-paper.pdf",
mode="page",
# "lines_strict" is the default strategy and
# is the most accurate for tables with column and row lines,
# but may not work well with all documents.
# "lines" is a less strict strategy that may work better with
# some documents.
# "text" is the least strict strategy and may work better
# with documents that do not have tables with lines.
table_strategy="lines",
)
docs = loader.load()
part = docs[4].page_content[3210:]
print(part)
display(Markdown(part))
与文件协作
许多文档加载器都涉及解析文件。这些加载器之间的区别通常在于文件的解析方式,而不是文件的加载方式。例如,你可以使用 open 来读取 PDF 或 Markdown 文件的二进制内容,但需要不同的解析逻辑才能将这些二进制数据转换为文本。
因此,将解析逻辑与加载逻辑解耦会有所帮助,这使得无论数据是如何加载的,都可以更轻松地复用给定的解析器。 您可以使用此策略,通过相同的解析参数来分析不同的文件。
from langchain_community.document_loaders import FileSystemBlobLoader
from langchain_community.document_loaders.generic import GenericLoader
from langchain_pymupdf4llm import PyMuPDF4LLMParser
loader = GenericLoader(
blob_loader=FileSystemBlobLoader(
path="./example_data/",
glob="*.pdf",
),
blob_parser=PyMuPDF4LLMParser(),
)
docs = loader.load()
part = docs[0].page_content[:562]
print(part)
display(Markdown(part))
API 参考
有关所有 PyMuPDF4LLMLoader 功能和配置的详细文档,请前往 GitHub 仓库:https://github.com/lakinduboteju/langchain-pymupdf4llm