KeyarSrini commited on
Commit
360bacb
Β·
verified Β·
1 Parent(s): a659985

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ # βœ… Version Tag
8
+ VERSION = "v2.4 - Donut CORD + EasyOCR Overlay (ZeroGPU Friendly)"
9
+
10
+ # 🧠 Load Donut model fine-tuned on CORD dataset (for receipts)
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 for bounding box overlays
15
+ reader = easyocr.Reader(['en'], gpu=False)
16
+
17
+ # πŸ“œ Donut-based field extractor
18
+ def extract_json_donut(image: Image.Image) -> str:
19
+ task_prompt = "<s_cord-v2>"
20
+ pixel_values = donut_processor(image, return_tensors="pt").pixel_values
21
+ decoder_input = donut_processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids
22
+ outputs = donut_model.generate(pixel_values, decoder_input_ids=decoder_input, max_length=768)
23
+ result = donut_processor.batch_decode(outputs, skip_special_tokens=True)[0]
24
+ return result
25
+
26
+ # πŸ– Highlight keywords from Donut using EasyOCR's bounding boxes
27
+ def highlight_matched_fields(image: Image.Image, field_values: list):
28
+ np_img = np.array(image.convert("RGB"))
29
+ results = reader.readtext(np_img, detail=1)
30
+ draw = ImageDraw.Draw(image)
31
+
32
+ for (bbox, text, prob) in results:
33
+ text_clean = text.strip().lower()
34
+ for fv in field_values:
35
+ if fv.lower() in text_clean:
36
+ points = [(int(p[0]), int(p[1])) for p in bbox]
37
+ draw.line(points + [points[0]], fill="green", width=2)
38
+ draw.text((points[0][0], points[0][1] - 12), fv, fill="green")
39
+ return image
40
+
41
+ # 🧾 Full pipeline
42
+ def analyze_receipt(image):
43
+ try:
44
+ json_result = extract_json_donut(image)
45
+ keywords = ["total", "tax", "price", "item", "amount", "date"]
46
+ field_values = [
47
+ word.strip(",:.") for word in json_result.split()
48
+ if any(k in word.lower() for k in keywords)
49
+ ]
50
+ annotated = highlight_matched_fields(image.copy(), field_values)
51
+ result = f"VERSION: {VERSION}\n\n{json_result}"
52
+ return result, annotated
53
+ except Exception as e:
54
+ return f"Error: {str(e)}\nVERSION: {VERSION}", image
55
+
56
+ # 🎨 Gradio UI
57
+ with gr.Blocks(title=f"Donut OCR ({VERSION})") as demo:
58
+ gr.Markdown(f"# 🧾 Donut Receipt OCR (CORD v2) + Bounding Box Overlay\n**Version:** `{VERSION}`")
59
+ gr.Markdown("Upload a printed or handwritten receipt. Key fields are extracted and overlaid with bounding boxes.")
60
+
61
+ with gr.Row():
62
+ with gr.Column():
63
+ image_input = gr.Image(type="pil", label="πŸ“€ Upload Receipt Image")
64
+ analyze_btn = gr.Button("πŸ“„ Upload & Analyze")
65
+
66
+ with gr.Column():
67
+ output_json = gr.Textbox(label="🧠 Extracted JSON with Version", lines=15)
68
+ output_image = gr.Image(label="πŸ“Έ Highlighted Receipt Image")
69
+
70
+ analyze_btn.click(analyze_receipt, inputs=image_input, outputs=[output_json, output_image])
71
+
72
+ if __name__ == "__main__":
73
+ demo.launch()