Spaces:
Sleeping
Sleeping
File size: 2,113 Bytes
1eaf351 |
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import PIL.Image
import gradio as gr
import base64
import time
import os
import google.generativeai as genai
from dotenv import load_dotenv
load_dotenv()
# Set Google API key
genai.configure(api_key=os.getenv("'GOOGLE_API_KEY'"))
# os.environ['GOOGLE_API_KEY'] = ""
# genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
# Create the Model
txt_model = genai.GenerativeModel('gemini-pro')
vis_model = genai.GenerativeModel('gemini-pro-vision')
# Image to Base 64 Converter
def image_to_base64(image_path):
with open(image_path, 'rb') as img:
encoded_string = base64.b64encode(img.read())
return encoded_string.decode('utf-8')
# Function that takes User Inputs and displays it on ChatUI
def query_message(history, txt, img):
if not img:
history.append((txt, None))
return history
base64_data = image_to_base64(img)
data_url = f"data:image/jpeg;base64,{base64_data}"
history.append((f"{txt} ![]({data_url})", None))
return history
# Function that takes User Inputs, generates Response and displays on Chat UI
def llm_response(history, text, img):
if not img:
response = txt_model.generate_content(text)
history.append((None, response.text))
return history
else:
img = PIL.Image.open(img)
response = vis_model.generate_content([text, img])
history.append((None, response.text))
return history
# Interface Code
with gr.Blocks() as app:
with gr.Row():
image_box = gr.Image(type="filepath")
chatbot = gr.Chatbot(
scale=2,
height=600
)
text_box = gr.Textbox(
placeholder="Enter text and press enter, or upload an image",
container=False,
)
btn = gr.Button("Submit")
clicked = btn.click(query_message,
[chatbot, text_box, image_box],
chatbot
).then(llm_response,
[chatbot, text_box, image_box],
chatbot
)
app.queue()
app.launch(debug=True)
|