-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_UI.py
More file actions
186 lines (154 loc) · 6.95 KB
/
streamlit_UI.py
File metadata and controls
186 lines (154 loc) · 6.95 KB
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
import random
import streamlit as st
import requests
import pytz
from datetime import date
# Get the system's default timezone
default_timezone = pytz.timezone(pytz.country_timezones['US'][0])
# Get the user's timezone based on their IP address
user_timezone = pytz.timezone(requests.get('https://ipapi.co/timezone/').text)
# Determine the selected timezone
timezone = user_timezone if user_timezone else default_timezone
today = date.today()
st.set_page_config(page_title="Chronologic", page_icon="📆", layout="wide")
st.title('Chronologic')
def initiate_authorization():
auth_url = 'http://localhost:5000/authorize/google'
st.markdown(f"""
<meta http-equiv="refresh" content="0; url={auth_url}">
If you are not redirected automatically, <a href="{auth_url}">click here</a>.
""", unsafe_allow_html=True)
def get_token_from_url():
query_params = st.query_params
token = query_params.get('token', None)
if token:
st.session_state['token'] = token
st.query_params.clear()
# Function to get the user's prompt and send it to the LLM via the Flask API
def send_prompt_to_llm(prompt):
api_url = 'http://localhost:5000/chat' # Replace with your actual API URL
headers = {'Content-Type': 'application/json'}
response = requests.post(api_url, json={'prompt': prompt}, headers=headers)
if response.status_code == 200:
return response.json()
else:
st.error('Failed to communicate with the server')
return None
def calendar_interaction(event, function_to_call):
api_url = f'http://localhost:5000/{function_to_call}'
headers = {'Content-Type': 'application/json', 'Authorization': f"Bearer {st.session_state['token']}"}
response = requests.post(api_url, json={'event': event}, headers=headers)
if response.status_code == 200:
return response.json()
else:
return response
def get_calendar():
headers = {'Authorization': f"Bearer {st.session_state['token']}"}
response = requests.get('http://localhost:5000/calendar', headers=headers)
if response.status_code == 200:
calendar = response.json()
else:
st.error('Failed to retrieve calendar.')
return calendar
if 'token' not in st.session_state:
get_token_from_url()
def pick_suggestions(recommended_suggestions):
if len(recommended_suggestions) < 3:
raise ValueError("The list must contain at least 3 suggestions.")
# Randomly choose 3 unique suggestions
return random.sample(recommended_suggestions, 3)
# Exhaustive list of suggestions
recommended_suggestions = [
"Create a new event for the team meeting at 10 AM tomorrow",
"Delete the lunch meeting scheduled for Friday",
"Update the project review meeting to 3 PM instead of 2 PM",
"Set up a recurring event for daily stand-up meetings at 9 AM",
"Cancel the one-on-one meeting with John next Monday",
"Move the weekly sync meeting to Wednesdays at 4 PM",
"Add a reminder for the dentist appointment next Thursday",
"Schedule a call with the client on Tuesday at 11 AM",
"Reschedule the board meeting to next Friday at 2 PM",
"Remove the dinner reservation from the calendar",
"Change the location of the quarterly review meeting to the main office",
"Set a meeting with the marketing team at 1 PM on Thursday",
"Clear all events from the calendar on Sunday",
"Adjust the start time of the training session to 9:30 AM",
"Add a new event for the software release on August 1st",
"Delete the outdated conference call on the calendar",
"Update the status meeting to be an all-day event",
"Set a personal appointment for a haircut on Saturday at 10 AM",
"Cancel the weekend workshop scheduled for next month",
"Move the brainstorming session to the afternoon at 2 PM"
]
# Ensure Streamlit's session state is initialized for picked_suggestions
if "picked_suggestions" not in st.session_state:
st.session_state.picked_suggestions = pick_suggestions(recommended_suggestions) ## add .copy() to make the code more secure in case we add things in the future
# Get suggestions from session state
suggestion, suggestion2, suggestion3 = st.session_state.picked_suggestions
if 'token' in st.session_state:
# st.button('Get Google Calendar Events', on_click=get_events)
col1, col2, col3 = st.columns(3)
with st.container():
with col1:
button1 = st.button(suggestion)
with col2:
button2 = st.button(suggestion2)
with col3:
button3 = st.button(suggestion3)
# Start state for chat responses
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Check if prompt is present and if button is pressed
prompt = st.chat_input("How can I help you today?")
if button1:
prompt = suggestion
elif button2:
prompt = suggestion2
elif button3:
prompt = suggestion3
# Store prompt in state
if prompt:
with st.chat_message("User", avatar="📆"):
st.markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
# Chatbot response
prompt = prompt + " Timezone is " + str(timezone.zone) + f". Today's date is {today}."
response = send_prompt_to_llm(prompt)
with st.chat_message("Assistant", avatar="🤖"):
st.markdown(response)
while response is None or response['function_to_call'] is None:
response = send_prompt_to_llm(prompt)
function_to_call = response['function_to_call']
# Remove the function_to_call key from the response
response = {key: value for key, value in response.items() if key != 'function_to_call'}
response = calendar_interaction(event=response, function_to_call=function_to_call)
with st.chat_message("Assistant", avatar="🤖"):
if response['message']:
st.markdown(response['message'])
else:
st.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response['message']})
st.rerun()
else:
st.write('Log in to Google Calendar in the sidebar to get started.')
with st.sidebar:
if 'token' in st.session_state:
calendar = get_calendar()
st.header('Welcome!')
st.markdown(f'''
<iframe id="calendar-iframe" src="{calendar['embed_link']}" style="border: 0" width="450" height="400" frameborder="0" scrolling="no">
<meta http-equiv="refresh" content="300">
</iframe>
''',
unsafe_allow_html=True)
if st.button('Logout'):
st.session_state.pop('token')
st.query_params.clear()
st.rerun()
else:
st.write('Log in to Google Calendar')
if st.button('Login'):
initiate_authorization()