KeyarSrini commited on
Commit
511d413
·
verified ·
1 Parent(s): 5dacd96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -313
app.py CHANGED
@@ -1,329 +1,118 @@
1
- import easyocr
2
- import pytesseract
3
- from pytesseract import Output
4
  import cv2
 
5
  import numpy as np
6
- from PIL import Image
7
- import re
8
  import json
9
- import gradio as gr
10
-
11
- # Initialize OCR readers for required languages.
12
- # EasyOCR: specify languages list (English, Chinese Simplified, Tamil for example).
13
- # Tesseract: we will specify languages in pytesseract calls as needed.
14
- EASYOCR_LANGS = ['en', 'ch_sim', 'ta'] # English, Chinese Simplified, Tamil
15
- easyocr_reader = easyocr.Reader(EASYOCR_LANGS, gpu=False) # using CPU for compatibility
16
 
17
- # Predefined keyword sets for labels in various languages (for label detection)
18
- LABEL_KEYWORDS = {
19
- 'name': ['name', 'bill to', 'sold to', 'customer', 'client', 'नाम'], # 'नाम' (Hindi for name) as example
20
- 'address': ['address', 'addr', 'முகவரி', '地址'], # Tamil "முகவரி", Chinese "地址"
21
- 'city': ['city', 'நகரம்', '城市'],
22
- 'zip': ['zip', 'postal', '邮编', 'அஞ்சல்'],
23
- 'phone': ['phone', 'tel', 'telephone', 'ph:', 'தொலைபேசி', '电话'],
24
- 'date': ['date', 'dated', 'தேதி', '日期'],
25
- 'total': ['total', 'grand total', 'amount due', 'மொத்தம்', '总计', '合计'],
26
- 'tax': ['tax', 'gst', 'vat', 'தி.உ', 'வரி', '税'], # 'வரி' is Tamil for tax
27
- 'subtotal': ['subtotal', 'sub total', 'முதல் தொகை', '小计']
28
- }
29
- # Flatten label keywords for easy checking
30
- LABEL_WORDS_FLAT = {word.lower(): field for field, words in LABEL_KEYWORDS.items() for word in words}
31
 
32
- def preprocess_image(img: np.ndarray) -> np.ndarray:
33
- """Convert image to grayscale and apply threshold to improve OCR."""
34
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
35
- # Apply slight blur to reduce noise
36
- gray = cv2.medianBlur(gray, 3)
37
- # Apply adaptive threshold or Otsu's threshold
38
- # Here, use Otsu to binarize (good for uniform background like receipts)
39
- _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
40
- return thresh
41
 
42
- def run_ocr(img: np.ndarray):
43
- """Run EasyOCR and Tesseract OCR on the image and return combined results."""
44
- # EasyOCR detection
45
- easy_results = easyocr_reader.readtext(img, detail=1) # list of tuples: (bbox, text, confidence)
46
- ocr_elements = [] # will store dicts with text and bbox
47
-
48
- for bbox, text, conf in easy_results:
49
- if text.strip() == '':
50
- continue
51
- # Get bounding box as x, y, w, h
52
- # easyocr bbox is [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] (possibly rotated quadrilateral)
53
- coords = np.array(bbox).astype(int)
54
- x, y = coords[:,0].min(), coords[:,1].min()
55
- w, h = coords[:,0].max() - x, coords[:,1].max() - y
56
- ocr_elements.append({
57
- "text": text.strip(),
58
- "conf": float(conf),
59
- "bbox": (int(x), int(y), int(w), int(h))
60
- })
61
-
62
- # Tesseract detection (word-level)
63
- # We'll use pytesseract image_to_data to get bounding boxes of words for additional robustness
64
- tess_config = "--psm 6" # Assume a block of text with some lines (PSM 6 = assume uniform text block)
65
- tess_data = pytesseract.image_to_data(img, lang="eng+tam+chi_sim", config=tess_config, output_type=Output.DICT)
66
- n_boxes = len(tess_data['text'])
67
- for i in range(n_boxes):
68
- text = tess_data['text'][i]
69
- conf = int(tess_data['conf'][i]) if tess_data['conf'][i].isdigit() else -1
70
- if conf < 0 or text.strip() == '':
71
- continue
72
- x, y, w, h = tess_data['left'][i], tess_data['top'][i], tess_data['width'][i], tess_data['height'][i]
73
- # Check if this text is already present (to avoid duplicates with easyocr)
74
- # We use a simple fuzzy match: same text and coordinates overlapping significantly
75
- duplicate = False
76
- for elem in ocr_elements:
77
- if elem['text'].lower() == text.strip().lower():
78
- # Compute overlap
79
- ex, ey, ew, eh = elem['bbox']
80
- if (abs(ex - x) < 10 and abs(ey - y) < 10):
81
- duplicate = True
82
- break
83
- if not duplicate:
84
- ocr_elements.append({
85
- "text": text.strip(),
86
- "conf": float(conf) if conf >= 0 else 0.0,
87
- "bbox": (int(x), int(y), int(w), int(h))
88
- })
89
- return ocr_elements
90
-
91
- def classify_and_extract(ocr_elements):
92
- """Classify OCR text elements into fields and assemble structured data."""
93
- # Sort elements top-to-bottom, left-to-right (approximate reading order)
94
- ocr_elements.sort(key=lambda el: (el['bbox'][1], el['bbox'][0]))
95
  data = {
96
- "Name": None,
97
- "Address": None, "City": None, "ZIP Code": None, "Phone": None,
98
- "Date": None,
99
- "Total": None,
100
- "Tax": None,
101
- "Items": [],
102
- "Vendor Name": None,
103
- "Vendor Address": None
104
  }
105
- # We will determine vendor info from top lines, and items from bottom lines
106
- lines = [] # group text by line using y coordinate
107
- current_line_y = -1
108
- line_buffer = []
109
- for elem in ocr_elements:
110
- x, y, w, h = elem['bbox']
111
- text = elem['text']
112
- if current_line_y < 0:
113
- current_line_y = y
114
- # If this element's y is within the same line (threshold h/2)
115
- if y <= current_line_y + h//2:
116
- line_buffer.append(elem)
117
- else:
118
- # new line
119
- # sort the current line by x and form text
120
- line_buffer.sort(key=lambda el: el['bbox'][0])
121
- line_text = " ".join([e['text'] for e in line_buffer])
122
- lines.append({"text": line_text, "elems": line_buffer})
123
- # reset for new line
124
- line_buffer = [elem]
125
- current_line_y = y
126
- # Add last line
127
- if line_buffer:
128
- line_buffer.sort(key=lambda el: el['bbox'][0])
129
- line_text = " ".join([e['text'] for e in line_buffer])
130
- lines.append({"text": line_text, "elems": line_buffer})
131
-
132
- # Identify vendor section (top of receipt until we hit a known field or item)
133
- vendor_lines = []
134
- other_lines = []
135
  for line in lines:
136
- text = line['text'].strip()
137
- # If this line contains a label keyword like "Date" or "Total", we consider that the end of vendor info.
138
- lower_text = text.lower()
139
- if any(lbl in lower_text for lbl in ['date', 'total', 'subtotal', 'tax']) or re.search(r'\d{1,2}/\d{1,2}/\d{2,4}', text):
140
- other_lines.append(line)
141
- elif len(other_lines) == 0:
142
- # If we haven't started other_lines (no break triggered yet), it's still vendor info
143
- vendor_lines.append(line)
144
- else:
145
- other_lines.append(line)
146
- # Determine Vendor Name and Address from vendor_lines
147
- if vendor_lines:
148
- # Vendor Name: first line
149
- data["Vendor Name"] = vendor_lines[0]['text']
150
- # Vendor Address: all subsequent lines concatenated
151
- if len(vendor_lines) > 1:
152
- addr_lines = [v['text'] for v in vendor_lines[1:]]
153
- data["Vendor Address"] = " ".join(addr_lines)
154
- # Attempt to split city, zip, etc. if possible
155
- addr_text = data["Vendor Address"]
156
- zip_match = re.search(r'\b\d{5,6}\b', addr_text) # 5 or 6 digit code
157
- if zip_match:
158
- zip_code = zip_match.group()
159
- data["ZIP Code"] = zip_code
160
- # City might be the word immediately before the ZIP code
161
- before_zip = addr_text[:zip_match.start()].rstrip(", ")
162
- # Take the last token of before_zip as City (assuming "City, ST")
163
- city_parts = before_zip.split()
164
- if city_parts:
165
- data["City"] = city_parts[-1].rstrip(",")
166
- # If there's a phone in vendor address lines (like "Tel: 123456"), capture it
167
- phone_match = re.search(r'\+?\d[\d\-\s]{6,}', addr_text)
168
- if phone_match:
169
- data["Phone"] = phone_match.group().strip()
170
- # Now process other_lines to find explicit labels and values
171
- for line in other_lines:
172
- text = line['text']
173
- lower = text.lower()
174
- # Check for known field labels in this line
175
- for label_word, field in LABEL_WORDS_FLAT.items():
176
- if label_word in lower:
177
- # e.g., if "date" in line, then this line likely contains Date and its value
178
- if field.lower() == "date":
179
- # Extract date value from line (by taking a date pattern or text after label)
180
- date_match = re.search(r'\d{1,2}[\/\-\.\s]\d{1,2}[\/\-\.\s]\d{2,4}', text)
181
- if date_match:
182
- data["Date"] = date_match.group()
183
- else:
184
- # If no obvious date pattern, take text after the label word
185
- idx = lower.index(label_word) + len(label_word)
186
- date_value = text[idx:].strip(" :.-")
187
- if date_value:
188
- data["Date"] = date_value
189
- elif field.lower() == "total":
190
- # Extract total amount (last number in the line, perhaps)
191
- amt_match = re.findall(r'[0-9]+(?:\.[0-9]{1,2})?', text)
192
- if amt_match:
193
- data["Total"] = amt_match[-1] # last number is likely total
194
- elif field.lower() in ["tax", "gst", "vat"]:
195
- amt_match = re.findall(r'[0-9]+(?:\.[0-9]{1,2})?', text)
196
- if amt_match:
197
- data["Tax"] = amt_match[-1]
198
- elif field.lower() == "phone":
199
- phone_match = re.search(r'\+?\d[\d\-\s]{6,}', text)
200
- if phone_match:
201
- data["Phone"] = phone_match.group().strip()
202
- elif field.lower() == "name" and "name" in lower:
203
- # Get text after 'Name' or so
204
- idx = lower.index(label_word) + len(label_word)
205
- name_val = text[idx:].strip(" :.-")
206
- if name_val:
207
- data["Name"] = name_val
208
- # We handle address, city, zip below if present as separate lines
209
- # If line looks like an item (contains price and not identified yet as known field):
210
- if re.search(r'[0-9]+(?:\.[0-9]{1,2})', text) and ("total" not in lower and "tax" not in lower):
211
- # Potential item line (has a number but not a total/tax line)
212
- # Attempt to split item line into parts: description, quantity, price, total
213
- parts = text.split()
214
- # If last part is a number and one of the earlier parts has 'x' or is a number, we interpret it
215
- price = None
216
- qty = None
217
- item_name = None
218
- if parts:
219
- # If last token is numeric, treat it as item total price
220
- if re.match(r'^[0-9]+(?:\.[0-9]{1,2})?$', parts[-1]):
221
- price = parts[-1]
222
- parts = parts[:-1]
223
- # If first token has an 'x' (like 2xItem or 2x), separate quantity
224
- if parts and 'x' in parts[0].lower():
225
- qty_token = parts[0]
226
- qty = re.findall(r'\d+', qty_token)
227
- qty = qty[0] if qty else None
228
- # Remove quantity token from parts
229
- parts = parts[1:]
230
- elif parts and re.match(r'^\d+$', parts[0]):
231
- # If first part is just a number (quantity)
232
- qty = parts[0]
233
- parts = parts[1:]
234
- # Remaining parts form the item description
235
- if parts:
236
- item_name = " ".join(parts)
237
- item_entry = {
238
- "description": item_name if item_name else text,
239
- "quantity": qty,
240
- "unit_price": None,
241
- "total_price": price
242
- }
243
- data["Items"].append(item_entry)
244
- # If no explicit Total label was found, as fallback use the largest monetary value as Total
245
- if data["Total"] is None:
246
- all_numbers = []
247
- for m in re.findall(r'[0-9]+(?:\.[0-9]{1,2})?', " ".join([l['text'] for l in lines])):
248
- try:
249
- all_numbers.append(float(m))
250
- except:
251
- continue
252
- if all_numbers:
253
- max_val = max(all_numbers)
254
- # If a Tax exists, ensure Total is >= Tax
255
- if data["Tax"]:
256
- total_candidate = max_val if max_val >= float(data["Tax"]) else None
257
- else:
258
- total_candidate = max_val
259
- if total_candidate:
260
- data["Total"] = f"{total_candidate:.2f}"
261
  return data
262
 
263
- def highlight_image(img: np.ndarray, ocr_elements, data):
264
- """Draw bounding boxes on the image for labels (green) and values (blue)."""
265
- result_img = img.copy()
266
- # Mark all label keywords found
267
- # We can derive which elements correspond to labels vs values by checking the data we extracted.
268
- # Create sets of values from data for quick matching (strings)
269
- value_texts = set()
270
- for key, val in data.items():
271
- if key == "Items":
272
- for item in data["Items"]:
273
- # include each item field as value text
274
- for v in item.values():
275
- if v:
276
- value_texts.add(str(v))
277
- else:
278
- if val:
279
- value_texts.add(str(val))
280
- label_texts = set() # any label keywords that appeared
281
- for field, words in LABEL_KEYWORDS.items():
282
- for w in words:
283
- # if that word appears in any OCR text element, mark it as label_text
284
- for elem in ocr_elements:
285
- if re.fullmatch(re.escape(w), elem['text'], flags=re.IGNORECASE):
286
- label_texts.add(elem['text'])
287
- # Draw boxes
288
- for elem in ocr_elements:
289
- x, y, w, h = elem['bbox']
290
- text = elem['text']
291
- color = None
292
- if text in label_texts:
293
- color = (0, 255, 0) # green for labels
294
- elif text in value_texts or text.strip().strip(':').lower() in LABEL_WORDS_FLAT:
295
- # Mark as value if text matches extracted value or if it's likely a value (not a label keyword)
296
- color = (255, 0, 0) # blue for values
297
- if color:
298
- cv2.rectangle(result_img, (x, y), (x+w, y+h), color, 2)
299
- return result_img
300
 
301
- def process_receipt(image: np.ndarray):
302
- """Main function to process the receipt image and return annotated image and JSON data."""
303
- if image is None:
304
- return None, "{}"
305
- # Convert to numpy array (in case PIL image is provided by Gradio)
306
- img = np.array(image)
307
- # Preprocess
308
- proc = preprocess_image(img)
309
- # OCR
310
- ocr_elems = run_ocr(proc)
311
- # Classify and extract fields
312
- data = classify_and_extract(ocr_elems)
313
- # Highlight image
314
- highlighted = highlight_image(img, ocr_elems, data)
315
- # Convert data to JSON string (pretty formatted)
316
- json_output = json.dumps(data, indent=2, ensure_ascii=False)
317
- return Image.fromarray(highlighted), json_output
318
 
319
- # Set up Gradio Interface
320
- demo = gr.Interface(
321
- fn=process_receipt,
322
- inputs=gr.Image(type="numpy", label="Upload Receipt Image"),
323
- outputs=[gr.Image(label="Detected Fields Highlighted"), gr.JSON(label="Extracted Data")],
324
- title="Multilingual Receipt OCR Parser",
325
- description="Upload a receipt image (printed or handwritten, English/தமிழ்/中文 etc.) to extract structured data. Field labels are highlighted in green and values in blue on the image."
 
 
 
326
  )
327
 
328
  if __name__ == "__main__":
329
- demo.launch()
 
1
+ # app.py (v3.8.1 - Hugging Face Compatible, Fixed EasyOCR Languages)
2
+ import gradio as gr
 
3
  import cv2
4
+ import easyocr
5
  import numpy as np
6
+ import pytesseract
 
7
  import json
8
+ import re
9
+ from PIL import Image, ImageDraw
10
+ from typing import List
 
 
 
 
11
 
12
+ # EasyOCR reader - Only 'en' and 'ch_sim' allowed together
13
+ reader = easyocr.Reader(['en', 'ch_sim'], gpu=False)
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def extract_text_lines(image: Image.Image) -> List[str]:
16
+ gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
17
+ gray = cv2.bilateralFilter(gray, 11, 17, 17)
18
+ lines = pytesseract.image_to_string(gray).splitlines()
19
+ return [line.strip() for line in lines if line.strip()]
 
 
 
 
20
 
21
+ def extract_receipt_data(lines: List[str]) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  data = {
23
+ "version": "v3.8.1 - Hugging Face Compatible OCR",
24
+ "RECEIPT/INVOICE_SUMMARY": {},
25
+ "LINE_ITEMS": [],
26
+ "HIGHLIGHTS": [],
27
+ "raw_lines": lines
 
 
 
28
  }
29
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  for line in lines:
31
+ lower = line.lower()
32
+
33
+ if "name" in lower:
34
+ value = line.split("name")[-1].strip()
35
+ data["RECEIPT/INVOICE_SUMMARY"]["NAME"] = value
36
+ data["HIGHLIGHTS"].append({"type": "text", "value": "NAME", "line": line})
37
+ data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
38
+
39
+ elif "address" in lower:
40
+ value = line.split("address")[-1].strip()
41
+ data["RECEIPT/INVOICE_SUMMARY"]["ADDRESS"] = value
42
+ data["HIGHLIGHTS"].append({"type": "text", "value": "ADDRESS", "line": line})
43
+ data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
44
+
45
+ elif "phone" in lower:
46
+ match = re.search(r'(\+\d{1,3}\s)?\(?\d{2,4}\)?[\s.-]\d{3,4}[\s.-]\d{4}', line)
47
+ if match:
48
+ phone = match.group()
49
+ data["RECEIPT/INVOICE_SUMMARY"]["PHONE"] = phone
50
+ data["HIGHLIGHTS"].append({"type": "text", "value": "PHONE", "line": line})
51
+ data["HIGHLIGHTS"].append({"type": "value", "value": phone, "line": line})
52
+
53
+ elif "date" in lower or re.search(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', line):
54
+ date_match = re.search(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', line)
55
+ if date_match:
56
+ date = date_match.group()
57
+ data["RECEIPT/INVOICE_SUMMARY"]["DATE"] = date
58
+ data["HIGHLIGHTS"].append({"type": "text", "value": "DATE", "line": line})
59
+ data["HIGHLIGHTS"].append({"type": "value", "value": date, "line": line})
60
+
61
+ elif "total" in lower:
62
+ match = re.search(r'(\d+[.,]?[\d]*)$', line)
63
+ if match:
64
+ amount = match.group().replace(',', '')
65
+ data["RECEIPT/INVOICE_SUMMARY"]["TOTAL"] = amount
66
+ data["HIGHLIGHTS"].append({"type": "text", "value": "TOTAL", "line": line})
67
+ data["HIGHLIGHTS"].append({"type": "value", "value": amount, "line": line})
68
+
69
+ elif re.search(r'(\d+[.,]\d{2})$', line):
70
+ parts = line.rsplit(" ", 1)
71
+ if len(parts) == 2:
72
+ item, price = parts
73
+ data["LINE_ITEMS"].append({"Item": item.strip(), "Price": price.strip()})
74
+ data["HIGHLIGHTS"].append({"type": "text", "value": item.strip(), "line": line})
75
+ data["HIGHLIGHTS"].append({"type": "value", "value": price.strip(), "line": line})
76
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  return data
78
 
79
+ def highlight_image(image: Image.Image, data: dict) -> Image.Image:
80
+ draw = ImageDraw.Draw(image)
81
+ ocr_boxes = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
82
+ for i in range(len(ocr_boxes['text'])):
83
+ text = ocr_boxes['text'][i].strip()
84
+ if not text:
85
+ continue
86
+ try:
87
+ x, y, w, h = ocr_boxes['left'][i], ocr_boxes['top'][i], ocr_boxes['width'][i], ocr_boxes['height'][i]
88
+ for item in data["HIGHLIGHTS"]:
89
+ if item['value'].lower() in text.lower():
90
+ color = 'green' if item['type'] == 'text' else 'blue'
91
+ draw.rectangle([x, y, x + w, y + h], outline=color, width=2)
92
+ except Exception as e:
93
+ print("Highlighting error:", e)
94
+ return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
+ def analyze_receipt(image):
97
+ try:
98
+ lines = extract_text_lines(image)
99
+ parsed_data = extract_receipt_data(lines)
100
+ highlighted_img = highlight_image(image.copy(), parsed_data)
101
+ return highlighted_img, parsed_data
102
+ except Exception as e:
103
+ return image, {"error": str(e), "version": "v3.8.1"}
 
 
 
 
 
 
 
 
 
104
 
105
+ # Hugging Face Spaces UI
106
+ iface = gr.Interface(
107
+ fn=analyze_receipt,
108
+ inputs=gr.Image(type="pil", label="Upload Receipt Image"),
109
+ outputs=[
110
+ gr.Image(label="Highlighted Receipt Fields"),
111
+ gr.JSON(label="Extracted JSON Output")
112
+ ],
113
+ title="v3.8.1 - Hugging Face Dynamic OCR Receipt Parser",
114
+ description="Upload printed or handwritten receipt images in English or Chinese. Outputs structured JSON data and highlighted fields."
115
  )
116
 
117
  if __name__ == "__main__":
118
+ iface.launch()