File size: 1,460 Bytes
227dccc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import gradio as gr
from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
from PIL import Image
import pytesseract

# Load model and processor
model = LayoutLMv3ForTokenClassification.from_pretrained("./model")
processor = LayoutLMv3Processor.from_pretrained("./model")

# Define label mapping
id2label = {0: "company", 1: "date", 2: "address", 3: "total", 4: "other"}

def predict_receipt(image):
    ocr_data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
    texts = ocr_data["text"]
    boxes = [
        [
            ocr_data["left"][i],
            ocr_data["top"][i],
            ocr_data["left"][i] + ocr_data["width"][i],
            ocr_data["top"][i] + ocr_data["height"][i],
        ]
        for i in range(len(ocr_data["text"]))
    ]
    encoding = processor(image, text=texts, boxes=boxes, return_tensors="pt", truncation=True, padding="max_length")
    outputs = model(**{k: v for k, v in encoding.items()})
    predictions = outputs.logits.argmax(-1).squeeze().tolist()
    labeled_output = {id2label[pred]: texts[i] for i, pred in enumerate(predictions) if pred != 4}
    return labeled_output

interface = gr.Interface(
    fn=predict_receipt,
    inputs=gr.Image(type="pil"),
    outputs="json",
    title="Receipt Analyzer",
    description="Upload a receipt image to extract key information."
)

if __name__ == "__main__":
    interface.launch()