import logging from PIL import Image import cv2 import numpy as np # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class OCREngine: def __init__(self): self.supported_languages = ['eng'] def preprocess_image(self, image_path: str) -> np.ndarray: """Preprocess image for better OCR results""" try: # Read image image = cv2.imread(image_path) if image is None: raise ValueError(f"Could not read image from {image_path}") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply noise removal denoised = cv2.medianBlur(gray, 3) # Apply thresholding _, thresh = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return thresh except Exception as e: logger.error(f"Error preprocessing image: {e}") # Return original image if preprocessing fails image = cv2.imread(image_path) return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) def extract_text(self, image_path: str, preprocess: bool = True) -> str: """Extract text from image using OCR""" try: # Try to use pytesseract if available try: import pytesseract tesseract_available = True except ImportError: tesseract_available = False logger.warning("pytesseract not available, using fallback method") if preprocess: processed_image = self.preprocess_image(image_path) pil_image = Image.fromarray(processed_image) else: pil_image = Image.open(image_path) if tesseract_available: # Configure Tesseract custom_config = r'--oem 3 --psm 6' # Extract text text = pytesseract.image_to_string(pil_image, config=custom_config) logger.info(f"Successfully extracted text using Tesseract from {image_path}") else: # Fallback: Return empty text text = "OCR functionality requires pytesseract. Please install tesseract-ocr on your system." logger.warning("Using fallback OCR method") return text.strip() except Exception as e: logger.error(f"OCR extraction failed: {e}") return f"OCR Error: {str(e)}"