User
import os
from langchain_community.document_loaders import PyPDFLoader
from rapidocr_onnxruntime import RapidOCRONNX
def read_pdf_with_ocr(file_path):
"""
Reads a PDF file, extracts text using PyPDFLoader, and applies OCR if necessary.
Args:
file_path (str): The path to the PDF file.
Returns:
str: Extracted text from the PDF.
"""
try:
loader = PyPDFLoader(file_path)
pages = loader.load_and_split()
text = []
ocr_engine = RapidOCRONNX()
for page in pages:
page_text = page.page_content
if not page_text.strip(): # If no text, use OCR
page_image = page.page_image # Assuming this is how you get the image of the page
page_text = ocr_engine.recognize(page_image)
text.append(page_text)
return '\n'.join(text)
except Exception as e:
print(f"Error reading/processing PDF file: {e}")
return None
def write_text_to_file(text, output_file):
"""
Writes extracted text to a text file.
Args:
text (str): Extracted text to write.
output_file (str): Path of the file to write to.
"""
try:
with open(output_file, 'w') as file:
file.write(text)
print(f"Content saved to {output_file}")
except Exception as e:
print(f"Error writing to file {output_file}: {e}")
def process_all_pdfs(pdf_files, output_directory):
"""
Process a list of PDF files and save their content as text files.
Args:
pdf_files (list): List of file paths to PDF files.
output_directory (str): Directory to save text files.
"""
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for file_path in pdf_files:
filename = os.path.basename(file_path)
output_filename = os.path.splitext(filename)[0] + ".txt"
output_file_path = os.path.join(output_directory, output_filename)
print(f"Processing: {filename}")
pdf_text = read_pdf_with_ocr(file_path)
if pdf_text:
write_text_to_file(pdf_text, output_file_path)
else:
print(f"No text extracted from {filename}.")
def list_all_pdfs(directory):
"""
List all PDF file paths in a given directory.
Args:
directory (str): The path to the directory containing PDF files.
Returns:
list: List of file paths to PDF files.
"""
return [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.pdf')]
Example usage
if name == "main":
directory = "src/data/documents/PDF"
output_directory = "src/data/documents/Text"
pdf_files = list_all_pdfs(directory)
process_all_pdfs(pdf_files, output_directory)
(app_env) badredine@MinideBadredine Chagpy % /Users/badredine/Code/Chagy/Chagpy/app_env/bin/python /Users/badredine/Code/Chagy/Chagpy/src/langchain/RAG/Loaders/pdf.py
Traceback (most recent call last):
File "/Users/badredine/Code/Chagy/Chagpy/src/langchain/RAG/Loaders/pdf.py", line 3, in
from rapidocr_onnxruntime import RapidOCRONNX
ImportError: cannot import name 'RapidOCRONNX' from 'rapidocr_onnxruntime' (/Users/badredine/Code/Chagy/Chagpy/app_env/lib/python3.11/site-packages/rapidocr_onnxruntime/init.py)
(app_env) badredine@MinideBadredine Chagpy %