Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (v3.8.3 - Improved OCR Matching for Multilingual Handwritten Receipts)
|
| 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, ImageEnhance
|
| 10 |
+
from typing import List
|
| 11 |
+
|
| 12 |
+
# EasyOCR reader for multilingual support
|
| 13 |
+
reader = easyocr.Reader(['en', 'ch_sim'], gpu=False)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 17 |
+
image = image.convert("L") # grayscale
|
| 18 |
+
image = ImageEnhance.Contrast(image).enhance(2.5)
|
| 19 |
+
image = image.resize((image.width * 2, image.height * 2))
|
| 20 |
+
np_img = np.array(image)
|
| 21 |
+
np_img = cv2.adaptiveThreshold(np_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 22 |
+
cv2.THRESH_BINARY, 11, 2)
|
| 23 |
+
return np_img
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def extract_text_lines(image: Image.Image) -> List[str]:
|
| 27 |
+
preprocessed = preprocess_image(image)
|
| 28 |
+
lines = reader.readtext(preprocessed, detail=0)
|
| 29 |
+
return [line.strip() for line in lines if line.strip()]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def extract_receipt_data(lines: List[str]) -> dict:
|
| 33 |
+
data = {
|
| 34 |
+
"version": "v3.8.3 - Hugging Face Dynamic OCR",
|
| 35 |
+
"RECEIPT/INVOICE_SUMMARY": {},
|
| 36 |
+
"LINE_ITEMS": [],
|
| 37 |
+
"HIGHLIGHTS": [],
|
| 38 |
+
"raw_lines": lines
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
for line in lines:
|
| 42 |
+
lower = line.lower()
|
| 43 |
+
|
| 44 |
+
if "name" in lower:
|
| 45 |
+
value = re.sub(".*name", "", lower, flags=re.IGNORECASE).strip()
|
| 46 |
+
data["RECEIPT/INVOICE_SUMMARY"]["RECEIVER_NAME"] = value
|
| 47 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": "name", "line": line})
|
| 48 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
|
| 49 |
+
|
| 50 |
+
elif "address" in lower:
|
| 51 |
+
value = re.sub(".*address", "", lower, flags=re.IGNORECASE).strip()
|
| 52 |
+
data["RECEIPT/INVOICE_SUMMARY"]["RECEIVER_ADDRESS"] = value
|
| 53 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": "address", "line": line})
|
| 54 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
|
| 55 |
+
|
| 56 |
+
elif "phone" in lower or "tel" in lower:
|
| 57 |
+
phone_match = re.search(r'[\d\-]{6,}', line)
|
| 58 |
+
if phone_match:
|
| 59 |
+
phone = phone_match.group()
|
| 60 |
+
data["RECEIPT/INVOICE_SUMMARY"]["RECEIVER_PHONE"] = phone
|
| 61 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": "phone", "line": line})
|
| 62 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": phone, "line": line})
|
| 63 |
+
|
| 64 |
+
elif "total" in lower:
|
| 65 |
+
match = re.search(r'(\d+[\s,.]?\d*)$', line)
|
| 66 |
+
if match:
|
| 67 |
+
value = match.group().replace(",", "").strip()
|
| 68 |
+
data["RECEIPT/INVOICE_SUMMARY"]["TOTAL"] = value
|
| 69 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": "total", "line": line})
|
| 70 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
|
| 71 |
+
|
| 72 |
+
elif "tax" in lower:
|
| 73 |
+
match = re.search(r'(\d+[\s,.]?\d*)$', line)
|
| 74 |
+
if match:
|
| 75 |
+
value = match.group().replace(",", "").strip()
|
| 76 |
+
data["RECEIPT/INVOICE_SUMMARY"]["TAX"] = value
|
| 77 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": "tax", "line": line})
|
| 78 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
|
| 79 |
+
|
| 80 |
+
elif re.search(r'(\d+[.,]\d{2})$', line):
|
| 81 |
+
parts = line.rsplit(" ", 1)
|
| 82 |
+
if len(parts) == 2:
|
| 83 |
+
item, price = parts
|
| 84 |
+
data["LINE_ITEMS"].append({"Item": item.strip(), "Price": price.strip()})
|
| 85 |
+
data["HIGHLIGHTS"].append({"type": "text", "value": item.strip(), "line": line})
|
| 86 |
+
data["HIGHLIGHTS"].append({"type": "value", "value": price.strip(), "line": line})
|
| 87 |
+
|
| 88 |
+
return data
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def highlight_image(image: Image.Image, data: dict) -> Image.Image:
|
| 92 |
+
draw = ImageDraw.Draw(image)
|
| 93 |
+
ocr = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
|
| 94 |
+
for i, text in enumerate(ocr['text']):
|
| 95 |
+
if not text.strip():
|
| 96 |
+
continue
|
| 97 |
+
x, y, w, h = ocr['left'][i], ocr['top'][i], ocr['width'][i], ocr['height'][i]
|
| 98 |
+
for item in data.get("HIGHLIGHTS", []):
|
| 99 |
+
if item['value'].lower() in text.lower():
|
| 100 |
+
color = 'green' if item['type'] == 'text' else 'blue'
|
| 101 |
+
draw.rectangle([x, y, x + w, y + h], outline=color, width=2)
|
| 102 |
+
return image
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def analyze_receipt(image):
|
| 106 |
+
try:
|
| 107 |
+
lines = extract_text_lines(image)
|
| 108 |
+
parsed_data = extract_receipt_data(lines)
|
| 109 |
+
highlighted_img = highlight_image(image.copy(), parsed_data)
|
| 110 |
+
return highlighted_img, parsed_data
|
| 111 |
+
except Exception as e:
|
| 112 |
+
return image, {"error": str(e), "version": "v3.8.3"}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
iface = gr.Interface(
|
| 116 |
+
fn=analyze_receipt,
|
| 117 |
+
inputs=gr.Image(type="pil", label="Upload Receipt Image"),
|
| 118 |
+
outputs=[
|
| 119 |
+
gr.Image(label="Highlighted Receipt Fields"),
|
| 120 |
+
gr.JSON(label="Extracted JSON Output")
|
| 121 |
+
],
|
| 122 |
+
title="v3.8.3 - Dynamic OCR Receipt Parser",
|
| 123 |
+
description="Upload any printed or handwritten receipt (multilingual supported). Extracts structured JSON and highlights fields."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
iface.launch()
|