File size: 1,185 Bytes
a8c31fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import re
import easyocr
import torch
import numpy as np
from PIL import Image, ImageOps

# Initialize EasyOCR Reader globally so it stays in memory once
# This will use GPU (CUDA) if available
reader = easyocr.Reader(['en'], gpu=torch.cuda.is_available())

def resize_image(image: Image.Image, max_dim: int = 1500) -> Image.Image:
    """Resizes image if either dimension exceeds max_dim to speed up CPU OCR."""
    w, h = image.size
    if w <= max_dim and h <= max_dim:
        return image
    
    scale = max_dim / max(w, h)
    new_size = (int(w * scale), int(h * scale))
    print(f"--- [CPU OPTIMIZATION] Resizing from {w}x{h} to {new_size[0]}x{new_size[1]} ---")
    return image.resize(new_size, Image.Resampling.LANCZOS)

def normalize_text(text: str) -> str:
    """Removes special characters, extra spaces, and converts to uppercase for reliable matching."""
    if not text: return ""
    text = text.upper()
    return re.sub(r'[^A-Z0-9]', '', text)

def preprocess_image(image: Image.Image) -> Image.Image:
    """Applies basic grayscale to reduce dimensionality while preserving natural contrast for EasyOCR."""
    image = ImageOps.grayscale(image)
    return image