"""OCR processing using Tesseract and Pillow.""" from __future__ import annotations import io import logging from typing import Optional try: from PIL import Image, ImageEnhance, ImageFilter PIL_AVAILABLE = True except ImportError: PIL_AVAILABLE = False try: import pytesseract TESSERACT_AVAILABLE = True except ImportError: TESSERACT_AVAILABLE = False logger = logging.getLogger(__name__) def preprocess_image_for_ocr(image: "Image.Image") -> "Image.Image": """Enhance image for better OCR accuracy.""" img = image.convert("L") enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(2.0) img = img.filter(ImageFilter.SHARPEN) w, h = img.size if w < 1000: scale = 1000 / w img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS) return img def ocr_image(image: "Image.Image", lang: str = "eng") -> str: """Run Tesseract OCR on a PIL Image.""" if not PIL_AVAILABLE: raise RuntimeError("Pillow is not installed. Install it with: pip install pillow") if not TESSERACT_AVAILABLE: raise RuntimeError("pytesseract is not installed. Install it with: pip install pytesseract") processed = preprocess_image_for_ocr(image) config = "--oem 3 --psm 6" text = pytesseract.image_to_string(processed, lang=lang, config=config) return text.strip() def ocr_image_file(path: str, lang: str = "eng") -> str: """OCR an image file by path.""" if not PIL_AVAILABLE: raise RuntimeError("Pillow is not installed.") with Image.open(path) as img: img = img.convert("RGB") return ocr_image(img, lang=lang) def ocr_image_bytes(data: bytes, lang: str = "eng") -> str: """OCR image from raw bytes.""" if not PIL_AVAILABLE: raise RuntimeError("Pillow is not installed.") with Image.open(io.BytesIO(data)) as img: img = img.convert("RGB") return ocr_image(img, lang=lang)