Files
langchain/docs/docs/integrations/document_loaders/pypdfloader.ipynb
Philippe PRADOS ceda8bc050 community[minor]: 03 - Refactoring PyPDF parser (#29330)
This is one part of a larger Pull Request (PR) that is too large to be
submitted all at once.
This specific part focuses on updating the PyPDF parser.

For more details, see [PR
28970](https://github.com/langchain-ai/langchain/pull/28970).
2025-01-31 10:05:07 -05:00

1122 lines
42 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# PyPDFLoader\n",
"\n",
"This notebook provides a quick overview for getting started with `PyPDF` [document loader](https://python.langchain.com/docs/concepts/document_loaders). For detailed documentation of all DocumentLoader features and configurations head to the [API reference](https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html).\n",
"\n",
" \n",
"\n",
"## Overview\n",
"### Integration details\n",
"\n",
"| Class | Package | Local | Serializable | JS support|\n",
"| :--- | :--- | :---: | :---: | :---: |\n",
"| [PyPDFLoader](https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html) | [langchain_community](https://python.langchain.com/api_reference/community/index.html) | ✅ | ❌ | ❌ | \n",
" \n",
"--------- \n",
"\n",
"### Loader features\n",
"\n",
"| Source | Document Lazy Loading | Native Async Support | Extract Images | Extract Tables |\n",
"|:-----------:| :---: | :---: | :---: |:---: |\n",
"| PyPDFLoader | ✅ | ❌ | ✅ | ❌ |\n",
"\n",
" \n",
"\n",
"## Setup\n",
"\n",
"### Credentials\n",
"\n",
"No credentials are required to use `PyPDFLoader`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "If you want to get automated best in-class tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:"
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:08.825630Z",
"start_time": "2025-01-21T08:01:08.823315Z"
}
},
"outputs": [],
"source": [
"# os.environ[\"LANGSMITH_API_KEY\"] = getpass.getpass(\"Enter your LangSmith API key: \")\n",
"# os.environ[\"LANGSMITH_TRACING\"] = \"true\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Installation\n",
"\n",
"Install **langchain_community** and **pypdf**."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:10.997240Z",
"start_time": "2025-01-21T08:01:09.529997Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -qU langchain_community pypdf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialization\n",
"\n",
"Now we can instantiate our model object and load documents:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:14.685958Z",
"start_time": "2025-01-21T08:01:13.653438Z"
}
},
"outputs": [],
"source": [
"from langchain_community.document_loaders import PyPDFLoader\n",
"\n",
"file_path = \"./example_data/layout-parser-paper.pdf\"\n",
"loader = PyPDFLoader(file_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:17.433959Z",
"start_time": "2025-01-21T08:01:17.080724Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"Document(metadata={'producer': 'pdfTeX-1.40.21', 'creator': 'LaTeX with hyperref', 'creationdate': '2021-06-22T01:27:10+00:00', 'author': '', 'keywords': '', 'moddate': '2021-06-22T01:27:10+00:00', 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) kpathsea version 6.3.2', 'subject': '', 'title': '', 'trapped': '/False', 'source': './example_data/layout-parser-paper.pdf', 'total_pages': 16, 'page': 0, 'page_label': '1'}, page_content='LayoutParser: A Unified Toolkit for Deep\\nLearning Based Document Image Analysis\\nZejiang Shen1 (\\x00 ), Ruochen Zhang2, Melissa Dell3, Benjamin Charles Germain\\nLee4, Jacob Carlson3, and Weining Li5\\n1 Allen Institute for AI\\nshannons@allenai.org\\n2 Brown University\\nruochen zhang@brown.edu\\n3 Harvard University\\n{melissadell,jacob carlson}@fas.harvard.edu\\n4 University of Washington\\nbcgl@cs.washington.edu\\n5 University of Waterloo\\nw422li@uwaterloo.ca\\nAbstract. 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 im-\\nportant 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 applica-\\ntions. The core LayoutParser library comes with a set of simple and\\nintuitive interfaces for applying and customizing DL models for layout de-\\ntection, 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 digiti-\\nzation pipelines. We demonstrate that LayoutParser is helpful for both\\nlightweight and large-scale digitization pipelines in real-word use cases.\\nThe library is publicly available at https://layout-parser.github.io.\\nKeywords: Document Image Analysis · Deep Learning · Layout Analysis\\n· Character Recognition · Open Source library · Toolkit.\\n1 Introduction\\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,\\narXiv:2103.15348v2 [cs.CV] 21 Jun 2021')"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs = loader.load()\n",
"docs[0]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:18.619845Z",
"start_time": "2025-01-21T08:01:18.615643Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'producer': 'pdfTeX-1.40.21',\n",
" 'creator': 'LaTeX with hyperref',\n",
" 'creationdate': '2021-06-22T01:27:10+00:00',\n",
" 'author': '',\n",
" 'keywords': '',\n",
" 'moddate': '2021-06-22T01:27:10+00:00',\n",
" 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live '\n",
" '2020) kpathsea version 6.3.2',\n",
" 'subject': '',\n",
" 'title': '',\n",
" 'trapped': '/False',\n",
" 'source': './example_data/layout-parser-paper.pdf',\n",
" 'total_pages': 16,\n",
" 'page': 0,\n",
" 'page_label': '1'}\n"
]
}
],
"source": [
"import pprint\n",
"\n",
"pprint.pp(docs[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lazy Load\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:20.450806Z",
"start_time": "2025-01-21T08:01:20.176333Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pages = []\n",
"for doc in loader.lazy_load():\n",
" pages.append(doc)\n",
" if len(pages) >= 10:\n",
" # do some paged operation, e.g.\n",
" # index.upsert(page)\n",
"\n",
" pages = []\n",
"len(pages)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:21.267444Z",
"start_time": "2025-01-21T08:01:21.263726Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"LayoutParser: A Unified Toolkit for DL-Based DIA 11\n",
"focuses on precision, efficiency, and robustness. T\n",
"{'producer': 'pdfTeX-1.40.21',\n",
" 'creator': 'LaTeX with hyperref',\n",
" 'creationdate': '2021-06-22T01:27:10+00:00',\n",
" 'author': '',\n",
" 'keywords': '',\n",
" 'moddate': '2021-06-22T01:27:10+00:00',\n",
" 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live '\n",
" '2020) kpathsea version 6.3.2',\n",
" 'subject': '',\n",
" 'title': '',\n",
" 'trapped': '/False',\n",
" 'source': './example_data/layout-parser-paper.pdf',\n",
" 'total_pages': 16,\n",
" 'page': 10,\n",
" 'page_label': '11'}\n"
]
}
],
"source": [
"print(pages[0].page_content[:100])\n",
"pprint.pp(pages[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The metadata attribute contains at least the following keys:\n",
"- source\n",
"- page (if in mode *page*)\n",
"- total_page\n",
"- creationdate\n",
"- creator\n",
"- producer\n",
"\n",
"Additional metadata are specific to each parser.\n",
"These pieces of information can be helpful (to categorize your PDFs for example)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Splitting mode & custom pages delimiter"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When loading the PDF file you can split it in two different ways:\n",
"- By page\n",
"- As a single text flow\n",
"\n",
"By default PyPDFLoader will split the PDF as a single text flow."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Extract the PDF by page. Each page is extracted as a langchain Document object:"
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:28.128153Z",
"start_time": "2025-01-21T08:01:27.823798Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n",
"{'producer': 'pdfTeX-1.40.21',\n",
" 'creator': 'LaTeX with hyperref',\n",
" 'creationdate': '2021-06-22T01:27:10+00:00',\n",
" 'author': '',\n",
" 'keywords': '',\n",
" 'moddate': '2021-06-22T01:27:10+00:00',\n",
" 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live '\n",
" '2020) kpathsea version 6.3.2',\n",
" 'subject': '',\n",
" 'title': '',\n",
" 'trapped': '/False',\n",
" 'source': './example_data/layout-parser-paper.pdf',\n",
" 'total_pages': 16,\n",
" 'page': 0,\n",
" 'page_label': '1'}\n"
]
}
],
"source": [
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"page\",\n",
")\n",
"docs = loader.load()\n",
"print(len(docs))\n",
"pprint.pp(docs[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "In this mode the pdf is split by pages and the resulting Documents metadata contains the page number. But in some cases we could want to process the pdf as a single text flow (so we don't cut some paragraphs in half). In this case you can use the *single* mode :"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Extract the whole PDF as a single langchain Document object:"
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:31.794895Z",
"start_time": "2025-01-21T08:01:31.470806Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"{'producer': 'pdfTeX-1.40.21',\n",
" 'creator': 'LaTeX with hyperref',\n",
" 'creationdate': '2021-06-22T01:27:10+00:00',\n",
" 'author': '',\n",
" 'keywords': '',\n",
" 'moddate': '2021-06-22T01:27:10+00:00',\n",
" 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live '\n",
" '2020) kpathsea version 6.3.2',\n",
" 'subject': '',\n",
" 'title': '',\n",
" 'trapped': '/False',\n",
" 'source': './example_data/layout-parser-paper.pdf',\n",
" 'total_pages': 16}\n"
]
}
],
"source": [
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"single\",\n",
")\n",
"docs = loader.load()\n",
"print(len(docs))\n",
"pprint.pp(docs[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "Logically, in this mode, the page_number metadata disappears. Here's how to clearly identify where pages end in the text flow :"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Add a custom *pages_delimiter* to identify where are ends of pages in *single* mode:"
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:35.848808Z",
"start_time": "2025-01-21T08:01:35.575903Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"LayoutParser: A Unified Toolkit for Deep\n",
"Learning Based Document Image Analysis\n",
"Zejiang Shen1 (\u0000 ), Ruochen Zhang2, Melissa Dell3, Benjamin Charles Germain\n",
"Lee4, Jacob Carlson3, and Weining Li5\n",
"1 Allen Institute for AI\n",
"shannons@allenai.org\n",
"2 Brown University\n",
"ruochen zhang@brown.edu\n",
"3 Harvard University\n",
"{melissadell,jacob carlson}@fas.harvard.edu\n",
"4 University of Washington\n",
"bcgl@cs.washington.edu\n",
"5 University of Waterloo\n",
"w422li@uwaterloo.ca\n",
"Abstract. Recent advances in document image analysis (DIA) have been\n",
"primarily driven by the application of neural networks. Ideally, research\n",
"outcomes could be easily deployed in production and extended for further\n",
"investigation. However, various factors like loosely organized codebases\n",
"and sophisticated model configurations complicate the easy reuse of im-\n",
"portant innovations by a wide audience. Though there have been on-going\n",
"efforts to improve reusability and simplify deep learning (DL) model\n",
"development in disciplines like natural language processing and computer\n",
"vision, none of them are optimized for challenges in the domain of DIA.\n",
"This represents a major gap in the existing toolkit, as DIA is central to\n",
"academic research across a wide range of disciplines in the social sciences\n",
"and humanities. This paper introduces LayoutParser, an open-source\n",
"library for streamlining the usage of DL in DIA research and applica-\n",
"tions. The core LayoutParser library comes with a set of simple and\n",
"intuitive interfaces for applying and customizing DL models for layout de-\n",
"tection, character recognition, and many other document processing tasks.\n",
"To promote extensibility, LayoutParser also incorporates a community\n",
"platform for sharing both pre-trained models and full document digiti-\n",
"zation pipelines. We demonstrate that LayoutParser is helpful for both\n",
"lightweight and large-scale digitization pipelines in real-word use cases.\n",
"The library is publicly available at https://layout-parser.github.io.\n",
"Keywords: Document Image Analysis · Deep Learning · Layout Analysis\n",
"· Character Recognition · Open Source library · Toolkit.\n",
"1 Introduction\n",
"Deep Learning(DL)-based approaches are the state-of-the-art for a wide range of\n",
"document image analysis (DIA) tasks including document image classification [11,\n",
"arXiv:2103.15348v2 [cs.CV] 21 Jun 2021\n",
"-------THIS IS A CUSTOM END OF PAGE-------\n",
"2 Z. Shen et al.\n",
"37], layout detection [38, 22], table detection [ 26], and scene text detection [ 4].\n",
"A generalized learning-based framework dramatically reduces the need for the\n",
"manual specification of complicated rules, which is the status quo with traditional\n",
"methods. DL has the potential to transform DIA pipelines and benefit a broad\n",
"spectrum of large-scale document digitization projects.\n",
"However, there are several practical difficulties for taking advantages of re-\n",
"cent advances in DL-based methods: 1) DL models are notoriously convoluted\n",
"for reuse and extension. Existing models are developed using distinct frame-\n",
"works like TensorFlow [1] or PyTorch [ 24], and the high-level parameters can\n",
"be obfuscated by implementation details [ 8]. It can be a time-consuming and\n",
"frustrating experience to debug, reproduce, and adapt existing models for DIA,\n",
"and many researchers who would benefit the most from using these methods lack\n",
"the technical background to implement them from scratch. 2) Document images\n",
"contain diverse and disparate patterns across domains, and customized training\n",
"is often required to achieve a desirable detection accuracy. Currently there is no\n",
"full-fledged infrastructure for easily curating the target document image datasets\n",
"and fine-tuning or re-training the models. 3) DIA usually requires a sequence of\n",
"models and other processing to obtain the final outputs. Often research teams use\n",
"DL models and then perform further document analyses in separate processes,\n",
"and these pipelines are not documented in any central location (and often not\n",
"documented at all). This makes it difficult for research teams to learn about how\n",
"full pipelines are implemented and leads them to invest significant resources in\n",
"reinventing the DIA wheel .\n",
"LayoutParser provides a unified toolkit to support DL-based document image\n",
"analysis and processing. To address the aforementioned challenges,LayoutParser\n",
"is built with the following components:\n",
"1. An off-the-shelf toolkit for applying DL models for layout detection, character\n",
"recognition, and other DIA tasks (Section 3)\n",
"2. A rich repository of pre-trained neural network models (Model Zoo) that\n",
"underlies the off-the-shelf usage\n",
"3. Comprehensive tools for efficient document image data annotation and model\n",
"tuning to support different levels of customization\n",
"4. A DL model hub and community platform for the easy sharing, distribu-\n",
"tion, and discussion of DIA models and pipelines, to promote reusability,\n",
"reproducibility, and extensibility (Section 4)\n",
"The library implements simple and intuitive Python APIs without sacrificing\n",
"generalizability and versatility, and can be easily installed via pip. Its convenient\n",
"functions for handling document image data can be seamlessly integrated with\n",
"existing DIA pipelines. With detailed documentations and carefully curated\n",
"tutorials, we hope this tool will benefit a variety of end-users, and will lead to\n",
"advances in applications in both industry and academic research.\n",
"LayoutParser is well aligned with recent efforts for improving DL model\n",
"reusability in other disciplines like natural language processing [ 8, 34] and com-\n",
"puter vision [ 35], but with a focus on unique challenges in DIA. We show\n",
"LayoutParser can be applied in sophisticated and large-scale digitization projects\n",
"-------THIS IS A CUSTOM END OF PAGE-------\n",
"LayoutParser: A Unified Toolkit for DL-Based DIA 3\n",
"that require precision, efficiency, and robustness, as well as simple and light\n"
]
}
],
"source": [
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"single\",\n",
" pages_delimiter=\"\\n-------THIS IS A CUSTOM END OF PAGE-------\\n\",\n",
")\n",
"docs = loader.load()\n",
"print(docs[0].page_content[:5780])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "This could simply be \\n, or \\f to clearly indicate a page change, or \\<!-- PAGE BREAK --> for seamless injection in a Markdown viewer without a visual effect."
},
{
"cell_type": "markdown",
"metadata": {},
"source": "# Extract images from the PDF"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can extract images from your PDFs with a choice of three different solutions:\n",
"- rapidOCR (lightweight Optical Character Recognition tool)\n",
"- Tesseract (OCR tool with high precision)\n",
"- Multimodal language model\n",
"\n",
"You can tune these functions to choose the output format of the extracted images among *html*, *markdown* or *text*\n",
"\n",
"The result is inserted between the last and the second-to-last paragraphs of text of the page."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Extract images from the PDF with rapidOCR:"
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:01:40.692855Z",
"start_time": "2025-01-21T08:01:39.293791Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -qU rapidocr-onnxruntime"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:07.273962Z",
"start_time": "2025-01-21T08:01:42.848244Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6 Z. Shen et al.\n",
"Fig. 2: The relationship between the three types of layout data structures.\n",
"Coordinate supports three kinds of variation; TextBlock consists of the co-\n",
"ordinate information and extra features like block text, types, and reading orders;\n",
"a Layout object is a list of all possible layout elements, including other Layout\n",
"objects. They all support the same set of transformation and operation APIs for\n",
"maximum flexibility.\n",
"Shown in Table 1, LayoutParser currently hosts 9 pre-trained models trained\n",
"on 5 different datasets. Description of the training dataset is provided alongside\n",
"with the trained models such that users can quickly identify the most suitable\n",
"models for their tasks. Additionally, when such a model is not readily available,\n",
"LayoutParser also supports training customized layout models and community\n",
"sharing of the models (detailed in Section 3.5).\n",
"3.2 Layout Data Structures\n",
"A critical feature of LayoutParser is the implementation of a series of data\n",
"structures and operations that can be used to efficiently process and manipulate\n",
"the layout elements. In document image analysis pipelines, various post-processing\n",
"on the layout analysis model outputs is usually required to obtain the final\n",
"outputs. Traditionally, this requires exporting DL model outputs and then loading\n",
"the results into other pipelines. All model outputs from LayoutParser will be\n",
"stored in carefully engineered data types optimized for further processing, which\n",
"makes it possible to build an end-to-end document digitization pipeline within\n",
"LayoutParser. There are three key components in the data structure, namely\n",
"the Coordinate system, the TextBlock, and the Layout. They provide different\n",
"levels of abstraction for the layout data, and a set of APIs are supported for\n",
"transformations or operations on these classes.\n",
"\n",
"\n",
"\n",
"![Coordinate\n",
"(x1, y1)\n",
"(X1, y1)\n",
"(x2,y2)\n",
"APIS\n",
"x-interval\n",
"tart\n",
"end\n",
"Quadrilateral\n",
"operation\n",
"Rectangle\n",
"y-interval\n",
"ena\n",
"(x2, y2)\n",
"(x4, y4)\n",
"(x3, y3)\n",
"and\n",
"textblock\n",
"Coordinate\n",
"transformation\n",
"+\n",
"Block\n",
"Block\n",
"Reading\n",
"Extra features\n",
"Text\n",
"Type\n",
"Order\n",
"coordinatel\n",
"textblockl\n",
"layout\n",
" same\n",
"textblock2\n",
"layoutl\n",
"The\n",
"A list of the layout elements](#)\n"
]
}
],
"source": [
"from langchain_community.document_loaders.parsers import RapidOCRBlobParser\n",
"\n",
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"page\",\n",
" images_inner_format=\"markdown-img\",\n",
" images_parser=RapidOCRBlobParser(),\n",
")\n",
"docs = loader.load()\n",
"\n",
"print(docs[5].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "Be careful, RapidOCR is designed to work with Chinese and English, not other languages."
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Extract images from the PDF with Tesseract:"
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:12.070378Z",
"start_time": "2025-01-21T08:02:10.696635Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -qU pytesseract"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:21.712219Z",
"start_time": "2025-01-21T08:02:12.081700Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6 Z. Shen et al.\n",
"Fig. 2: The relationship between the three types of layout data structures.\n",
"Coordinate supports three kinds of variation; TextBlock consists of the co-\n",
"ordinate information and extra features like block text, types, and reading orders;\n",
"a Layout object is a list of all possible layout elements, including other Layout\n",
"objects. They all support the same set of transformation and operation APIs for\n",
"maximum flexibility.\n",
"Shown in Table 1, LayoutParser currently hosts 9 pre-trained models trained\n",
"on 5 different datasets. Description of the training dataset is provided alongside\n",
"with the trained models such that users can quickly identify the most suitable\n",
"models for their tasks. Additionally, when such a model is not readily available,\n",
"LayoutParser also supports training customized layout models and community\n",
"sharing of the models (detailed in Section 3.5).\n",
"3.2 Layout Data Structures\n",
"A critical feature of LayoutParser is the implementation of a series of data\n",
"structures and operations that can be used to efficiently process and manipulate\n",
"the layout elements. In document image analysis pipelines, various post-processing\n",
"on the layout analysis model outputs is usually required to obtain the final\n",
"outputs. Traditionally, this requires exporting DL model outputs and then loading\n",
"the results into other pipelines. All model outputs from LayoutParser will be\n",
"stored in carefully engineered data types optimized for further processing, which\n",
"makes it possible to build an end-to-end document digitization pipeline within\n",
"LayoutParser. There are three key components in the data structure, namely\n",
"the Coordinate system, the TextBlock, and the Layout. They provide different\n",
"levels of abstraction for the layout data, and a set of APIs are supported for\n",
"transformations or operations on these classes.\n",
"\n",
"\n",
"\n",
"<img alt=\"Coordinate\n",
"\n",
"textblock\n",
"\n",
"x-interval\n",
"\n",
"JeAsaqul-A\n",
"\n",
"Coordinate\n",
"+\n",
"\n",
"Extra features\n",
"\n",
"Rectangle\n",
"\n",
"Quadrilateral\n",
"\n",
"Block\n",
"Text\n",
"\n",
"Block\n",
"Type\n",
"\n",
"Reading\n",
"Order\n",
"\n",
"layout\n",
"\n",
"[ coordinatel textblock1 |\n",
"&#x27;\n",
"\n",
"“y textblock2 , layout1 ]\n",
"\n",
"A list of the layout elements\n",
"\n",
"The same transformation and operation APIs src=\"#\" />\n"
]
}
],
"source": [
"from langchain_community.document_loaders.parsers import TesseractBlobParser\n",
"\n",
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"page\",\n",
" images_inner_format=\"html-img\",\n",
" images_parser=TesseractBlobParser(),\n",
")\n",
"docs = loader.load()\n",
"print(docs[5].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Extract images from the PDF with multimodal model:"
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:25.912928Z",
"start_time": "2025-01-21T08:02:24.324014Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -qU langchain_openai"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:28.494996Z",
"start_time": "2025-01-21T08:02:28.468181Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"\n",
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:02:29.318093Z",
"start_time": "2025-01-21T08:02:29.314654Z"
}
},
"outputs": [],
"source": [
"from getpass import getpass\n",
"\n",
"if not os.environ.get(\"OPENAI_API_KEY\"):\n",
" os.environ[\"OPENAI_API_KEY\"] = getpass(\"OpenAI API key =\")"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:05:00.352337Z",
"start_time": "2025-01-21T08:02:30.723099Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6 Z. Shen et al.\n",
"Fig. 2: The relationship between the three types of layout data structures.\n",
"Coordinate supports three kinds of variation; TextBlock consists of the co-\n",
"ordinate information and extra features like block text, types, and reading orders;\n",
"a Layout object is a list of all possible layout elements, including other Layout\n",
"objects. They all support the same set of transformation and operation APIs for\n",
"maximum flexibility.\n",
"Shown in Table 1, LayoutParser currently hosts 9 pre-trained models trained\n",
"on 5 different datasets. Description of the training dataset is provided alongside\n",
"with the trained models such that users can quickly identify the most suitable\n",
"models for their tasks. Additionally, when such a model is not readily available,\n",
"LayoutParser also supports training customized layout models and community\n",
"sharing of the models (detailed in Section 3.5).\n",
"3.2 Layout Data Structures\n",
"A critical feature of LayoutParser is the implementation of a series of data\n",
"structures and operations that can be used to efficiently process and manipulate\n",
"the layout elements. In document image analysis pipelines, various post-processing\n",
"on the layout analysis model outputs is usually required to obtain the final\n",
"outputs. Traditionally, this requires exporting DL model outputs and then loading\n",
"the results into other pipelines. All model outputs from LayoutParser will be\n",
"stored in carefully engineered data types optimized for further processing, which\n",
"makes it possible to build an end-to-end document digitization pipeline within\n",
"LayoutParser. There are three key components in the data structure, namely\n",
"the Coordinate system, the TextBlock, and the Layout. They provide different\n",
"levels of abstraction for the layout data, and a set of APIs are supported for\n",
"transformations or operations on these classes.\n",
"\n",
"\n",
"\n",
"![**Image Summary:** \n",
"Diagram explaining coordinate systems and layout elements with labels for coordinate intervals, rectangle, quadrilateral, textblock with extra features, and layout list. Includes transformation and operation APIs.\n",
"\n",
"**Extracted Text:** \n",
"Coordinate \n",
"coordinate \n",
"start \n",
"start \n",
"x-interval \n",
"end \n",
"y-interval \n",
"end \n",
"(x1, y1) \n",
"Rectangle \n",
"(x2, y2) \n",
"(x1, y1) \n",
"Quadrilateral \n",
"(x2, y2) \n",
"(x4, y4) \n",
"(x3, y3) \n",
"The same transformation and operation APIs \n",
"textblock \n",
"Coordinate \n",
"Extra features \n",
"Block Text \n",
"Block Type \n",
"Reading Order \n",
"... \n",
"layout \n",
"coordinate1, textblock1, ... \n",
"..., textblock2, layout1 \n",
"A list of the layout elements ](#)\n"
]
}
],
"source": [
"from langchain_community.document_loaders.parsers import LLMImageBlobParser\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"loader = PyPDFLoader(\n",
" \"./example_data/layout-parser-paper.pdf\",\n",
" mode=\"page\",\n",
" images_inner_format=\"markdown-img\",\n",
" images_parser=LLMImageBlobParser(model=ChatOpenAI(model=\"gpt-4o\", max_tokens=1024)),\n",
")\n",
"docs = loader.load()\n",
"print(docs[5].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Working with Files\n",
"\n",
"Many document loaders involve parsing files. The difference between such loaders usually stems from how the file is parsed, rather than how the file is loaded. For example, you can use `open` to read the binary content of either a PDF or a markdown file, but you need different parsing logic to convert that binary data into text.\n",
"\n",
"As a result, it can be helpful to decouple the parsing logic from the loading logic, which makes it easier to re-use a given parser regardless of how the data was loaded.\n",
"You can use this strategy to analyze different files, with the same parsing parameters."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-21T08:05:08.330141Z",
"start_time": "2025-01-21T08:05:07.997956Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"LayoutParser: A Unified Toolkit for Deep\n",
"Learning Based Document Image Analysis\n",
"Zejiang Shen1 (\u0000 ), Ruochen Zhang2, Melissa Dell3, Benjamin Charles Germain\n",
"Lee4, Jacob Carlson3, and Weining Li5\n",
"1 Allen Institute for AI\n",
"shannons@allenai.org\n",
"2 Brown University\n",
"ruochen zhang@brown.edu\n",
"3 Harvard University\n",
"{melissadell,jacob carlson}@fas.harvard.edu\n",
"4 University of Washington\n",
"bcgl@cs.washington.edu\n",
"5 University of Waterloo\n",
"w422li@uwaterloo.ca\n",
"Abstract. Recent advances in document image analysis (DIA) have been\n",
"primarily driven by the application of neural networks. Ideally, research\n",
"outcomes could be easily deployed in production and extended for further\n",
"investigation. However, various factors like loosely organized codebases\n",
"and sophisticated model configurations complicate the easy reuse of im-\n",
"portant innovations by a wide audience. Though there have been on-going\n",
"efforts to improve reusability and simplify deep learning (DL) model\n",
"development in disciplines like natural language processing and computer\n",
"vision, none of them are optimized for challenges in the domain of DIA.\n",
"This represents a major gap in the existing toolkit, as DIA is central to\n",
"academic research across a wide range of disciplines in the social sciences\n",
"and humanities. This paper introduces LayoutParser, an open-source\n",
"library for streamlining the usage of DL in DIA research and applica-\n",
"tions. The core LayoutParser library comes with a set of simple and\n",
"intuitive interfaces for applying and customizing DL models for layout de-\n",
"tection, character recognition, and many other document processing tasks.\n",
"To promote extensibility, LayoutParser also incorporates a community\n",
"platform for sharing both pre-trained models and full document digiti-\n",
"zation pipelines. We demonstrate that LayoutParser is helpful for both\n",
"lightweight and large-scale digitization pipelines in real-word use cases.\n",
"The library is publicly available at https://layout-parser.github.io.\n",
"Keywords: Document Image Analysis · Deep Learning · Layout Analysis\n",
"· Character Recognition · Open Source library · Toolkit.\n",
"1 Introduction\n",
"Deep Learning(DL)-based approaches are the state-of-the-art for a wide range of\n",
"document image analysis (DIA) tasks including document image classification [11,\n",
"arXiv:2103.15348v2 [cs.CV] 21 Jun 2021\n",
"{'producer': 'pdfTeX-1.40.21',\n",
" 'creator': 'LaTeX with hyperref',\n",
" 'creationdate': '2021-06-22T01:27:10+00:00',\n",
" 'author': '',\n",
" 'keywords': '',\n",
" 'moddate': '2021-06-22T01:27:10+00:00',\n",
" 'ptex.fullbanner': 'This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live '\n",
" '2020) kpathsea version 6.3.2',\n",
" 'subject': '',\n",
" 'title': '',\n",
" 'trapped': '/False',\n",
" 'source': 'example_data/layout-parser-paper.pdf',\n",
" 'total_pages': 16,\n",
" 'page': 0,\n",
" 'page_label': '1'}\n"
]
}
],
"source": [
"from langchain_community.document_loaders import FileSystemBlobLoader\n",
"from langchain_community.document_loaders.generic import GenericLoader\n",
"from langchain_community.document_loaders.parsers import PyPDFParser\n",
"\n",
"loader = GenericLoader(\n",
" blob_loader=FileSystemBlobLoader(\n",
" path=\"./example_data/\",\n",
" glob=\"*.pdf\",\n",
" ),\n",
" blob_parser=PyPDFParser(),\n",
")\n",
"docs = loader.load()\n",
"print(docs[0].page_content)\n",
"pprint.pp(docs[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": "It is possible to work with files from cloud storage."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.document_loaders import CloudBlobLoader\n",
"from langchain_community.document_loaders.generic import GenericLoader\n",
"\n",
"loader = GenericLoader(\n",
" blob_loader=CloudBlobLoader(\n",
" url=\"s3://mybucket\", # Supports s3://, az://, gs://, file:// schemes.\n",
" glob=\"*.pdf\",\n",
" ),\n",
" blob_parser=PyPDFParser(),\n",
")\n",
"docs = loader.load()\n",
"print(docs[0].page_content)\n",
"pprint.pp(docs[0].metadata)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## API reference\n",
"\n",
"For detailed documentation of all `PyPDFLoader` features and configurations head to the API reference: https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.1"
}
},
"nbformat": 4,
"nbformat_minor": 4
}