|
|
import os |
|
|
import google.generativeai as genai |
|
|
import gradio as gr |
|
|
from PIL import Image |
|
|
|
|
|
|
|
|
API_KEY = os.getenv("AIzaSyDeQ5VIcPbgzSG6QfFvn4tjP4G-V-frpwM") |
|
|
if not API_KEY: |
|
|
raise ValueError("API Key is missing! Set GEMINI_API_KEY as an environment variable.") |
|
|
|
|
|
|
|
|
try: |
|
|
genai.configure(api_key=API_KEY) |
|
|
model = genai.GenerativeModel("gemini-1.5-flash") |
|
|
chat = model.start_chat(history=[]) |
|
|
except Exception as e: |
|
|
print(f"Error initializing Gemini model: {e}") |
|
|
exit() |
|
|
|
|
|
|
|
|
def chatbot_interface(text_input, image_input=None, audio_input=None): |
|
|
try: |
|
|
if not text_input: |
|
|
return "Please enter a message." |
|
|
|
|
|
content = [{"text": text_input}] |
|
|
|
|
|
|
|
|
if image_input: |
|
|
try: |
|
|
image_input.save("temp_image.png") |
|
|
with open("temp_image.png", "rb") as img_file: |
|
|
image_data = img_file.read() |
|
|
content.append({"image": image_data}) |
|
|
except Exception as e: |
|
|
return f"Error processing image: {e}" |
|
|
|
|
|
|
|
|
if audio_input and os.path.exists(audio_input): |
|
|
try: |
|
|
with open(audio_input, "rb") as audio_file: |
|
|
audio_data = audio_file.read() |
|
|
content.append({"audio": audio_data}) |
|
|
except Exception as e: |
|
|
return f"Error processing audio: {e}" |
|
|
elif audio_input: |
|
|
return "Audio file not found." |
|
|
|
|
|
|
|
|
response = chat.send_message(content) |
|
|
return response.text if response else "No response from the model." |
|
|
|
|
|
except Exception as e: |
|
|
return f"An error occurred: {e}" |
|
|
|
|
|
|
|
|
interface = gr.Interface( |
|
|
fn=chatbot_interface, |
|
|
inputs=[ |
|
|
gr.Textbox(label="Your Message", placeholder="Type your question here..."), |
|
|
gr.Image(label="Upload an Image", type="pil"), |
|
|
gr.Audio(label="Upload or Record Audio", type="filepath") |
|
|
], |
|
|
outputs=gr.Textbox(label="Bot Response"), |
|
|
title="FINANCE Chatbot", |
|
|
description="Chat using text, images, and audio! Ensure your API key is valid.", |
|
|
allow_flagging="never" |
|
|
) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
try: |
|
|
interface.launch(debug=True, share=True) |
|
|
except Exception as e: |
|
|
print(f"Error launching interface: {e}") |
|
|
|