Spaces:
Runtime error
Runtime error
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import cv2
|
| 4 |
-
import easyocr
|
| 5 |
-
import numpy as np
|
| 6 |
-
import json
|
| 7 |
-
from PIL import Image
|
| 8 |
-
import tempfile
|
| 9 |
-
|
| 10 |
-
reader = easyocr.Reader(['en'], gpu=False)
|
| 11 |
-
|
| 12 |
-
def preprocess_image(image_path):
|
| 13 |
-
img = cv2.imread(image_path)
|
| 14 |
-
img = cv2.resize(img, (800, int(img.shape[0] * 800 / img.shape[1])))
|
| 15 |
-
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 16 |
-
gray = cv2.bilateralFilter(gray, 11, 17, 17)
|
| 17 |
-
return gray
|
| 18 |
-
|
| 19 |
-
def extract_json(image):
|
| 20 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 21 |
-
image.save(tmp.name)
|
| 22 |
-
img_path = tmp.name
|
| 23 |
-
|
| 24 |
-
try:
|
| 25 |
-
preprocessed = preprocess_image(img_path)
|
| 26 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as proc_tmp:
|
| 27 |
-
cv2.imwrite(proc_tmp.name, preprocessed)
|
| 28 |
-
result = reader.readtext(proc_tmp.name, detail=0, paragraph=True)
|
| 29 |
-
except Exception as e:
|
| 30 |
-
return {"error": f"OCR failed: {str(e)}"}
|
| 31 |
-
|
| 32 |
-
lines = [line.strip() for line in result if line.strip()]
|
| 33 |
-
keywords = ["total", "amount", "tax", "date", "invoice", "phone", "address", "name"]
|
| 34 |
-
summary = {}
|
| 35 |
-
items = []
|
| 36 |
-
|
| 37 |
-
for line in lines:
|
| 38 |
-
low = line.lower()
|
| 39 |
-
if any(k in low for k in keywords):
|
| 40 |
-
for k in keywords:
|
| 41 |
-
if k in low:
|
| 42 |
-
summary[k.upper()] = line
|
| 43 |
-
elif any(char.isdigit() for char in line) and any(char.isalpha() for char in line):
|
| 44 |
-
items.append({"Item": line})
|
| 45 |
-
|
| 46 |
-
return {
|
| 47 |
-
"version": "v3.5 - Dynamic OCR Receipt Parser (Improved Preprocessing)",
|
| 48 |
-
"RECEIPT/INVOICE_SUMMARY": summary,
|
| 49 |
-
"LINE_ITEMS": items,
|
| 50 |
-
"raw_lines": lines
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
demo = gr.Interface(
|
| 54 |
-
fn=extract_json,
|
| 55 |
-
inputs=gr.Image(type="pil"),
|
| 56 |
-
outputs=gr.JSON(label="Parsed Receipt JSON"),
|
| 57 |
-
title="Dynamic OCR Receipt Parser",
|
| 58 |
-
description="Upload any receipt (printed or handwritten) and get structured JSON data."
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
if __name__ == "__main__":
|
| 62 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|