Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image
|
3 |
+
import google.generativeai as genai
|
4 |
+
import os
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
|
7 |
+
# Load environment variables
|
8 |
+
load_dotenv()
|
9 |
+
|
10 |
+
# Configure the API key for Google Gemini
|
11 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
12 |
+
|
13 |
+
# Function to process the image and get response from Gemini model
|
14 |
+
def get_gemini_response(input_prompt, uploaded_file, query):
|
15 |
+
try:
|
16 |
+
# Load the image file as bytes
|
17 |
+
if uploaded_file is None:
|
18 |
+
return "Please upload an image."
|
19 |
+
bytes_data = uploaded_file.read()
|
20 |
+
image_parts = [{"mime_type": uploaded_file.type, "data": bytes_data}]
|
21 |
+
|
22 |
+
# Load the Gemini model and get the response
|
23 |
+
model = genai.GenerativeModel("gemini-pro-vision")
|
24 |
+
response = model.generate_content([input_prompt, image_parts[0], query])
|
25 |
+
return response.text
|
26 |
+
except Exception as e:
|
27 |
+
return f"Error: {e}"
|
28 |
+
|
29 |
+
# Define input prompt
|
30 |
+
default_prompt = """
|
31 |
+
You are an expert in understanding invoices. You will receive input images as invoices and
|
32 |
+
you will have to answer questions based on the input image.
|
33 |
+
"""
|
34 |
+
|
35 |
+
# Define Gradio interface
|
36 |
+
with gr.Blocks() as invoice_extractor:
|
37 |
+
gr.Markdown("# Invoice Extractor")
|
38 |
+
gr.Markdown(
|
39 |
+
"""
|
40 |
+
Upload an invoice image and ask specific questions about it.
|
41 |
+
The system uses Google's Gemini model to extract and interpret the invoice details.
|
42 |
+
"""
|
43 |
+
)
|
44 |
+
|
45 |
+
input_prompt = gr.Textbox(label="Input Prompt", value=default_prompt, lines=3)
|
46 |
+
image_input = gr.Image(label="Upload Invoice Image", type="file")
|
47 |
+
query_input = gr.Textbox(label="Enter your query about the invoice", placeholder="e.g., What is the total amount?")
|
48 |
+
output_response = gr.Textbox(label="Response", lines=5)
|
49 |
+
|
50 |
+
# Button to process the image and query
|
51 |
+
submit_btn = gr.Button("Process Invoice")
|
52 |
+
|
53 |
+
# Set the button to call the processing function
|
54 |
+
submit_btn.click(
|
55 |
+
get_gemini_response,
|
56 |
+
inputs=[input_prompt, image_input, query_input],
|
57 |
+
outputs=output_response
|
58 |
+
)
|
59 |
+
|
60 |
+
# Launch the app
|
61 |
+
invoice_extractor.launch()
|