Alibrown commited on
Commit
7397922
Β·
verified Β·
1 Parent(s): 66ca1a0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import google.generativeai as genai
3
+ from PIL import Image
4
+ import io
5
+ import base64
6
+ import requests
7
+ import json # Added to handle JSON decoding errors
8
+
9
+ st.set_page_config(page_title="Gemini AI Chat", layout="wide")
10
+
11
+ st.title("πŸ€– Gemini AI Chat Interface")
12
+ st.markdown("""
13
+ **Welcome to the Gemini AI Chat Interface!**
14
+ Chat seamlessly with Google's advanced Gemini AI models, supporting both text and image inputs.
15
+ πŸ”— [GitHub Profile](https://github.com/volkansah) |
16
+ πŸ“‚ [Project Repository](https://github.com/volkansah/gemini-ai-chat) |
17
+ πŸ’¬ [Soon](https://aicodecraft.io)
18
+ Follow me for more innovative projects and updates!
19
+ """)
20
+
21
+
22
+ def encode_image(image):
23
+ """Convert PIL Image to base64 string"""
24
+ buffered = io.BytesIO()
25
+ image.save(buffered, format="JPEG")
26
+ image_bytes = buffered.getvalue()
27
+ encoded_image = base64.b64encode(image_bytes).decode('utf-8')
28
+ return encoded_image
29
+
30
+ # Sidebar for settings with dynamic model fetching (PLACEHOLDER API)
31
+ with st.sidebar:
32
+ api_key = st.text_input("Enter Google AI API Key", type="password")
33
+
34
+ try:
35
+ url = "https://api.example.com/gemini/models" # REPLACE THIS with the actual Google API endpoint
36
+ headers = {"Authorization": f"Bearer {api_key}"}
37
+ response = requests.get(url, headers=headers)
38
+ response.raise_for_status()
39
+ models_data = response.json()
40
+ models = [model["name"] for model in models_data["models"]] # REPLACE with the actual JSON structure
41
+
42
+ except requests.exceptions.RequestException as e:
43
+ st.error(f"Error fetching model list: {e}")
44
+ models = ["gemini-1.5-flash"]
45
+
46
+ except (KeyError, json.JSONDecodeError) as e:
47
+ st.error(f"Error parsing model list: {e}")
48
+ models = ["gemini-1.5-flash"]
49
+
50
+ model = st.selectbox("Select Model", models)
51
+ temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
52
+ max_tokens = st.slider("Max Tokens", 1, 2048, 1000)
53
+ system_prompt = st.text_area("System Prompt (Optional)")
54
+
55
+ # Initialize session state for chat history
56
+ if "messages" not in st.session_state:
57
+ st.session_state.messages = []
58
+
59
+ # Display chat history
60
+ for message in st.session_state.messages:
61
+ with st.chat_message(message["role"]):
62
+ st.markdown(message["content"])
63
+
64
+ # File uploader for images
65
+ uploaded_file = st.file_uploader("Upload an image (optional)", type=["jpg", "jpeg", "png"])
66
+ uploaded_image = None
67
+ if uploaded_file is not None:
68
+ uploaded_image = Image.open(uploaded_file).convert('RGB')
69
+ st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
70
+
71
+ # Chat input
72
+ user_input = st.chat_input("Type your message here...")
73
+
74
+ if user_input and api_key:
75
+ try:
76
+ # Configure the API
77
+ genai.configure(api_key=api_key)
78
+
79
+ # Add user message to chat history
80
+ st.session_state.messages.append({"role": "user", "content": user_input})
81
+ with st.chat_message("user"):
82
+ st.markdown(user_input)
83
+
84
+ # Prepare the model and content
85
+ model_instance = genai.GenerativeModel(model_name=model)
86
+
87
+ content = []
88
+ if uploaded_image:
89
+ # Convert image to base64
90
+ encoded_image = encode_image(uploaded_image)
91
+ content = [
92
+ {"text": user_input},
93
+ {
94
+ "inline_data": {
95
+ "mime_type": "image/jpeg",
96
+ "data": encoded_image
97
+ }
98
+ }
99
+ ]
100
+ else:
101
+ content = [{"text": user_input}]
102
+
103
+ # Generate response
104
+ response = model_instance.generate_content(
105
+ content,
106
+ generation_config=genai.types.GenerationConfig(
107
+ temperature=temperature,
108
+ max_output_tokens=max_tokens
109
+ )
110
+ )
111
+
112
+ # Display assistant response
113
+ with st.chat_message("assistant"):
114
+ st.markdown(response.text)
115
+
116
+ # Add assistant response to chat history
117
+ st.session_state.messages.append({"role": "assistant", "content": response.text})
118
+
119
+ except Exception as e:
120
+ st.error(f"Error: {str(e)}")
121
+ st.error("If using an image, make sure to select a vision-enabled model (ones with 'vision' in the name)")
122
+
123
+ elif not api_key and user_input:
124
+ st.warning("Please enter your API key in the sidebar first.")
125
+
126
+ # Instructions in the sidebar
127
+ with st.sidebar:
128
+ st.markdown("""
129
+ ## πŸ“ Instructions:
130
+ 1. Enter your Google AI API key
131
+ 2. Select a model (use vision models for image analysis)
132
+ 3. Adjust temperature and max tokens if needed
133
+ 4. Optional: Set a system prompt
134
+ 5. Upload an image (optional)
135
+ 6. Type your message and press Enter
136
+ ### About
137
+ πŸ”— [GitHub Profile](https://github.com/volkansah) |
138
+ πŸ“‚ [Project Repository](https://github.com/volkansah/gemini-ai-chat) |
139
+ πŸ’¬ [Soon](https://aicodecraft.io)
140
+ """)