KeyarSrini commited on
Commit
b3b3ed7
Β·
verified Β·
1 Parent(s): 9b26e48

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw
3
+ import easyocr
4
+ import numpy as np
5
+ import re
6
+
7
+ VERSION = "v3.1 - Structured OCR Parser with Address + Multiline Items"
8
+
9
+ reader = easyocr.Reader(['en'], gpu=False)
10
+
11
+ def clean_text(text):
12
+ return re.sub(r"[^a-zA-Z0-9@.,:/\-&\s]", "", text).strip()
13
+
14
+ def parse_price(value):
15
+ value = value.replace(" ", "").replace(",", ".")
16
+ return re.findall(r"\d+\.\d{2}", value)
17
+
18
+ def process_receipt(image: Image.Image):
19
+ img = np.array(image.convert("RGB"))
20
+ results = reader.readtext(img, detail=1)
21
+ draw = ImageDraw.Draw(image)
22
+
23
+ lines = []
24
+ for (bbox, text, conf) in results:
25
+ clean = clean_text(text)
26
+ if clean:
27
+ lines.append(clean)
28
+ draw.rectangle([tuple(bbox[0]), tuple(bbox[2])], outline="green", width=2)
29
+
30
+ summary = {}
31
+ items = []
32
+ vendor_address_parts = []
33
+ item_buffer = []
34
+ last_price = None
35
+
36
+ for i, line in enumerate(lines):
37
+ low = line.lower()
38
+
39
+ # πŸ‘€ Name
40
+ if "name" in low and not summary.get("RECEIVER_NAME"):
41
+ maybe_name = lines[i+1] if i+1 < len(lines) else ""
42
+ summary["RECEIVER_NAME"] = maybe_name
43
+
44
+ # πŸ—“οΈ Date
45
+ if "date" in low:
46
+ date_line = lines[i+1] if i+1 < len(lines) else line
47
+ date_match = re.findall(r"\d{1,2}[/\- ]\d{1,2}[/\- ]\d{2,4}", date_line)
48
+ if not date_match:
49
+ part_date = re.findall(r"\d{1,2}", date_line)
50
+ year_match = re.findall(r"19\d{2}|20\d{2}", " ".join(lines[i:i+3]))
51
+ if part_date and year_match:
52
+ summary["INVOICE_RECEIPT_DATE"] = f"{part_date[0]} / {year_match[0]}"
53
+ elif date_match:
54
+ summary["INVOICE_RECEIPT_DATE"] = date_match[0]
55
+
56
+ # ☎️ Phone
57
+ if re.search(r"\d{3}[-\s]\d{4}", line):
58
+ summary["RECEIVER_PHONE"] = re.search(r"\d{3}[-\s]\d{4}", line).group()
59
+
60
+ # πŸ™ Address block
61
+ if "store" in low or "book" in low:
62
+ summary["NAME"] = line
63
+ vendor_address_parts.append(line)
64
+ elif "avenue" in low or "road" in low or "pacific" in low:
65
+ vendor_address_parts.append(line)
66
+ elif "calif" in low or "zip" in low or re.search(r"\d{5}", line):
67
+ vendor_address_parts.append(line)
68
+ elif re.match(r"\d{3}[-\s]?\d{4}", line):
69
+ vendor_address_parts.append(line)
70
+
71
+ # 🧾 Tax and Total
72
+ if "tax" in low and not summary.get("TAX"):
73
+ prices = parse_price(line)
74
+ if prices:
75
+ summary["TAX"] = prices[0]
76
+
77
+ if "total" in low and not summary.get("TOTAL"):
78
+ prices = parse_price(line)
79
+ if prices:
80
+ summary["TOTAL"] = prices[0]
81
+
82
+ # 🧠 Group line items
83
+ price = parse_price(line)
84
+ if price:
85
+ last_price = price[0]
86
+ elif last_price:
87
+ item_buffer.append(line)
88
+ if len(item_buffer) >= 2:
89
+ full_item = " ".join(item_buffer)
90
+ items.append({"Item": full_item, "Price": last_price})
91
+ item_buffer = []
92
+ last_price = None
93
+
94
+ if vendor_address_parts:
95
+ summary["VENDOR_ADDRESS"] = ", ".join(vendor_address_parts)
96
+
97
+ result = {
98
+ "version": VERSION,
99
+ "RECEIPT/INVOICE_SUMMARY": summary,
100
+ "LINE_ITEMS": items
101
+ }
102
+
103
+ return result, image
104
+
105
+ # Gradio UI
106
+ with gr.Blocks(title=VERSION) as demo:
107
+ gr.Markdown(f"# πŸ“„ {VERSION}")
108
+ gr.Markdown("Upload a receipt (including handwritten). Extracts full invoice summary + item list.")
109
+
110
+ with gr.Row():
111
+ with gr.Column():
112
+ img_input = gr.Image(type="pil", label="Upload Receipt Image")
113
+ btn = gr.Button("Analyze")
114
+
115
+ with gr.Column():
116
+ json_output = gr.JSON(label="Extracted Structured JSON")
117
+ overlay_img = gr.Image(label="Detected Overlay")
118
+
119
+ btn.click(fn=process_receipt, inputs=img_input, outputs=[json_output, overlay_img])
120
+
121
+ if __name__ == "__main__":
122
+ demo.launch()