从PDF和图像中提取文本,以供大型语言模型使用

简介: 从PDF和图像中提取文本,以供大型语言模型使用

想法

大型语言模型已经席卷了互联网,导致更多的人没有认真关注使用这些模型最重要的部分:高质量的数据!本文旨在提供一些有效从任何类型文档中提取文本的技术。


Python库

本文专注于PytesseracteasyOCRPyPDF2LangChain库。实验数据是一个单页PDF文件,可在以下链接获取:

https://github.com/keitazoumana/Experimentation-Data/blob/main/Experimentation_file.pdf


由于PytesseracteasyOCR可以处理图像,因此在执行内容提取之前需要将PDF文件转换为图像。可以使用pypdfium2进行转换,这是一个用于处理PDF文件的强大库,其实现如下:


pip install pypdfium2


以下函数以PDF作为输入,并将PDF的每一页作为图像列表返回。


def convert_pdf_to_images(file_path, scale=300/72):
   pdf_file = pdfium.PdfDocument(file_path)
   page_indices = [i for i in range(len(pdf_file))]
   renderer = pdf_file.render(
       pdfium.PdfBitmap.to_pil,
       page_indices = page_indices, 
       scale = scale,
   )
   final_images = [] 
   for i, image in zip(page_indices, renderer):
       image_byte_array = BytesIO()
       image.save(image_byte_array, format='jpeg', optimize=True)
       image_byte_array = image_byte_array.getvalue()
       final_images.append(dict({i:image_byte_array}))
   return final_images


现在,我们可以使用`display_images`函数来可视化PDF文件的所有页面。


def display_images(list_dict_final_images):
   all_images = [list(data.values())[0] for data in list_dict_final_images]
   for index, image_bytes in enumerate(all_images):
       image = Image.open(BytesIO(image_bytes))
       figure = plt.figure(figsize = (image.width / 100, image.height / 100))
       plt.title(f"----- Page Number {index+1} -----")
       plt.imshow(image)
       plt.axis("off")
       plt.show()


通过组合上述两个函数,我们可以得到以下结果:


convert_pdf_to_images = convert_pdf_to_images('Experimentation_file.pdf')
display_images(convert_pdf_to_images)

PDF以图像格式可视化


深入文本提取过程

Pytesseract

PytesseractPython-tesseract)是用于从图像中提取文本信息的Python OCR工具,可以使用以下pip命令进行安装:


pip install pytesseract

以下的辅助函数使用了Pytesseract`image_to_string()` 函数从输入图像中提取文本。


from pytesseract import image_to_string
def extract_text_with_pytesseract(list_dict_final_images):
   image_list = [list(data.values())[0] for data in list_dict_final_images]
   image_content = []
   for index, image_bytes in enumerate(image_list):
       image = Image.open(BytesIO(image_bytes))
       raw_text = str(image_to_string(image))
       image_content.append(raw_text)
   return "\n".join(image_content)


可以使用 `extract_text_with_pytesseract` 函数提取文本,如下所示:


text_with_pytesseract = extract_text_with_pytesseract(convert_pdf_to_images)
print(text_with_pytesseract)


成功执行以上代码将生成以下结果:


This document provides a quick summary of some of Zoumana’s article on Medium.
It can be considered as the compilation of his 80+ articles about Data Science, Machine Learning and
Machine Learning Operations.
...
Pytesseract was able to extract the content of the image.
Here is how it managed to do it!
Pytesseract starts by identifying rectangular shapes within the input image from top-right to bottom-right. Then it extracts the content of the individual images, and the final result is the concatenation of those extracted content. This approach works perfectly when dealing with column-based PDFs and image documents.
...


Pytesseract 首先通过从图像的右上角到右下角识别矩形形状。然后它提取各个图像的内容,最终的结果是这些提取内容的串联。这种方法在处理基于列的 PDF 和图像文档时效果非常好。


easyOCR

easyOCR 也是一个用于光学字符识别的开源 Python 库,目前支持提取 80 多种语言的文本。easyOCR需要安装Pytorch OpenCV,可以使用以下指令安装:


!pip install opencv-python-headless==4.1.2.30

根据您的操作系统,安装 Pytorch 模块的方法可能不同。但所有的说明都可以在官方页面上找到。现在我们来安装 easyOCR 库:


!pip install easyocr

在使用 easyOCR 时,因为它支持多语言,所以在处理文档时需要指定语言。通过其 Reader 模块设置语言,指定语言列表。例如,fr 用于法语,en 用于英语。语言的详细列表在此处可用。


from easyocr import Reader
# Load model for the English language
language_reader = Reader(["en"])


文本提取过程在`extract_text_with_easyocr` 函数中实现:


def extract_text_with_easyocr(list_dict_final_images):
   image_list = [list(data.values())[0] for data in list_dict_final_images]
   image_content = []
   for index, image_bytes in enumerate(image_list):
       image = Image.open(BytesIO(image_bytes))
       raw_text = language_reader.readtext(image)
       raw_text = " ".join([res[1] for res in raw_text])
       image_content.append(raw_text)
   return "\n".join(image_content)


我们可以如下执行上述函数:


text_with_easy_ocr = extract_text_with_easyocr(convert_pdf_to_images)
print(text_with_easy_ocr)

easyOCR 的结果

Pytesseract 相比,easyOCR 的效果似乎不太高效。例如,它能够有效地读取前两个段落。然而,它不是将每个文本块视为独立的文本,而是使用基于行的方法进行读取。例如,第一个文本块中的字符串“Data Science section covers basic to advanced”已与第二个文本块中的“overfitting when training computer vision”组合在一起,这种组合完全破坏了文本的结构并使最终结果产生偏差。


PyPDF2

PyPDF2也是一个专门用于 PDF 处理任务的 Python 库,例如文本和元数据的检索、合并、裁剪等。


!pip install PyPDF2


提取逻辑实现在 `extract_text_with_pyPDF` 函数中:


def extract_text_with_pyPDF(PDF_File):
    pdf_reader = PdfReader(PDF_File)
    raw_text = ''
    for i, page in enumerate(pdf_reader.pages):
        text = page.extract_text()
        if text:
            raw_text += text
    return raw_text
text_with_pyPDF = extract_text_with_pyPDF("Experimentation_file.pdf")
print(text_with_pyPDF)

使用 PyPDF 库进行文本提取

提取过程快速而准确,甚至保留了原始字体大小。PyPDF 的主要问题是它不能有效地从图像中提取文本。


LangChain

LangChain UnstructuredImageLoader UnstructuredFileLoader 模块可分别用于从图像和文本/PDF 文件中提取文本,并且在本节中将探讨这两个选项。

首先,我们需要按照以下方式安装 langchain 库:


!pip install langchain

从图像中提取文本


from langchain.document_loaders.image import UnstructuredImageLoader

以下是提取文本的函数:


def extract_text_with_langchain_image(list_dict_final_images):
   image_list = [list(data.values())[0] for data in list_dict_final_images]
   image_content = []
   for index, image_bytes in enumerate(image_list):
       image = Image.open(BytesIO(image_bytes))
       loader = UnstructuredImageLoader(image)
       data = loader.load()
       raw_text = data[index].page_content
       image_content.append(raw_text)
   return "\n".join(image_content)


现在,我们可以提取内容:


text_with_langchain_image = extract_text_with_langchain_image(convert_pdf_to_images)
print(text_with_langchain_image)

来自 langchain UnstructuredImageLoader 的文本提取

该库成功高效地提取了图像的内容。


PDF 中提取文本

以下是从 PDF 中提取内容的实现:


from langchain.document_loaders import UnstructuredFileLoader
def extract_text_with_langchain_pdf(pdf_file):
   loader = UnstructuredFileLoader(pdf_file)
   documents = loader.load()
   pdf_pages_content = '\n'.join(doc.page_content for doc in documents)
   return pdf_pages_content
text_with_langchain_files = extract_text_with_langchain_pdf("Experimentation_file.pdf")
print(text_with_langchain_files)

类似于 PyPDF 模块,langchain 模块能够生成准确的结果,同时保持原始字体大小。

从 langchain 的 UnstructuredFileLoader 中提取文本

相关实践学习
使用CLup和iSCSI共享盘快速体验PolarDB for PostgtreSQL
在Clup云管控平台中快速体验创建与管理在iSCSI共享盘上的PolarDB for PostgtreSQL。
AnalyticDB PostgreSQL 企业智能数据中台:一站式管理数据服务资产
企业在数据仓库之上可构建丰富的数据服务用以支持数据应用及业务场景;ADB PG推出全新企业智能数据平台,用以帮助用户一站式的管理企业数据服务资产,包括创建, 管理,探索, 监控等; 助力企业在现有平台之上快速构建起数据服务资产体系
相关文章
|
2月前
|
存储 传感器 编解码
CVPR 2023 最全分割类论文整理:图像/全景/语义/实例分割等【附PDF+代码】
CVPR 2023 最全分割类论文整理:图像/全景/语义/实例分割等【附PDF+代码】
120 1
|
Java Unix Linux
知识分享之Golang——读取pdf中纯文本内容
知识分享之Golang篇是我在日常使用Golang时学习到的各种各样的知识的记录,将其整理出来以文章的形式分享给大家,来进行共同学习。欢迎大家进行持续关注。 知识分享系列目前包含Java、Golang、Linux、Docker等等。
1326 1
知识分享之Golang——读取pdf中纯文本内容
|
11月前
|
存储 Linux 测试技术
Python操作PDF-文本和图片提取(使用PyPDF2和PyMuPDF)
Python操作PDF-文本和图片提取(使用PyPDF2和PyMuPDF)
700 0
|
C#
C# 如何在PDF中绘制不同风格类型的文本
通过对控件Spire.PDF的测试,我们可以创建PDF文件并向文档中绘制文本、图片、表格、图形等内容,其中,对于绘制文本这一部分,Spire.PDF提供了三种字体类型来绘制文本,即: Standard fonts TrueType fonts Chinese, Japanese and Korean (CJK) fonts 从以上类中我们可以发现,是可以支持中、日、韩、英等字体类的,这为我们在操作PDF文件上提供了更多可能。
1109 0
|
机器学习/深度学习 自然语言处理 算法
|
存储 自然语言处理 数据挖掘
如何用Python批量提取PDF文本内容?
本文为你展示,如何用Python把许多PDF文件的文本内容批量提取出来,并且整理存储到数据框中,以便于后续的数据分析。 问题 最近,读者们在后台的留言,愈发五花八门了。
2113 0
|
C# 开发者 图形学
C# 如何将PDF转为多种图像文件格式(Png/Bmp/Emf/Tiff)
PDF是一种在我们日常工作学习中最常用到的文档格式之一,但常常也会因为文档的不易编辑的特点,在遇到需要编辑PDF文档内容或者转换文件格式的情况时让人苦恼。通常对于开发者而言,可选择通过使用组件的方式来实现PDF文档的编辑或者格式转换,因此本文将介绍如何通过使用免费版的组件Free Spire.PDF for .NET来转换PDF文档。
1580 0
|
C#
C#在PDF中如何以不同颜色高亮文本
高亮的文本有助于阅读者快速有效地获取文章关键信息。在PDF文件中,对文章的不同文本,关键词、句等进行不同颜色的文本高亮操作,可以使阅读者在阅读过程中有效地区分不同高亮颜色文本的意义。在下面的示例中,我使用Free Spire.
1080 0