KeyarSrini commited on
Commit
79e4427
·
verified ·
1 Parent(s): 4fdf122

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
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
+ reader = easyocr.Reader(['en'], gpu=False)
13
+
14
+ def extract_text_lines(image: Image.Image) -> List[str]:
15
+ gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
16
+ gray = cv2.bilateralFilter(gray, 11, 17, 17)
17
+ lines = pytesseract.image_to_string(gray).splitlines()
18
+ return [line.strip() for line in lines if line.strip()]
19
+
20
+ def extract_receipt_data(lines: List[str]) -> dict:
21
+ data = {
22
+ "version": "v3.7 - Universal OCR Receipt Parser",
23
+ "RECEIPT/INVOICE_SUMMARY": {},
24
+ "LINE_ITEMS": [],
25
+ "HIGHLIGHTS": [],
26
+ "raw_lines": lines
27
+ }
28
+
29
+ for line in lines:
30
+ lower = line.lower()
31
+
32
+ if "name" in lower:
33
+ value = line.split("name")[-1].strip()
34
+ data["RECEIPT/INVOICE_SUMMARY"]["NAME"] = value
35
+ data["HIGHLIGHTS"].append({"type": "text", "value": "NAME", "line": line})
36
+ data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
37
+
38
+ elif "address" in lower:
39
+ value = line.split("address")[-1].strip()
40
+ data["RECEIPT/INVOICE_SUMMARY"]["ADDRESS"] = value
41
+ data["HIGHLIGHTS"].append({"type": "text", "value": "ADDRESS", "line": line})
42
+ data["HIGHLIGHTS"].append({"type": "value", "value": value, "line": line})
43
+
44
+ elif "phone" in lower:
45
+ match = re.search(r'(\+\d{1,3}\s)?\(?\d{2,4}\)?[\s.-]\d{3,4}[\s.-]\d{4}', line)
46
+ if match:
47
+ phone = match.group()
48
+ data["RECEIPT/INVOICE_SUMMARY"]["PHONE"] = phone
49
+ data["HIGHLIGHTS"].append({"type": "text", "value": "PHONE", "line": line})
50
+ data["HIGHLIGHTS"].append({"type": "value", "value": phone, "line": line})
51
+
52
+ elif "date" in lower or re.search(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', line):
53
+ date_match = re.search(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', line)
54
+ if date_match:
55
+ date = date_match.group()
56
+ data["RECEIPT/INVOICE_SUMMARY"]["DATE"] = date
57
+ data["HIGHLIGHTS"].append({"type": "text", "value": "DATE", "line": line})
58
+ data["HIGHLIGHTS"].append({"type": "value", "value": date, "line": line})
59
+
60
+ elif "total" in lower:
61
+ match = re.search(r'(\d+[.,]?\d*)$', line)
62
+ if match:
63
+ amount = match.group().replace(',', '')
64
+ data["RECEIPT/INVOICE_SUMMARY"]["TOTAL"] = amount
65
+ data["HIGHLIGHTS"].append({"type": "text", "value": "TOTAL", "line": line})
66
+ data["HIGHLIGHTS"].append({"type": "value", "value": amount, "line": line})
67
+
68
+ elif re.search(r'(\d+[.,]\d{2})$', line):
69
+ parts = line.rsplit(" ", 1)
70
+ if len(parts) == 2:
71
+ item, price = parts
72
+ data["LINE_ITEMS"].append({"Item": item.strip(), "Price": price.strip()})
73
+ data["HIGHLIGHTS"].append({"type": "text", "value": item.strip(), "line": line})
74
+ data["HIGHLIGHTS"].append({"type": "value", "value": price.strip(), "line": line})
75
+
76
+ return data
77
+
78
+ def highlight_image(image: Image.Image, data: dict) -> Image.Image:
79
+ draw = ImageDraw.Draw(image)
80
+ ocr_boxes = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
81
+ for i in range(len(ocr_boxes['text'])):
82
+ text = ocr_boxes['text'][i].strip()
83
+ if not text:
84
+ continue
85
+ x, y, w, h = ocr_boxes['left'][i], ocr_boxes['top'][i], ocr_boxes['width'][i], ocr_boxes['height'][i]
86
+ for item in data["HIGHLIGHTS"]:
87
+ if item['value'].lower() in text.lower():
88
+ color = 'green' if item['type'] == 'text' else 'blue'
89
+ draw.rectangle([x, y, x + w, y + h], outline=color, width=2)
90
+ return image
91
+
92
+ def analyze_receipt(image):
93
+ lines = extract_text_lines(image)
94
+ parsed_data = extract_receipt_data(lines)
95
+ highlighted_img = highlight_image(image.copy(), parsed_data)
96
+ return highlighted_img, parsed_data
97
+
98
+ demo = gr.Interface(
99
+ fn=analyze_receipt,
100
+ inputs=gr.Image(type="pil"),
101
+ outputs=[gr.Image(label="Highlighted Receipt"), gr.JSON(label="Extracted JSON")],
102
+ title="v3.7 Dynamic OCR Receipt Parser",
103
+ description="Upload any printed or handwritten receipt and get structured data with highlighted labels and values."
104
+ )
105
+
106
+ demo.launch()