이 가이드는 PyMuPDF4LLM document loader 시작하기에 대한 간단한 개요를 제공합니다. PyMuPDF4LLMLoader의 모든 기능과 구성에 대한 자세한 문서는 GitHub repository를 참조하세요.

Overview

Integration details

ClassPackageLocalSerializableJS support
PyMuPDF4LLMLoaderlangchain-pymupdf4llm

Loader features

SourceDocument Lazy LoadingNative Async SupportExtract ImagesExtract Tables
PyMuPDF4LLMLoader

Setup

PyMuPDF4LLM document loader에 접근하려면 langchain-pymupdf4llm integration package를 설치해야 합니다.

Credentials

PyMuPDF4LLMLoader를 사용하는 데 필요한 credentials는 없습니다. 모델 호출의 자동 추적을 활성화하려면 LangSmith API key를 설정하세요:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

Installation

langchain-communitylangchain-pymupdf4llm을 설치합니다.
pip install -qU langchain-community langchain-pymupdf4llm
Note: you may need to restart the kernel to use updated packages.

Initialization

이제 model object를 인스턴스화하고 documents를 로드할 수 있습니다:
from langchain_pymupdf4llm import PyMuPDF4LLMLoader

file_path = "./example_data/layout-parser-paper.pdf"
loader = PyMuPDF4LLMLoader(file_path)

Load

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              [email protected]\n\n\`\`\`\n2 Brown University\n\`\`\`\n             ruochen [email protected]\n\n\`\`\`\n3 Harvard University\n_{melissadell,jacob carlson}@fas.harvard.edu_\n4 University of Washington\n\`\`\`\n              [email protected]\n\n\`\`\`\n5 University of Waterloo\n\`\`\`\n              [email protected]\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}

Lazy Load

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 attribute는 최소한 다음 key들을 포함합니다:
  • source
  • page (page mode인 경우)
  • total_page
  • creationdate
  • creator
  • producer
추가 metadata는 각 parser에 따라 다릅니다. 이러한 정보는 (예를 들어 PDF를 분류하는 데) 유용할 수 있습니다.

Splitting mode & custom pages delimiter

PDF 파일을 로드할 때 두 가지 방법으로 분할할 수 있습니다:
  • 페이지별
  • 단일 텍스트 흐름으로
기본적으로 PyMuPDF4LLMLoader는 PDF를 페이지별로 분할합니다.

페이지별로 PDF 추출. 각 페이지는 langchain Document object로 추출됩니다

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}
이 mode에서는 pdf가 페이지별로 분할되고 결과 Documents metadata에는 page (페이지 번호)가 포함됩니다. 하지만 경우에 따라 pdf를 단일 텍스트 흐름으로 처리하고 싶을 수 있습니다 (따라서 일부 단락을 반으로 자르지 않습니다). 이 경우 single mode를 사용할 수 있습니다:

전체 PDF를 단일 langchain Document object로 추출

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'}
논리적으로 이 mode에서는 page (page_number) metadata가 사라집니다. 텍스트 흐름에서 페이지가 끝나는 위치를 명확하게 식별하는 방법은 다음과 같습니다:

single mode에서 페이지 끝을 식별하기 위해 사용자 정의 pages_delimiter 추가

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이거나, 시각적 효과 없이 Markdown viewer에 원활하게 삽입하기 위한 {/* PAGE BREAK */}일 수 있습니다.

PDF에서 이미지 추출

세 가지 다른 솔루션 중 하나를 선택하여 PDF에서 이미지를 (텍스트 형식으로) 추출할 수 있습니다:
  • rapidOCR (경량 Optical Character Recognition 도구)
  • Tesseract (높은 정밀도의 OCR 도구)
  • Multimodal language model
결과는 페이지 텍스트의 끝에 삽입됩니다.

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:])

multimodal model로 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))

Working with Files

많은 document loader들은 파일 파싱을 포함합니다. 이러한 loader들 간의 차이점은 일반적으로 파일이 로드되는 방식이 아니라 파일이 파싱되는 방식에서 비롯됩니다. 예를 들어, open을 사용하여 PDF 또는 markdown 파일의 binary content를 읽을 수 있지만, 해당 binary data를 텍스트로 변환하려면 다른 파싱 로직이 필요합니다. 결과적으로 파싱 로직을 로딩 로직에서 분리하는 것이 도움이 될 수 있으며, 이를 통해 데이터가 로드된 방식에 관계없이 주어진 parser를 재사용하기가 더 쉬워집니다. 이 전략을 사용하여 동일한 파싱 매개변수로 다양한 파일을 분석할 수 있습니다.
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 reference

PyMuPDF4LLMLoader의 모든 기능과 구성에 대한 자세한 문서는 GitHub repository를 참조하세요: github.com/lakinduboteju/langchain-pymupdf4llm
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I