-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
396 lines (350 loc) · 13.9 KB
/
Copy pathstreamlit_app.py
File metadata and controls
396 lines (350 loc) · 13.9 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import streamlit as st
import requests
import json
import datetime
import pandas as pd
import calendar
from datetime import datetime, timedelta
import time
# Set page configuration
st.set_page_config(
page_title="AssistantAGI Calendar",
page_icon="📅",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for styling
st.markdown("""
<style>
.main {
padding: 1rem;
}
.calendar-container {
background-color: white;
border-radius: 10px;
padding: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.chat-container {
background-color: #f9f9f9;
border-radius: 10px;
padding: 15px;
margin-top: 20px;
height: 400px;
overflow-y: auto;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.message {
padding: 10px;
margin: 5px 0;
border-radius: 10px;
}
.user-message {
background-color: #e1f5fe;
text-align: right;
margin-left: 20%;
}
.assistant-message {
background-color: #f0f0f0;
text-align: left;
margin-right: 20%;
}
.event-form {
background-color: #f0f8ff;
padding: 15px;
border-radius: 10px;
margin-top: 20px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.stButton button {
width: 100%;
background-color: #4CAF50;
color: white;
}
.calendar-day {
text-align: center;
padding: 10px;
border: 1px solid #ddd;
height: 100px;
overflow-y: auto;
}
.calendar-day:hover {
background-color: #f5f5f5;
}
.calendar-header {
text-align: center;
font-weight: bold;
padding: 10px;
background-color: #4CAF50;
color: white;
}
.calendar-event {
background-color: #4CAF50;
color: white;
border-radius: 5px;
padding: 2px 5px;
margin: 2px 0;
font-size: 0.8em;
cursor: pointer;
}
.today {
background-color: #e8f5e9;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if 'events' not in st.session_state:
st.session_state.events = []
if 'current_month' not in st.session_state:
st.session_state.current_month = datetime.now().month
if 'current_year' not in st.session_state:
st.session_state.current_year = datetime.now().year
if 'selected_date' not in st.session_state:
st.session_state.selected_date = datetime.now().date()
# Flask API endpoint
FLASK_API_URL = "http://localhost:5000"
# Function to send message to AssistantAGI
def send_message_to_assistant(message):
try:
response = requests.post(
f"{FLASK_API_URL}/chat",
json={"query": message},
timeout=30
)
response.raise_for_status()
return response.json()['response']
except requests.exceptions.RequestException as e:
st.error(f"Error communicating with AssistantAGI: {str(e)}")
return "Sorry, I couldn't process your request. Please try again later."
# Function to fetch events
def fetch_events():
try:
# In a real implementation, you would fetch events from your CalDAV server
# For now, we'll use dummy data
events = [
{
"id": "1",
"title": "Team Meeting",
"start": datetime.now().replace(hour=10, minute=0).isoformat(),
"end": datetime.now().replace(hour=11, minute=0).isoformat(),
"description": "Weekly team sync",
"location": "Conference Room A"
},
{
"id": "2",
"title": "Lunch with Client",
"start": (datetime.now() + timedelta(days=1)).replace(hour=12, minute=30).isoformat(),
"end": (datetime.now() + timedelta(days=1)).replace(hour=13, minute=30).isoformat(),
"description": "Discuss project requirements",
"location": "Downtown Cafe"
},
{
"id": "3",
"title": "Project Deadline",
"start": (datetime.now() + timedelta(days=3)).replace(hour=17, minute=0).isoformat(),
"end": (datetime.now() + timedelta(days=3)).replace(hour=17, minute=0).isoformat(),
"description": "Submit final deliverables",
"location": ""
}
]
return events
except Exception as e:
st.error(f"Error fetching events: {str(e)}")
return []
# Function to create a new event
def create_event(title, start, end, description, location):
try:
event = {
"id": str(len(st.session_state.events) + 1),
"title": title,
"start": start.isoformat(),
"end": end.isoformat(),
"description": description,
"location": location
}
st.session_state.events.append(event)
return True
except Exception as e:
st.error(f"Error creating event: {str(e)}")
return False
# Function to render calendar
def render_calendar():
# Get the first day of the month and the number of days
first_day = datetime(st.session_state.current_year, st.session_state.current_month, 1)
last_day = (datetime(st.session_state.current_year, st.session_state.current_month + 1, 1)
if st.session_state.current_month < 12
else datetime(st.session_state.current_year + 1, 1, 1)) - timedelta(days=1)
# Get the day of the week for the first day (0 is Monday in calendar module)
first_weekday = first_day.weekday()
# Create calendar header
month_name = calendar.month_name[st.session_state.current_month]
st.markdown(f"<h2 class='calendar-header'>{month_name} {st.session_state.current_year}</h2>", unsafe_allow_html=True)
# Navigation buttons
col1, col2, col3 = st.columns([1, 3, 1])
with col1:
if st.button("◀ Previous"):
if st.session_state.current_month > 1:
st.session_state.current_month -= 1
else:
st.session_state.current_month = 12
st.session_state.current_year -= 1
st.rerun()
with col3:
if st.button("Next ▶"):
if st.session_state.current_month < 12:
st.session_state.current_month += 1
else:
st.session_state.current_month = 1
st.session_state.current_year += 1
st.rerun()
# Create weekday headers
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
cols = st.columns(7)
for i, col in enumerate(cols):
with col:
st.markdown(f"<div class='calendar-header'>{weekdays[i]}</div>", unsafe_allow_html=True)
# Create calendar grid
day = 1
for week in range(6): # Maximum 6 weeks in a month view
if day > last_day.day:
break
cols = st.columns(7)
for i, col in enumerate(cols):
with col:
# Skip days before the first day of the month
if week == 0 and i < first_weekday:
st.markdown("<div class='calendar-day'></div>", unsafe_allow_html=True)
elif day <= last_day.day:
# Check if this is today
is_today = (day == datetime.now().day and
st.session_state.current_month == datetime.now().month and
st.session_state.current_year == datetime.now().year)
# Check if this is the selected date
is_selected = (day == st.session_state.selected_date.day and
st.session_state.current_month == st.session_state.selected_date.month and
st.session_state.current_year == st.session_state.selected_date.year)
# Get events for this day
current_date = datetime(st.session_state.current_year, st.session_state.current_month, day).date()
day_events = [e for e in st.session_state.events
if datetime.fromisoformat(e['start']).date() == current_date]
# Create day cell with appropriate styling
day_class = "calendar-day"
if is_today:
day_class += " today"
if is_selected:
day_class += " selected"
# Create clickable day cell
if st.button(f"{day}", key=f"day_{day}_{week}"):
st.session_state.selected_date = datetime(
st.session_state.current_year,
st.session_state.current_month,
day
).date()
st.rerun()
# Display events for this day
for event in day_events:
event_time = datetime.fromisoformat(event['start']).strftime('%H:%M')
st.markdown(
f"<div class='calendar-event' title='{event['title']}'>"
f"{event_time} {event['title'][:10]}{'...' if len(event['title']) > 10 else ''}"
f"</div>",
unsafe_allow_html=True
)
day += 1
else:
st.markdown("<div class='calendar-day'></div>", unsafe_allow_html=True)
# Function to display event details
def display_event_details():
st.subheader(f"Events on {st.session_state.selected_date.strftime('%B %d, %Y')}")
# Get events for the selected date
selected_date_events = [e for e in st.session_state.events
if datetime.fromisoformat(e['start']).date() == st.session_state.selected_date]
if not selected_date_events:
st.write("No events scheduled for this day.")
else:
for event in selected_date_events:
with st.expander(f"{event['title']} ({datetime.fromisoformat(event['start']).strftime('%H:%M')} - {datetime.fromisoformat(event['end']).strftime('%H:%M')})"):
st.write(f"**Description:** {event['description']}")
st.write(f"**Location:** {event['location'] or 'Not specified'}")
# Function to display event form
def display_event_form():
st.subheader("Add New Event")
with st.form("event_form"):
title = st.text_input("Event Title")
col1, col2 = st.columns(2)
with col1:
event_date = st.date_input("Date", value=st.session_state.selected_date)
col1, col2 = st.columns(2)
with col1:
start_time = st.time_input("Start Time", value=datetime.now().replace(hour=9, minute=0).time())
with col2:
end_time = st.time_input("End Time", value=datetime.now().replace(hour=10, minute=0).time())
description = st.text_area("Description")
location = st.text_input("Location")
submitted = st.form_submit_button("Add Event")
if submitted:
if title:
start_datetime = datetime.combine(event_date, start_time)
end_datetime = datetime.combine(event_date, end_time)
if create_event(title, start_datetime, end_datetime, description, location):
st.success("Event created successfully!")
time.sleep(1) # Give user time to see the success message
st.rerun()
else:
st.error("Event title is required.")
# Function to display chat interface
def display_chat_interface():
st.subheader("Chat with AssistantAGI")
# Display chat history
with st.container():
for message in st.session_state.chat_history:
if message['role'] == 'user':
st.markdown(f"<div class='message user-message'>{message['content']}</div>", unsafe_allow_html=True)
else:
st.markdown(f"<div class='message assistant-message'>{message['content']}</div>", unsafe_allow_html=True)
# Chat input
with st.form("chat_form", clear_on_submit=True):
user_input = st.text_input("Type your message:", key="user_message")
submitted = st.form_submit_button("Send")
if submitted and user_input:
# Add user message to chat history
st.session_state.chat_history.append({
'role': 'user',
'content': user_input
})
# Get response from AssistantAGI
with st.spinner("AssistantAGI is thinking..."):
response = send_message_to_assistant(user_input)
# Add assistant response to chat history
st.session_state.chat_history.append({
'role': 'assistant',
'content': response
})
st.rerun()
# Main application
def main():
st.title("AssistantAGI Calendar")
# Fetch events if not already loaded
if not st.session_state.events:
st.session_state.events = fetch_events()
# Create two columns for layout
col1, col2 = st.columns([2, 1])
with col1:
# Display calendar
with st.container():
render_calendar()
# Display event details for selected date
with st.container():
display_event_details()
with col2:
# Display event form
with st.container():
display_event_form()
# Display chat interface
with st.container():
display_chat_interface()
if __name__ == "__main__":
main()