Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +40 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import pytesseract
|
| 5 |
+
|
| 6 |
+
# Load model and processor
|
| 7 |
+
model = LayoutLMv3ForTokenClassification.from_pretrained("./model")
|
| 8 |
+
processor = LayoutLMv3Processor.from_pretrained("./model")
|
| 9 |
+
|
| 10 |
+
# Define label mapping
|
| 11 |
+
id2label = {0: "company", 1: "date", 2: "address", 3: "total", 4: "other"}
|
| 12 |
+
|
| 13 |
+
def predict_receipt(image):
|
| 14 |
+
ocr_data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
|
| 15 |
+
texts = ocr_data["text"]
|
| 16 |
+
boxes = [
|
| 17 |
+
[
|
| 18 |
+
ocr_data["left"][i],
|
| 19 |
+
ocr_data["top"][i],
|
| 20 |
+
ocr_data["left"][i] + ocr_data["width"][i],
|
| 21 |
+
ocr_data["top"][i] + ocr_data["height"][i],
|
| 22 |
+
]
|
| 23 |
+
for i in range(len(ocr_data["text"]))
|
| 24 |
+
]
|
| 25 |
+
encoding = processor(image, text=texts, boxes=boxes, return_tensors="pt", truncation=True, padding="max_length")
|
| 26 |
+
outputs = model(**{k: v for k, v in encoding.items()})
|
| 27 |
+
predictions = outputs.logits.argmax(-1).squeeze().tolist()
|
| 28 |
+
labeled_output = {id2label[pred]: texts[i] for i, pred in enumerate(predictions) if pred != 4}
|
| 29 |
+
return labeled_output
|
| 30 |
+
|
| 31 |
+
interface = gr.Interface(
|
| 32 |
+
fn=predict_receipt,
|
| 33 |
+
inputs=gr.Image(type="pil"),
|
| 34 |
+
outputs="json",
|
| 35 |
+
title="Receipt Analyzer",
|
| 36 |
+
description="Upload a receipt image to extract key information."
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
interface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==3.36
|
| 2 |
+
torch>=1.10.0
|
| 3 |
+
transformers
|
| 4 |
+
pytesseract
|
| 5 |
+
Pillow
|