自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

從PDF和圖像中提取文本,以供大型語言模型使用

開發(fā)
本文專注于Pytesseract、easyOCR、PyPDF2和LangChain庫,旨在提供一些有效從任何類型文檔中提取文本的技術(shù)。

想法

大型語言模型已經(jīng)席卷了互聯(lián)網(wǎng),導(dǎo)致更多的人沒有認(rèn)真關(guān)注使用這些模型最重要的部分:高質(zhì)量的數(shù)據(jù)!本文旨在提供一些有效從任何類型文檔中提取文本的技術(shù)。

Python庫

本文專注于Pytesseract、easyOCR、PyPDF2和LangChain庫。實驗數(shù)據(jù)是一個單頁PDF文件,可在以下鏈接獲?。?/p>

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

由于Pytesseract和easyOCR可以處理圖像,因此在執(zhí)行內(nèi)容提取之前需要將PDF文件轉(zhuǎn)換為圖像??梢允褂胮ypdfium2進(jìn)行轉(zhuǎn)換,這是一個用于處理PDF文件的強(qiáng)大庫,其實現(xiàn)如下:

pip install pypdfium2

以下函數(shù)以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

現(xiàn)在,我們可以使用display_images函數(shù)來可視化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()

通過組合上述兩個函數(shù),我們可以得到以下結(jié)果:

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

圖片PDF以圖像格式可視化

深入文本提取過程

1.Pytesseract

Pytesseract(Python-tesseract)是用于從圖像中提取文本信息的Python OCR工具,可以使用以下pip命令進(jìn)行安裝:

pip install pytesseract

以下的輔助函數(shù)使用了 Pytesseract 的 image_to_string() 函數(shù)從輸入圖像中提取文本。

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 函數(shù)提取文本,如下所示:

text_with_pytesseract = extract_text_with_pytesseract(convert_pdf_to_images)
print(text_with_pytesseract)

成功執(zhí)行以上代碼將生成以下結(jié)果:

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 首先通過從圖像的右上角到右下角識別矩形形狀。然后它提取各個圖像的內(nèi)容,最終的結(jié)果是這些提取內(nèi)容的串聯(lián)。這種方法在處理基于列的 PDF 和圖像文檔時效果非常好。

2.easyOCR

easyOCR 也是一個用于光學(xué)字符識別的開源 Python 庫,目前支持提取 80 多種語言的文本。easyOCR需要安裝Pytorch 和 OpenCV,可以使用以下指令安裝:

!pip install opencv-python-headless==4.1.2.30

根據(jù)您的操作系統(tǒng),安裝 Pytorch 模塊的方法可能不同。但所有的說明都可以在官方頁面上找到。現(xiàn)在我們來安裝 easyOCR 庫:

!pip install easyocr

在使用 easyOCR 時,因為它支持多語言,所以在處理文檔時需要指定語言。通過其 Reader 模塊設(shè)置語言,指定語言列表。例如,fr 用于法語,en 用于英語。語言的詳細(xì)列表在此處可用。

from easyocr import Reader

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

文本提取過程在extract_text_with_easyocr 函數(shù)中實現(xiàn):

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)

我們可以如下執(zhí)行上述函數(shù):

text_with_easy_ocr = extract_text_with_easyocr(convert_pdf_to_images)
print(text_with_easy_ocr)

easyOCR 的結(jié)果

與 Pytesseract 相比,easyOCR 的效果似乎不太高效。例如,它能夠有效地讀取前兩個段落。然而,它不是將每個文本塊視為獨立的文本,而是使用基于行的方法進(jìn)行讀取。例如,第一個文本塊中的字符串“Data Science section covers basic to advanced”已與第二個文本塊中的“overfitting when training computer vision”組合在一起,這種組合完全破壞了文本的結(jié)構(gòu)并使最終結(jié)果產(chǎn)生偏差。

3.PyPDF2

PyPDF2 也是一個專門用于 PDF 處理任務(wù)的 Python 庫,例如文本和元數(shù)據(jù)的檢索、合并、裁剪等。

!pip install PyPDF2

提取邏輯實現(xiàn)在 extract_text_with_pyPDF 函數(shù)中:

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 庫進(jìn)行文本提取

提取過程快速而準(zhǔn)確,甚至保留了原始字體大小。PyPDF 的主要問題是它不能有效地從圖像中提取文本。

4.LangChain

LangChain 的 UnstructuredImageLoader 和 UnstructuredFileLoader 模塊可分別用于從圖像和文本/PDF 文件中提取文本,并且在本節(jié)中將探討這兩個選項。

首先,我們需要按照以下方式安裝 langchain 庫:

!pip install langchain

(1) 從圖像中提取文本

from langchain.document_loaders.image import UnstructuredImageLoader

以下是提取文本的函數(shù):

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)

現(xiàn)在,我們可以提取內(nèi)容:

text_with_langchain_image = extract_text_with_langchain_image(convert_pdf_to_images)
print(text_with_langchain_image)

來自 langchain UnstructuredImageLoader 的文本提取。

該庫成功高效地提取了圖像的內(nèi)容。

(2) 從 PDF 中提取文本

以下是從 PDF 中提取內(nèi)容的實現(xiàn):

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 模塊能夠生成準(zhǔn)確的結(jié)果,同時保持原始字體大小。

從 langchain 的 UnstructuredFileLoader 中提取文本。

責(zé)任編輯:趙寧寧 來源: 小白玩轉(zhuǎn)Python
相關(guān)推薦

2021-03-15 21:50:22

Linux提取文本GUI工具

2021-03-10 10:20:06

Linux文本命令

2023-11-15 13:04:30

Python提取表格

2020-07-08 07:54:03

PythonPDF數(shù)據(jù)

2025-02-17 12:00:00

PythonOpenCV提取圖像

2021-09-04 23:45:40

機(jī)器學(xué)習(xí)語言人工智能

2014-07-16 17:35:03

Android表單模型

2021-03-16 09:00:00

深度學(xué)習(xí)人工智能傳感器

2021-08-16 11:51:16

微軟Windows 365Azure

2021-05-13 23:54:12

DockerDockerfile鏡像

2023-06-24 19:59:40

2013-04-01 11:14:56

IT大數(shù)據(jù)網(wǎng)絡(luò)信息化

2022-11-23 10:31:54

2023-03-26 00:24:15

2023-04-27 19:02:30

語言模型管理企業(yè)數(shù)據(jù)

2024-04-16 16:14:01

人工智能LLMRAG

2025-01-20 09:41:29

2016-01-26 11:08:54

2022-08-24 15:57:17

圖片輪廓

2023-06-19 16:05:22

大型語言模型人工智能
點贊
收藏

51CTO技術(shù)棧公眾號