Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import DonutProcessor, VisionEncoderDecoderModel
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
import easyocr
|
| 5 |
+
import numpy as np
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
# โ
Version
|
| 10 |
+
VERSION = "v2.5 - Proper JSON + Working Overlay Highlight (CORD + EasyOCR)"
|
| 11 |
+
|
| 12 |
+
# Load Donut (CORD-trained)
|
| 13 |
+
donut_model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
|
| 14 |
+
donut_processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
|
| 15 |
+
|
| 16 |
+
# Load EasyOCR
|
| 17 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 18 |
+
|
| 19 |
+
# Function to extract JSON output from Donut
|
| 20 |
+
def extract_json_donut(image: Image.Image) -> dict:
|
| 21 |
+
task_prompt = "<s_cord-v2>"
|
| 22 |
+
pixel_values = donut_processor(image, return_tensors="pt").pixel_values
|
| 23 |
+
decoder_input = donut_processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids
|
| 24 |
+
outputs = donut_model.generate(pixel_values, decoder_input_ids=decoder_input, max_length=768)
|
| 25 |
+
raw_result = donut_processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 26 |
+
|
| 27 |
+
# Try parsing into JSON
|
| 28 |
+
try:
|
| 29 |
+
json_start = raw_result.find('{')
|
| 30 |
+
json_result = json.loads(raw_result[json_start:])
|
| 31 |
+
return json_result
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return {"error": "Could not parse output into JSON", "raw_result": raw_result}
|
| 34 |
+
|
| 35 |
+
# Function to draw highlights on image
|
| 36 |
+
def highlight_matched_fields(image: Image.Image, field_values: list):
|
| 37 |
+
np_img = np.array(image.convert("RGB"))
|
| 38 |
+
results = reader.readtext(np_img, detail=1)
|
| 39 |
+
draw = ImageDraw.Draw(image)
|
| 40 |
+
matched = False
|
| 41 |
+
|
| 42 |
+
for (bbox, text, prob) in results:
|
| 43 |
+
text_clean = text.strip().lower()
|
| 44 |
+
for fv in field_values:
|
| 45 |
+
if re.sub(r"[^a-z0-9]", "", fv.lower()) in re.sub(r"[^a-z0-9]", "", text_clean):
|
| 46 |
+
points = [(int(p[0]), int(p[1])) for p in bbox]
|
| 47 |
+
draw.line(points + [points[0]], fill="green", width=2)
|
| 48 |
+
draw.text((points[0][0], points[0][1] - 12), fv, fill="green")
|
| 49 |
+
matched = True
|
| 50 |
+
return image if matched else image # If nothing matched, still return the image
|
| 51 |
+
|
| 52 |
+
# Main handler
|
| 53 |
+
def analyze_receipt(image):
|
| 54 |
+
try:
|
| 55 |
+
json_result = extract_json_donut(image)
|
| 56 |
+
|
| 57 |
+
# If JSON loaded successfully, try to extract values to highlight
|
| 58 |
+
field_values = []
|
| 59 |
+
if isinstance(json_result, dict):
|
| 60 |
+
def flatten(data):
|
| 61 |
+
for k, v in data.items():
|
| 62 |
+
if isinstance(v, str):
|
| 63 |
+
field_values.append(v)
|
| 64 |
+
elif isinstance(v, list):
|
| 65 |
+
for item in v:
|
| 66 |
+
if isinstance(item, dict):
|
| 67 |
+
flatten(item)
|
| 68 |
+
elif isinstance(v, dict):
|
| 69 |
+
flatten(v)
|
| 70 |
+
flatten(json_result)
|
| 71 |
+
|
| 72 |
+
annotated = highlight_matched_fields(image.copy(), field_values)
|
| 73 |
+
return json_result, annotated
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
return {"error": str(e), "version": VERSION}, image
|
| 77 |
+
|
| 78 |
+
# Gradio UI
|
| 79 |
+
with gr.Blocks(title=f"Donut OCR ({VERSION})") as demo:
|
| 80 |
+
gr.Markdown(f"# ๐งพ Donut Receipt OCR (CORD v2) + Bounding Box Overlay\n**Version:** `{VERSION}`")
|
| 81 |
+
gr.Markdown("Upload a printed or handwritten receipt. Fields are extracted as JSON and visually highlighted.")
|
| 82 |
+
|
| 83 |
+
with gr.Row():
|
| 84 |
+
with gr.Column():
|
| 85 |
+
image_input = gr.Image(type="pil", label="๐ค Upload Receipt Image")
|
| 86 |
+
analyze_btn = gr.Button("๐ Upload & Analyze")
|
| 87 |
+
|
| 88 |
+
with gr.Column():
|
| 89 |
+
output_json = gr.JSON(label="๐ง Parsed JSON Output")
|
| 90 |
+
output_image = gr.Image(label="๐ธ Highlighted Receipt Image")
|
| 91 |
+
|
| 92 |
+
analyze_btn.click(analyze_receipt, inputs=image_input, outputs=[output_json, output_image])
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
demo.launch()
|