Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 re
|
| 7 |
+
|
| 8 |
+
VERSION = "v2.9 - Donut + EasyOCR Highlighted Fields"
|
| 9 |
+
|
| 10 |
+
# Load Donut CORD model
|
| 11 |
+
donut_model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
|
| 12 |
+
donut_processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
|
| 13 |
+
|
| 14 |
+
# Load EasyOCR
|
| 15 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 16 |
+
|
| 17 |
+
# XML-like tag parser for Donut CORD output
|
| 18 |
+
def parse_cord_tags(raw_text):
|
| 19 |
+
fields = re.findall(r"<s_([^>]+)>(.*?)</s_\1>", raw_text)
|
| 20 |
+
parsed = {}
|
| 21 |
+
for key, value in fields:
|
| 22 |
+
if key in parsed:
|
| 23 |
+
if isinstance(parsed[key], list):
|
| 24 |
+
parsed[key].append(value)
|
| 25 |
+
else:
|
| 26 |
+
parsed[key] = [parsed[key], value]
|
| 27 |
+
else:
|
| 28 |
+
parsed[key] = value
|
| 29 |
+
return parsed
|
| 30 |
+
|
| 31 |
+
# Use Donut to extract structured receipt fields
|
| 32 |
+
def extract_donut_fields(image: Image.Image):
|
| 33 |
+
task_prompt = "<s_cord-v2>"
|
| 34 |
+
pixel_values = donut_processor(image, return_tensors="pt").pixel_values
|
| 35 |
+
decoder_input = donut_processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids
|
| 36 |
+
outputs = donut_model.generate(pixel_values, decoder_input_ids=decoder_input, max_length=768)
|
| 37 |
+
raw_result = donut_processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 38 |
+
print("🧠 Donut Raw Output:", raw_result)
|
| 39 |
+
parsed = parse_cord_tags(raw_result)
|
| 40 |
+
return parsed, raw_result
|
| 41 |
+
|
| 42 |
+
# Highlight only fields matched from Donut using EasyOCR bounding boxes
|
| 43 |
+
def highlight_fields(image: Image.Image, values_to_match: list):
|
| 44 |
+
np_img = np.array(image.convert("RGB"))
|
| 45 |
+
results = reader.readtext(np_img, detail=1)
|
| 46 |
+
draw = ImageDraw.Draw(image)
|
| 47 |
+
matched_lines = []
|
| 48 |
+
|
| 49 |
+
for (bbox, text, prob) in results:
|
| 50 |
+
cleaned_text = re.sub(r"\W+", "", text.lower())
|
| 51 |
+
for fv in values_to_match:
|
| 52 |
+
cleaned_fv = re.sub(r"\W+", "", str(fv).lower())
|
| 53 |
+
if cleaned_fv in cleaned_text or cleaned_text in cleaned_fv:
|
| 54 |
+
points = [(int(p[0]), int(p[1])) for p in bbox]
|
| 55 |
+
draw.line(points + [points[0]], fill="green", width=2)
|
| 56 |
+
draw.text((points[0][0], points[0][1] - 10), text.strip(), fill="green")
|
| 57 |
+
matched_lines.append(text.strip())
|
| 58 |
+
break
|
| 59 |
+
return image, matched_lines
|
| 60 |
+
|
| 61 |
+
# Combine logic
|
| 62 |
+
def process_receipt(image: Image.Image):
|
| 63 |
+
# Run Donut
|
| 64 |
+
donut_data, raw_output = extract_donut_fields(image)
|
| 65 |
+
|
| 66 |
+
# Collect all values to match
|
| 67 |
+
values = []
|
| 68 |
+
def collect_vals(d):
|
| 69 |
+
for v in d.values():
|
| 70 |
+
if isinstance(v, str):
|
| 71 |
+
values.append(v)
|
| 72 |
+
elif isinstance(v, list):
|
| 73 |
+
values.extend([str(item) for item in v])
|
| 74 |
+
collect_vals(donut_data)
|
| 75 |
+
|
| 76 |
+
# Highlight using OCR matches
|
| 77 |
+
highlighted_image, matched_text = highlight_fields(image.copy(), values)
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
"version": VERSION,
|
| 81 |
+
"donut_fields": donut_data,
|
| 82 |
+
"matched_text_in_image": matched_text,
|
| 83 |
+
"raw_donut_output": raw_output
|
| 84 |
+
}, highlighted_image
|
| 85 |
+
|
| 86 |
+
# Gradio UI
|
| 87 |
+
with gr.Blocks(title=f"Receipt Parser - {VERSION}") as demo:
|
| 88 |
+
gr.Markdown(f"# 🧾 Donut Receipt Parser with Smart Highlight\n**Version:** `{VERSION}`")
|
| 89 |
+
gr.Markdown("Donut extracts structured fields. EasyOCR finds matching text to highlight.")
|
| 90 |
+
|
| 91 |
+
with gr.Row():
|
| 92 |
+
with gr.Column():
|
| 93 |
+
image_input = gr.Image(type="pil", label="📤 Upload Receipt")
|
| 94 |
+
process_btn = gr.Button("📄 Analyze Receipt")
|
| 95 |
+
|
| 96 |
+
with gr.Column():
|
| 97 |
+
json_output = gr.JSON(label="🧠 Extracted Donut Fields & Matches")
|
| 98 |
+
overlay_image = gr.Image(label="📸 Highlighted Fields Only")
|
| 99 |
+
|
| 100 |
+
process_btn.click(fn=process_receipt, inputs=image_input, outputs=[json_output, overlay_image])
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
demo.launch()
|