Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,329 +1,118 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
from pytesseract import Output
|
| 4 |
import cv2
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
-
|
| 7 |
-
import re
|
| 8 |
import json
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
|
| 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 |
-
#
|
| 18 |
-
|
| 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
|
| 33 |
-
|
| 34 |
-
gray = cv2.
|
| 35 |
-
|
| 36 |
-
|
| 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
|
| 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 |
-
"
|
| 97 |
-
"
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"
|
| 101 |
-
"Items": [],
|
| 102 |
-
"Vendor Name": None,
|
| 103 |
-
"Vendor Address": None
|
| 104 |
}
|
| 105 |
-
|
| 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 |
-
|
| 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 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
if
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
if
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 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(
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
for item in data["
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 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
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 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 |
-
#
|
| 320 |
-
|
| 321 |
-
fn=
|
| 322 |
-
inputs=gr.Image(type="
|
| 323 |
-
outputs=[
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
| 326 |
)
|
| 327 |
|
| 328 |
if __name__ == "__main__":
|
| 329 |
-
|
|
|
|
| 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()
|