Spaces:
Runtime error
Runtime error
Delete ocr_engine.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from typing import List, Tuple, Optionalimport easyocrimport pytesseractimport numpy as npfrom PIL import Imageimport loggingfrom exceptions import OCRErrorfrom config import OCR_CONFIG
logger = logging.getLogger(__name__)
class OCREngine: """Handles OCR processing using multiple engines""" def __init__(self): """Initialize OCR engines""" try: self.reader = easyocr.Reader(OCR_CONFIG["supported_languages"]) self.confidence_threshold = OCR_CONFIG["confidence_threshold"] self.tesseract_confidence_threshold = OCR_CONFIG["tesseract_confidence_threshold"] except Exception as e: logger.error(f"Failed to initialize OCR engine: {str(e)}") raise OCRError(f"Failed to initialize OCR engine: {str(e)}") def process_image( self, image: np.ndarray ) -> List[Tuple[Tuple[int, int, int, int], str, float]]: """ Process image using multiple OCR engines Args: image: Input image as numpy array Returns: List of tuples containing bounding box, text, and confidence """ results = [] try: # Try EasyOCR first easy_ocr_results = self.reader.readtext(image) for box, text, conf in easy_ocr_results: if conf > self.confidence_threshold: # Convert box coordinates to (x1, y1, x2, y2) format x1, y1 = map(int, box[0]) x2, y2 = map(int, box[2]) results.append(((x1, y1, x2, y2), text, conf)) except Exception as e: logger.warning(f"EasyOCR failed: {str(e)}") try: # Try Tesseract as backup tess_data = pytesseract.image_to_data( image, output_type=pytesseract.Output.DICT ) for i in range(len(tess_data['text'])): if int(tess_data['conf'][i]) > self.tesseract_confidence_threshold: text = tess_data['text'][i] if text.strip(): x = tess_data['left'][i] y = tess_data['top'][i] w = tess_data['width'][i] h = tess_data['height'][i] conf = float(tess_data['conf'][i]) / 100 results.append(((x, y, x + w, y + h), text, conf)) except Exception as e: logger.warning(f"Tesseract failed: {str(e)}") if not results: logger.warning("No text detected by any OCR engine") return results def merge_results( self, results: List[Tuple[Tuple[int, int, int, int], str, float]] ) -> List[Tuple[Tuple[int, int, int, int], str, float]]: """ Merge overlapping OCR results Args: results: List of OCR results Returns: Merged OCR results """ def boxes_overlap(box1, box2): """Check if two boxes overlap""" x1_1, y1_1, x2_1, y2_1 = box1 x1_2, y1_2, x2_2, y2_2 = box2 return not (x2_1 < x1_2 or x1_1 > x2_2 or y2_1 < y1_2 or y1_1 > y2_2) merged = [] used = set() for i, (box1, text1, conf1) in enumerate(results): if i in used: continue current_box = list(box1) current_text = text1 current_conf = conf1 overlaps = [] for j, (box2, text2, conf2) in enumerate(results[i+1:], i+1): if j not in used and boxes_overlap(box1, box2): overlaps.append((j, box2, text2, conf2)) used.add(j) if overlaps: # Merge boxes and choose text with highest confidence for j, box2, text2, conf2 in overlaps: current_box[0] = min(current_box[0], box2[0]) current_box[1] = min(current_box[1], box2[1]) current_box[2] = max(current_box[2], box2[2]) current_box[3] = max(current_box[3], box2[3]) if conf2 > current_conf: current_text = text2 current_conf = conf2 merged.append((tuple(current_box), current_text, current_conf)) return mergedocr_engine.pyDeleted-129