File size: 4,083 Bytes
e2a1a46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""
Advanced OCR Engine for Prescription Text Extraction
Supports both EasyOCR and Tesseract with intelligent preprocessing
"""

try:
    import cv2
except ImportError:
    cv2 = None
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
try:
    import easyocr
except ImportError:
    easyocr = None
try:
    import pytesseract
except ImportError:
    pytesseract = None
import logging
from typing import List, Dict, Tuple, Optional
import re

class PrescriptionOCR:
    """
    Advanced OCR engine optimized for prescription images
    """
    
    def __init__(self, languages=['en'], use_gpu=False, fallback_to_tesseract=True):
        """
        Initialize OCR engines
        
        Args:
            languages: List of language codes for OCR
            use_gpu: Whether to use GPU for EasyOCR (requires CUDA)
            fallback_to_tesseract: Use Tesseract if EasyOCR fails
        """
        self.languages = languages
        self.fallback_to_tesseract = fallback_to_tesseract
        
        # Initialize EasyOCR
        try:
            if easyocr:
                self.easyocr_reader = easyocr.Reader(languages, gpu=use_gpu)
                self.easyocr_available = True
            else:
                self.easyocr_reader = None
                self.easyocr_available = False
        except Exception as e:
            logging.warning(f"EasyOCR initialization failed: {e}")
            self.easyocr_available = False
        
        # Test Tesseract availability
        try:
            pytesseract.get_tesseract_version()
            self.tesseract_available = True
        except Exception as e:
            logging.warning(f"Tesseract not available: {e}")
            self.tesseract_available = False
    
    def extract_text_smart(self, image_path: str) -> Dict:
        """
        Smart text extraction using best available method
        """
        if self.easyocr_available:
            try:
                # Use EasyOCR
                result = self.easyocr_reader.readtext(image_path, detail=0, paragraph=True)
                text = "\n".join(result)
                return {
                    "success": True,
                    "text": text,
                    "engine": "EasyOCR",
                    "avg_confidence": 0.9  # EasyOCR usually has higher accuracy
                }
            except Exception as e:
                logging.warning(f"EasyOCR failed: {e}")
                if self.fallback_to_tesseract and self.tesseract_available:
                    return self.extract_text_tesseract(image_path)
                else:
                    return {"success": False, "error": f"EasyOCR failed and Tesseract unavailable: {e}"}
        elif self.tesseract_available:
            return self.extract_text_tesseract(image_path)
        else:
            return {"success": False, "error": "No OCR engines available"}
    
    def extract_text_tesseract(self, image_path: str, psm=6, oem=3) -> Dict:
        """
        Extract text using Tesseract OCR
        """
        try:
            from PIL import Image
            
            # Open image
            image = Image.open(image_path)
            
            # Extract text
            text = pytesseract.image_to_string(image)
            
            # Clean text
            cleaned_text = self._clean_tesseract_text(text)
            
            return {
                "success": True,
                "text": cleaned_text,
                "engine": "Tesseract",
                "avg_confidence": 0.8  # Default confidence
            }
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _clean_tesseract_text(self, text: str) -> str:
        """Clean Tesseract extracted text"""
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        cleaned = '\n'.join(lines)
        cleaned = re.sub(r' +', ' ', cleaned)
        return cleaned
    
    def get_text_regions(self, image_path: str) -> List[Dict]:
        """Get text regions (basic implementation)"""
        return []