ShubhamManachekar's picture
Upload 13 files
826e4da
Raw History Blame Contribute Delete
3.15 kB
import os
import docx2txt
import easyocr
import numpy as np
import pytesseract
from PIL import ImageEnhance, ImageFilter
from docx import Document # Import the Document class from docx module
from pdf2image import convert_from_path
# Path to Tesseract executable
pytesseract.pytesseract.tesseract_cmd = r"D:\Tesseract-OCR\tesseract.exe"
def preprocess_image(image):
"""Preprocess an image (enhance contrast and sharpness, denoise)"""
image = image.convert("RGB")
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(2.0) # Increase contrast
enhancer = ImageEnhance.Sharpness(image)
image = enhancer.enhance(2.0) # Increase sharpness
image = image.filter(ImageFilter.GaussianBlur(radius=2)) # Apply Gaussian blur for denoising
return image
def process_image_tesseract(image):
"""Process an image using Tesseract OCR"""
try:
preprocessed_image = preprocess_image(image)
text = pytesseract.image_to_string(preprocessed_image)
return text
except Exception as e:
print(f"An error occurred during Tesseract OCR processing: {e}")
return ""
def process_image_easyocr(image):
"""Process an image using EasyOCR"""
try:
preprocessed_image = preprocess_image(image)
image_np = np.array(preprocessed_image)
reader = easyocr.Reader(lang_list=['en', 'hi', 'mr'])
results = reader.readtext(image_np)
text = " ".join([result[1] for result in results]) # Concatenate recognized text
return text
except Exception as e:
print(f"An error occurred during EasyOCR processing: {e}")
return ""
def extract_text_from_docx(docx_path):
"""Extract text from DOCX file"""
try:
extracted_text = ""
# Extract text from paragraphs
text = docx2txt.process(docx_path)
extracted_text += text
# Extract text from tables
doc = Document(docx_path)
for table in doc.tables:
table_text = extract_table_text(table)
extracted_text += table_text + "\n"
return extracted_text
except Exception as e:
print(f"An error occurred during DOCX processing: {e}")
return ""
def extract_table_text(table):
"""Extract text from a table in DOCX"""
table_text = ""
for row in table.rows:
for cell in row.cells:
cell_text = ""
for paragraph in cell.paragraphs:
cell_text += paragraph.text + " "
table_text += cell_text.strip() + "\t"
table_text += "\n"
return table_text
def process_pdf(pdf_path, poppler_path, output_folder):
"""Process a PDF file"""
try:
pdf_filename = os.path.basename(pdf_path)
images = convert_from_path(pdf_path, poppler_path=poppler_path)
extracted_text = ""
for i, image in enumerate(images):
text = process_image_tesseract(image) + process_image_easyocr(image)
extracted_text += text + "\n"
return extracted_text
except Exception as e:
print(f"An error occurred during PDF processing: {e}")
return ""