KeyarSrini commited on
Commit
8a13a92
·
verified ·
1 Parent(s): 8fde3e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ import easyocr
4
+ import re
5
+ import json
6
+ from PIL import Image
7
+
8
+ reader = easyocr.Reader(['en'], gpu=False)
9
+
10
+ def extract_fields(image):
11
+ result = reader.readtext(image)
12
+
13
+ raw_lines = [text for _, text, _ in result]
14
+ all_text = " ".join(raw_lines)
15
+
16
+ json_data = {
17
+ "version": "v3.4 - Dynamic OCR Receipt Parser (with Resize Fix)",
18
+ "RECEIPT/INVOICE_SUMMARY": {},
19
+ "LINE_ITEMS": []
20
+ }
21
+
22
+ # Extracting key fields
23
+ vendor_match = re.search(r"(?i)([A-Z][A-Z\s']+)(PTE LTD|BOOK STORE|TRADERS|ENTERPRISE)?", all_text)
24
+ if vendor_match:
25
+ json_data["RECEIPT/INVOICE_SUMMARY"]["VENDOR"] = vendor_match.group(0).strip()
26
+
27
+ date_match = re.search(r"(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", all_text)
28
+ if date_match:
29
+ json_data["RECEIPT/INVOICE_SUMMARY"]["DATE"] = date_match.group(1)
30
+
31
+ phone_match = re.search(r"(\+?\d{2,4}[\s-]?\d{3,4}[\s-]?\d{3,4})", all_text)
32
+ if phone_match:
33
+ json_data["RECEIPT/INVOICE_SUMMARY"]["PHONE"] = phone_match.group(0)
34
+
35
+ total_match = re.search(r"(?i)(TOTAL|Grand Total|Net Total)[^\d]*(\$?\d+[\.\,]?\d{0,2})", all_text)
36
+ if total_match:
37
+ json_data["RECEIPT/INVOICE_SUMMARY"]["TOTAL"] = total_match.group(2)
38
+
39
+ # Attempt to parse item lines
40
+ for line in raw_lines:
41
+ if re.search(r"\d+\s*[xX]\s*\$?\d", line) or re.search(r"\d+\s+\$\s*\d", line):
42
+ json_data["LINE_ITEMS"].append({"Item": line})
43
+ elif re.search(r"\$\s*\d+[\.\,]?\d{0,2}$", line):
44
+ json_data["LINE_ITEMS"].append({"Item": line})
45
+
46
+ return json.dumps(json_data, indent=2), image
47
+
48
+ demo = gr.Interface(
49
+ fn=extract_fields,
50
+ inputs=gr.Image(type="pil"),
51
+ outputs=[gr.JSON(label="Extracted JSON Data"), gr.Image(label="Uploaded Image")],
52
+ title="Dynamic OCR Receipt Parser",
53
+ description="Upload any receipt (printed or handwritten) and get structured JSON data."
54
+ )
55
+
56
+ demo.launch(share=True)