File size: 5,206 Bytes
4bf0aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import sys
import json
import base64
import cv2
import numpy as np
import easyocr
import logging
import traceback

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Global reader instance
_reader = None

def get_reader():
    global _reader
    if _reader is None:
        # Initialize with English
        _reader = easyocr.Reader(['en'], gpu=False)
    return _reader

def process_image(image_data):
    try:
        reader = get_reader()

        # Decode base64 image
        if ',' in image_data:
            image_data = image_data.split(',')[1]
        
        image_bytes = base64.b64decode(image_data)
        nparr = np.frombuffer(image_bytes, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        if img is None:
            raise ValueError("Could not decode image")

        # Run OCR
        result = reader.readtext(img)

        extracted_text = []
        structured_data = []

        # Process EasyOCR results
        for item in result:
            bbox, text, confidence = item
            
            # Convert bbox points to standard list of lists
            box = [[float(pt[0]), float(pt[1])] for pt in bbox]
            
            extracted_text.append(text)
            structured_data.append({
                "text": text,
                "confidence": float(confidence),
                "box": box
            })

        # Reconstruct lines based on Y-coordinates
        lines = []
        if structured_data:
            def get_y_min(item):
                box = item['box']
                return box[0][1]

            structured_data.sort(key=get_y_min)
            
            current_line = []
            current_y = -1
            y_threshold = 20  # Pixel threshold for same line
            
            for item in structured_data:
                box = item['box']
                y_center = (box[0][1] + box[2][1]) / 2
                
                if current_y == -1:
                    current_y = y_center
                    current_line.append(item)
                elif abs(y_center - current_y) < y_threshold:
                    current_line.append(item)
                else:
                    # Sort current line by X-coordinate
                    def get_x_min(item):
                        b = item['box']
                        return b[0][0]

                    current_line.sort(key=get_x_min)
                    lines.append(current_line)
                    current_line = [item]
                    current_y = y_center
            
            if current_line:
                def get_x_min(item):
                    b = item['box']
                    return b[0][0]
                current_line.sort(key=get_x_min)
                lines.append(current_line)

        # Build full text from lines with enhancement (User request)
        import re
        final_lines = []
        for line in lines:
            line_text = " ".join([str(item['text']) for item in line])
            
            # 1. Filter out "thank you" and "visit" phrases
            junk_keywords = ["thank you", "visit again", "thanks", "welcome", "have a nice day", "visit us", "come again"]
            if any(k in line_text.lower() for k in junk_keywords):
                continue
            
            # 2. Remove any numbers (User request: "dont add any number")
            line_text = re.sub(r'\d+', '', line_text)
            
            # Clean up extra whitespace and punctuation
            line_text = re.sub(r'\s+', ' ', line_text).strip()
            
            # Skip empty lines or lines with no alphanumeric characters
            if line_text and any(c.isalnum() for c in line_text):
                final_lines.append(line_text)
            
        full_text = "\n".join(final_lines)
        
        engine_type = "easyocr" # Define engine_type as requested
        return {
            "success": True,
            "text": full_text,
            "data": structured_data,
            "engine": engine_type
        }

    except Exception as e:
        logger.error(f"OCR processing failed: {str(e)}")
        logger.error(traceback.format_exc())
        return {
            "success": False,
            "error": str(e)
        }

if __name__ == "__main__":
    try:
        # Read input from stdin
        input_data = sys.stdin.read()
        if not input_data:
            print(json.dumps({"success": False, "error": "No input data received"}))
            sys.exit(1)

        try:
            request = json.loads(input_data)
        except json.JSONDecodeError:
             print(json.dumps({"success": False, "error": "Invalid JSON input"}))
             sys.exit(1)
            
        image_base64 = request.get("imageBase64")
        
        if not image_base64:
            print(json.dumps({"success": False, "error": "imageBase64 is required"}))
            sys.exit(1)

        result = process_image(image_base64)
        print(json.dumps(result))

    except Exception as e:
        print(json.dumps({"success": False, "error": f"Unexpected error: {str(e)}"}))
        sys.exit(1)