generated from streamlit/blank-app-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
264 lines (218 loc) · 12 KB
/
streamlit_app.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# import streamlit as st
# import google.generativeai as genai
# st.title("🐻❄️ FoodRec Chatbot App")
# # st.html("<b>🐻❄️ Lab3 Chatbot App</b>")
# st.subheader("Conversation")
# # Capture Gemini API Key
# gemini_api_key = st.text_input("Gemini API Key: ", placeholder="Type the API", type="password")
# # Initialize the Gemini Model
# if gemini_api_key:
# try:
# # Configure Gemini with the provided API Key
# genai.configure(api_key=gemini_api_key)
# model = genai.GenerativeModel("gemini-pro")
# st.success("Gemini API Key successfully configured.")
# except Exception as e:
# st.error(f"An error occurred while setting up the Gemini model: {e}")
# # Initialize session state for storing chat history
# if "chat_history" not in st.session_state:
# st.session_state.chat_history = [] # Initialize with an empty list
# # Display previous chat history using st.chat_message (if available)
# for role, message in st.session_state.chat_history:
# st.chat_message(role).markdown(message)
# # Capture user input and generate bot response
# if user_input := st.chat_input("Say something..."):
# # Store and display user message
# st.session_state.chat_history.append(("user", user_input))
# st.chat_message("user").markdown(user_input)
# # Use Gemini AI to generate a bot response
# if model:
# try:
# response = model.generate_content(user_input)
# bot_response = response.text
# # Store and display the bot response
# st.session_state.chat_history.append(("assistant", bot_response))
# st.chat_message("assistant").markdown(bot_response)
# except Exception as e:
# st.error(f"An error occurred while generating the response: {e}")
# # Use Gemini AI to generate a bot response
# import streamlit as st
# import google.generativeai as genai
# st.title("🐻❄️ FoodRec Chatbot App")
# st.subheader("Conversation")
# # Capture Gemini API Key
# gemini_api_key = st.text_input("Gemini API Key: ", placeholder="Type the API", type="password")
# # Initialize the Gemini Model
# if gemini_api_key:
# try:
# # Configure Gemini with the provided API Key
# genai.configure(api_key=gemini_api_key)
# model = genai.GenerativeModel("gemini-pro")
# st.success("Gemini API Key successfully configured.")
# except Exception as e:
# st.error(f"An error occurred while setting up the Gemini model: {e}")
# # Initialize session state for storing chat history and conversation context
# if "chat_history" not in st.session_state:
# st.session_state.chat_history = [] # Initialize with an empty list
# if "awaiting_hungry_response" not in st.session_state:
# st.session_state.awaiting_hungry_response = False # Flag to track if bot asked about hunger
# # Display previous chat history using st.chat_message (if available)
# for role, message in st.session_state.chat_history:
# st.chat_message(role).markdown(message)
# # List of keywords related to food to detect user intent for food recommendations
# food_keywords = ["food", "hungry", "meal", "recommendation", "eat", "dish", "cuisine"]
# # List of positive responses to detect affirmative answers
# positive_responses = ["yes", "yep", "okay", "sure", "absolutely", "definitely", "of course", "yeah", "affirmative"]
# # Function to check if user input contains any keyword from a list
# def contains_keyword(user_input, keywords):
# return any(keyword in user_input.lower() for keyword in keywords)
# # Capture user input and generate bot response
# if user_input := st.chat_input("Say something..."):
# # Store and display user message
# st.session_state.chat_history.append(("user", user_input))
# st.chat_message("user").markdown(user_input)
# # Process user input based on conversation context
# if st.session_state.awaiting_hungry_response:
# # Check if the user responded positively
# if contains_keyword(user_input, positive_responses):
# # Generate a food recommendation response using Gemini AI
# if 'model' in locals():
# try:
# # Custom prompt for food recommendation
# food_prompt = f"Can you recommend a delicious Thai {meal_type.lower()} option?"
# response = model.generate_content(food_prompt)
# bot_response = response.text
# # Store and display the bot response
# st.session_state.chat_history.append(("assistant", bot_response))
# st.chat_message("assistant").markdown(bot_response)
# except Exception as e:
# st.error(f"An error occurred while generating the response: {e}")
# else:
# # User did not respond positively; respond accordingly
# bot_response = "Alright, let me know if you need any food recommendations!"
# st.session_state.chat_history.append(("assistant", bot_response))
# st.chat_message("assistant").markdown(bot_response)
# # Reset the hunger response flag
# st.session_state.awaiting_hungry_response = False
# else:
# # Check if the user input contains any food-related keywords
# if contains_keyword(user_input, food_keywords):
# # Generate a food recommendation response using Gemini AI
# if 'model' in locals():
# try:
# # Custom prompt for food recommendation
# food_prompt = "Can you recommend a delicious meal or food option?"
# response = model.generate_content(food_prompt)
# bot_response = response.text
# # Store and display the bot response
# st.session_state.chat_history.append(("assistant", bot_response))
# st.chat_message("assistant").markdown(bot_response)
# except Exception as e:
# st.error(f"An error occurred while generating the response: {e}")
# else:
# # Generate a different response for non-food-related inputs
# bot_response = "Tell me.. are you hungry?"
# st.session_state.chat_history.append(("assistant", bot_response))
# st.chat_message("assistant").markdown(bot_response)
# # Set the flag to indicate that the bot is awaiting a hunger response
# st.session_state.awaiting_hungry_response = True
import streamlit as st
import google.generativeai as genai
from datetime import datetime
import pytz
st.title("🍜 This Meal? Chatbot App")
st.subheader("Conversation")
# Capture Gemini API Key
gemini_api_key = st.text_input("Gemini API Key: ", placeholder="Type the API", type="password")
# Initialize the Gemini Model
if gemini_api_key:
try:
# Configure Gemini with the provided API Key
genai.configure(api_key=gemini_api_key)
model = genai.GenerativeModel("gemini-pro")
st.success("Gemini API Key successfully configured.")
except Exception as e:
st.error(f"An error occurred while setting up the Gemini model: {e}")
# Initialize session state for storing chat history and conversation context
if "chat_history" not in st.session_state:
st.session_state.chat_history = [] # Initialize with an empty list
if "awaiting_hungry_response" not in st.session_state:
st.session_state.awaiting_hungry_response = False # Flag to track if bot asked about hunger
# Display previous chat history using st.chat_message (if available)
for role, message in st.session_state.chat_history:
st.chat_message(role).markdown(message)
# List of keywords related to food to detect user intent for food recommendations
food_keywords = ["food", "hungry", "meal", "recommendation", "eat", "dish", "cuisine"]
# List of positive responses to detect affirmative answers
positive_responses = ["yes", "yep", "okay", "sure", "absolutely", "definitely", "of course", "yeah", "affirmative"]
# Function to check if user input contains any keyword from a list
def contains_keyword(user_input, keywords):
return any(keyword in user_input.lower() for keyword in keywords)
# Function to determine the meal based on current time in GMT+7
def get_current_meal():
tz = pytz.timezone('Asia/Bangkok') # Timezone for GMT+7 (Thailand)
current_time = datetime.now(tz).time()
if current_time >= datetime.strptime("06:00", "%H:%M").time() and current_time <= datetime.strptime("10:00", "%H:%M").time():
return "breakfast"
elif current_time > datetime.strptime("10:00", "%H:%M").time() and current_time <= datetime.strptime("14:00", "%H:%M").time():
return "lunch"
elif current_time > datetime.strptime("14:00", "%H:%M").time() and current_time <= datetime.strptime("18:00", "%H:%M").time():
return "afternoon snack"
elif current_time > datetime.strptime("18:00", "%H:%M").time() and current_time <= datetime.strptime("21:00", "%H:%M").time():
return "dinner"
else:
return "late night snack"
# Capture user input and generate bot response
if user_input := st.chat_input("Say something..."):
# Store and display user message
st.session_state.chat_history.append(("user", user_input))
st.chat_message("user").markdown(user_input)
# Process user input based on conversation context
if st.session_state.awaiting_hungry_response:
# Check if the user responded positively
if contains_keyword(user_input, positive_responses):
# Determine current meal based on GMT+7 timezone
meal_type = get_current_meal()
# Generate a food recommendation response using Gemini AI
if 'model' in locals():
try:
# Custom prompt for Thai food recommendation based on meal type
food_prompt = f"Can you recommend a delicious Thai {meal_type} option?"
response = model.generate_content(food_prompt)
bot_response = response.text
# Store and display the bot response
st.session_state.chat_history.append(("assistant", bot_response))
st.chat_message("assistant").markdown(bot_response)
except Exception as e:
st.error(f"An error occurred while generating the response: {e}")
else:
# User did not respond positively; respond accordingly
bot_response = "Alright, let me know if you need any food recommendations!"
st.session_state.chat_history.append(("assistant", bot_response))
st.chat_message("assistant").markdown(bot_response)
# Reset the hunger response flag
st.session_state.awaiting_hungry_response = False
else:
# Check if the user input contains any food-related keywords
if contains_keyword(user_input, food_keywords):
# Determine current meal based on GMT+7 timezone
meal_type = get_current_meal()
# Generate a Thai food recommendation response using Gemini AI based on the current meal time
if 'model' in locals():
try:
# Custom prompt for Thai food recommendation
food_prompt = f"Can you recommend a delicious Thai {meal_type} option?"
response = model.generate_content(food_prompt)
bot_response = response.text
# Store and display the bot response
st.session_state.chat_history.append(("assistant", bot_response))
st.chat_message("assistant").markdown(bot_response)
except Exception as e:
st.error(f"An error occurred while generating the response: {e}")
else:
# Generate a different response for non-food-related inputs
bot_response = "Tell me... are you hungry?"
st.session_state.chat_history.append(("assistant", bot_response))
st.chat_message("assistant").markdown(bot_response)
# Set the flag to indicate that the bot is awaiting a hunger response
st.session_state.awaiting_hungry_response = True