File size: 1,075 Bytes
70c99a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from PIL import Image
import pytesseract
import openai
import gradio as gr
import os

# Load the API key from .env or environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")

def extract_receipt_data(image):
    try:
        raw_text = pytesseract.image_to_string(image)

        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You extract structured data from receipts in JSON format with keys like 'Bank Name', 'Date', 'Items', 'Total', etc."},
                {"role": "user", "content": f"Convert the following receipt text to JSON:\n\n{raw_text}"}
            ]
        )

        return response['choices'][0]['message']['content']

    except Exception as e:
        return f"❌ Error: {str(e)}"

ui = gr.Interface(
    fn=extract_receipt_data,
    inputs=gr.Image(type="pil"),
    outputs="text",
    title="Receipt OCR & Data Extractor",
    description="Upload a receipt image and get structured JSON data extracted."
)

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