atharv-16 commited on
Commit
7e234ea
·
verified ·
1 Parent(s): d606ebb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -367
app.py CHANGED
@@ -2,8 +2,7 @@ import streamlit as st
2
  from datetime import datetime, timedelta
3
  import re
4
  import os
5
- import json
6
- from scheduler import get_calendar_service, find_meetings_with_person
7
  from autonomous_agent import SchedulingAgent
8
 
9
  st.set_page_config(page_title="Autonomous Calendar Assistant", page_icon="📅")
@@ -39,17 +38,17 @@ def agent_page():
39
  st.title("Autonomous Calendar Agent")
40
 
41
  try:
42
-
43
  service = get_calendar_service()
44
 
45
-
46
  agent = SchedulingAgent(service)
47
 
48
-
49
- st.write("### AI Calendar Assistant")
50
-
51
 
52
-
53
  with st.expander("Your Scheduling Preferences"):
54
  prefs = agent.preferences
55
 
@@ -71,378 +70,46 @@ def agent_page():
71
  for contact in prefs['frequent_contacts'][:5]:
72
  st.write(f"- {contact}")
73
 
74
-
75
-
76
-
77
- # Example commands in tabs
78
- example_tabs = st.tabs(["Scheduling", "Finding", "Managing", "Availability"])
79
-
80
- with example_tabs[0]:
81
- st.markdown("""
82
- **Example scheduling commands:**
83
- - Schedule a meeting with Alex tomorrow at 2pm
84
- - Set up a 30 minute call with Morgan next Friday
85
- - Find a good time to meet with Taylor next week
86
- - Book a 1 hour meeting with the team on Monday
87
- """)
88
-
89
- with example_tabs[1]:
90
- st.markdown("""
91
- **Example finding commands:**
92
- - Find all meetings with Alex
93
- - Show me meetings for next Monday
94
- - What meetings do I have with the team this month?
95
- - Find my meetings for the week of June 10th
96
- """)
97
-
98
- with example_tabs[2]:
99
- st.markdown("""
100
- **Example management commands:**
101
- - Cancel my meeting with Alex on Friday
102
- - Reschedule my call with Morgan to next Tuesday at 3pm
103
- - Move my 2pm meeting to 4pm tomorrow
104
- - Delete all meetings with Marketing team
105
- """)
106
-
107
- with example_tabs[3]:
108
- st.markdown("""
109
- **Example availability commands:**
110
- - When am I free tomorrow?
111
- - Check my availability for next Wednesday
112
- - Find a free slot for a 2 hour meeting next week
113
- - What's my schedule for Monday?
114
- """)
115
-
116
-
117
  command = st.text_area(
118
- "Enter your request:",
119
  height=100,
120
- placeholder="Type your request here..."
121
  )
122
 
123
-
124
  if st.button("Process"):
125
  if not command:
126
  st.warning("Please enter a command first.")
127
  return
128
 
129
  with st.spinner("Processing your request..."):
130
-
131
- command_lower = command.lower()
132
 
133
-
134
- if any(x in command_lower for x in ["find", "show", "list", "what meeting", "which meeting"]):
135
-
136
- if "with" in command_lower:
137
- person_match = re.search(r'(?:with|and)\s+(\w+(?:\s+\w+)?)', command_lower)
138
- if person_match:
139
- person = person_match.group(1).strip()
140
-
141
-
142
- date_constraints = {}
143
- if "today" in command_lower:
144
- today = datetime.now()
145
- date_constraints["time_min"] = datetime.combine(today.date(), datetime.min.time()).isoformat() + "Z"
146
- date_constraints["time_max"] = datetime.combine(today.date(), datetime.max.time()).isoformat() + "Z"
147
- elif "tomorrow" in command_lower:
148
- tomorrow = datetime.now() + timedelta(days=1)
149
- date_constraints["time_min"] = datetime.combine(tomorrow.date(), datetime.min.time()).isoformat() + "Z"
150
- date_constraints["time_max"] = datetime.combine(tomorrow.date(), datetime.max.time()).isoformat() + "Z"
151
- elif "week" in command_lower:
152
- today = datetime.now()
153
- start_of_week = today - timedelta(days=today.weekday())
154
- end_of_week = start_of_week + timedelta(days=6)
155
- date_constraints["time_min"] = datetime.combine(start_of_week.date(), datetime.min.time()).isoformat() + "Z"
156
- date_constraints["time_max"] = datetime.combine(end_of_week.date(), datetime.max.time()).isoformat() + "Z"
157
-
158
-
159
- meetings = find_meetings_with_person(service, "primary", person, **date_constraints)
160
-
161
- if meetings:
162
- st.success(f"Found {len(meetings)} meetings with {person}")
163
-
164
- for i, meeting in enumerate(meetings):
165
- start_time = meeting['start']
166
- if 'T' in start_time:
167
- start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
168
- formatted_time = start_dt.strftime("%A, %b %d, %Y at %I:%M %p")
169
- else:
170
- formatted_time = start_time
171
-
172
- with st.expander(f"{i+1}. {meeting['summary']} - {formatted_time}"):
173
- st.write(f"**Time:** {formatted_time}")
174
- st.markdown(f"[View in Calendar]({meeting['htmlLink']})")
175
-
176
-
177
- if st.button(f"Cancel this meeting", key=f"cancel_{i}"):
178
- try:
179
- service.events().delete(calendarId="primary", eventId=meeting['id']).execute()
180
- st.success("Meeting cancelled!")
181
- st.rerun()
182
- except Exception as e:
183
- st.error(f"Error cancelling meeting: {str(e)}")
184
- else:
185
- st.info(f"No meetings found with {person} in the specified time range.")
186
-
187
-
188
- elif any(x in command_lower for x in ["today", "tomorrow", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]):
189
-
190
- date_value = None
191
-
192
- if "today" in command_lower:
193
- date_value = datetime.now().date()
194
- elif "tomorrow" in command_lower:
195
- date_value = (datetime.now() + timedelta(days=1)).date()
196
- else:
197
-
198
- day_mapping = {
199
- "monday": 0, "tuesday": 1, "wednesday": 2,
200
- "thursday": 3, "friday": 4, "saturday": 5, "sunday": 6
201
- }
202
-
203
- for day_name, day_number in day_mapping.items():
204
- if day_name in command_lower:
205
- today = datetime.now()
206
- days_ahead = (day_number - today.weekday()) % 7
207
- if days_ahead == 0: # Today
208
- days_ahead = 7 # Next week
209
- date_value = (today + timedelta(days=days_ahead)).date()
210
- break
211
-
212
- if date_value:
213
 
214
- start_dt = datetime.combine(date_value, datetime.min.time())
215
- end_dt = datetime.combine(date_value, datetime.max.time())
216
-
217
- time_min = start_dt.isoformat() + "Z"
218
- time_max = end_dt.isoformat() + "Z"
219
-
220
- try:
221
- events_result = service.events().list(
222
- calendarId="primary",
223
- timeMin=time_min,
224
- timeMax=time_max,
225
- singleEvents=True,
226
- orderBy='startTime'
227
- ).execute()
228
-
229
- events = events_result.get('items', [])
230
-
231
- if events:
232
- date_str = start_dt.strftime("%A, %B %d, %Y")
233
- st.success(f"Your schedule for {date_str}:")
234
-
235
- for i, event in enumerate(events):
236
- summary = event.get('summary', 'No Title')
237
- start = event['start'].get('dateTime', event['start'].get('date'))
238
-
239
- if 'T' in start:
240
- start_dt = datetime.fromisoformat(start.replace('Z', '+00:00'))
241
- time_str = start_dt.strftime("%I:%M %p")
242
- else:
243
- time_str = "All day"
244
-
245
- with st.expander(f"{i+1}. {summary} at {time_str}"):
246
- st.markdown(f"**Event:** {summary}")
247
- st.markdown(f"**Time:** {time_str}")
248
- st.markdown(f"[View in Calendar]({event.get('htmlLink', '#')})")
249
-
250
-
251
- if st.button(f"Cancel this event", key=f"cancel_event_{i}"):
252
- try:
253
- service.events().delete(calendarId="primary", eventId=event['id']).execute()
254
- st.success("Event cancelled!")
255
- st.rerun()
256
- except Exception as e:
257
- st.error(f"Error cancelling event: {str(e)}")
258
- else:
259
- st.info(f"You have no events scheduled for {start_dt.strftime('%A, %B %d')}.")
260
- except Exception as e:
261
- st.error(f"Error fetching events: {str(e)}")
262
-
263
-
264
- else:
265
- result = agent.process_command(command)
266
-
267
- if result["status"] == "suggestions":
268
- st.info(result["message"])
269
- for i, slot in enumerate(result["slots"]):
270
- st.write(f"{i+1}. {slot}")
271
- else:
272
- st.info("I couldn't find specific meetings. Try adding more details like a person's name or a date.")
273
 
274
-
275
- elif any(x in command_lower for x in ["schedule", "set up", "create", "book", "plan", "arrange"]):
276
-
277
- result = agent.process_command(command)
278
-
279
- if result["status"] == "created":
280
- st.success(result["message"])
281
- st.markdown(f"[View in Calendar]({result['event_link']})")
282
-
283
-
284
- if "alternatives" in result and result["alternatives"]:
285
- st.markdown("**Alternative times that would also work:**")
286
- for i, alt in enumerate(result["alternatives"]):
287
- if isinstance(alt, dict) and 'start' in alt:
288
- start_dt = datetime.fromisoformat(alt['start'].replace('Z', '+00:00'))
289
- st.write(f"{i+1}. {start_dt.strftime('%A, %b %d at %I:%M %p')}")
290
-
291
- elif result["status"] == "rescheduled":
292
- st.warning(result["message"])
293
- st.markdown(f"[View in Calendar]({result['event_link']})")
294
-
295
- else:
296
- st.error(result["message"])
297
 
298
-
299
- elif any(x in command_lower for x in ["cancel", "delete", "remove"]):
300
-
301
- person_match = re.search(r'(?:with|and)\s+(\w+(?:\s+\w+)?)', command_lower)
302
- if person_match:
303
- person = person_match.group(1).strip()
304
-
305
-
306
- meetings = find_meetings_with_person(service, "primary", person)
307
-
308
- if meetings:
309
- st.warning(f"Found {len(meetings)} meetings with {person}. Which one would you like to cancel?")
310
-
311
- for i, meeting in enumerate(meetings):
312
- start_time = meeting['start']
313
- if 'T' in start_time:
314
- start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
315
- formatted_time = start_dt.strftime("%A, %b %d, %Y at %I:%M %p")
316
- else:
317
- formatted_time = start_time
318
-
319
- col1, col2 = st.columns([3, 1])
320
- with col1:
321
- st.write(f"**{i+1}. {meeting['summary']}** - {formatted_time}")
322
- with col2:
323
- if st.button(f"Cancel", key=f"cancel_meeting_{i}"):
324
- try:
325
- service.events().delete(calendarId="primary", eventId=meeting['id']).execute()
326
- st.success(f"Meeting '{meeting['summary']}' cancelled!")
327
- st.rerun()
328
- except Exception as e:
329
- st.error(f"Error cancelling meeting: {str(e)}")
330
- else:
331
- st.info(f"No upcoming meetings found with {person}.")
332
- else:
333
- st.warning("Please specify whose meeting you want to cancel (e.g., 'Cancel meeting with Alex')")
334
 
335
-
336
- elif any(x in command_lower for x in ["free", "available", "when can i", "availability"]):
337
-
338
- date_value = None
339
-
340
- if "today" in command_lower:
341
- date_value = datetime.now().date()
342
- elif "tomorrow" in command_lower:
343
- date_value = (datetime.now() + timedelta(days=1)).date()
344
- else:
345
-
346
- day_mapping = {
347
- "monday": 0, "tuesday": 1, "wednesday": 2,
348
- "thursday": 3, "friday": 4, "saturday": 5, "sunday": 6
349
- }
350
-
351
- for day_name, day_number in day_mapping.items():
352
- if day_name in command_lower:
353
- today = datetime.now()
354
- days_ahead = (day_number - today.weekday()) % 7
355
- if days_ahead == 0: # Today
356
- days_ahead = 7 # Next week
357
- date_value = (today + timedelta(days=days_ahead)).date()
358
- break
359
-
360
-
361
- if not date_value:
362
- date_value = (datetime.now() + timedelta(days=1)).date()
363
-
364
-
365
- start_dt = datetime.combine(date_value, datetime.min.time().replace(hour=9)) # 9 AM
366
- end_dt = datetime.combine(date_value, datetime.min.time().replace(hour=17)) # 5 PM
367
-
368
- time_min = start_dt.isoformat() + "Z"
369
- time_max = end_dt.isoformat() + "Z"
370
-
371
-
372
- freebusy_query = {
373
- "timeMin": time_min,
374
- "timeMax": time_max,
375
- "items": [{"id": "primary"}]
376
- }
377
-
378
- try:
379
- freebusy_result = service.freebusy().query(body=freebusy_query).execute()
380
- busy_slots = freebusy_result['calendars']['primary']['busy']
381
-
382
- date_str = start_dt.strftime("%A, %B %d")
383
-
384
- if busy_slots:
385
- st.info(f"Your availability for {date_str}:")
386
-
387
- # Create a timeline from 9 AM to 5 PM
388
- hour_slots = []
389
- for hour in range(9, 18):
390
- slot_start = datetime.combine(date_value, datetime.min.time().replace(hour=hour))
391
- slot_end = slot_start + timedelta(hours=1)
392
-
393
- # Check if this slot overlaps with any busy time
394
- is_busy = False
395
- for busy in busy_slots:
396
- busy_start = datetime.fromisoformat(busy['start'].replace('Z', '+00:00'))
397
- busy_end = datetime.fromisoformat(busy['end'].replace('Z', '+00:00'))
398
-
399
- if (slot_start < busy_end and slot_end > busy_start):
400
- is_busy = True
401
- break
402
-
403
- hour_slots.append({
404
- "hour": hour,
405
- "is_busy": is_busy,
406
- "time_str": slot_start.strftime("%I:%M %p")
407
- })
408
-
409
- # Display timeline
410
- col1, col2 = st.columns([1, 3])
411
- with col1:
412
- st.markdown("**Time**")
413
- for slot in hour_slots:
414
- st.write(slot["time_str"])
415
-
416
-
417
- with col2:
418
- st.markdown("**Status**")
419
- for slot in hour_slots:
420
- if slot["is_busy"]:
421
- st.markdown("🔴 Busy")
422
- else:
423
- st.markdown("🟢 Available")
424
-
425
- else:
426
- st.success(f"You're completely free on {date_str} from 9 AM to 5 PM!")
427
- except Exception as e:
428
- st.error(f"Error checking availability: {str(e)}")
429
-
430
-
431
  else:
432
- result = agent.process_command(command)
433
-
434
- if result["status"] == "created":
435
- st.success(result["message"])
436
- st.markdown(f"[View in Calendar]({result['event_link']})")
437
- elif result["status"] == "rescheduled":
438
- st.warning(result["message"])
439
- st.markdown(f"[View in Calendar]({result['event_link']})")
440
- elif result["status"] == "suggestions":
441
- st.info(result["message"])
442
- for i, slot in enumerate(result["slots"]):
443
- st.write(f"{i+1}. {slot}")
444
- else:
445
- st.error(result["message"])
446
 
447
  except Exception as e:
448
  st.error(f"Error: {str(e)}")
@@ -450,11 +117,11 @@ def agent_page():
450
  st.session_state['authenticated'] = False
451
  st.rerun()
452
 
453
-
454
  if 'authenticated' not in st.session_state:
455
  st.session_state['authenticated'] = False
456
 
457
-
458
  if st.session_state['authenticated']:
459
  if st.sidebar.button("Logout"):
460
  st.session_state['authenticated'] = False
@@ -462,7 +129,7 @@ if st.session_state['authenticated']:
462
  del st.session_state['user_token']
463
  st.rerun()
464
 
465
-
466
  if st.session_state['authenticated']:
467
  agent_page()
468
  else:
 
2
  from datetime import datetime, timedelta
3
  import re
4
  import os
5
+ from scheduler import get_calendar_service
 
6
  from autonomous_agent import SchedulingAgent
7
 
8
  st.set_page_config(page_title="Autonomous Calendar Assistant", page_icon="📅")
 
38
  st.title("Autonomous Calendar Agent")
39
 
40
  try:
41
+ # Get the service again
42
  service = get_calendar_service()
43
 
44
+ # Create our intelligent agent
45
  agent = SchedulingAgent(service)
46
 
47
+ # User Interface
48
+ st.write("### Your AI Calendar Assistant")
49
+ st.write("I can help schedule meetings, find optimal times, and manage your calendar intelligently.")
50
 
51
+ # Show user preferences
52
  with st.expander("Your Scheduling Preferences"):
53
  prefs = agent.preferences
54
 
 
70
  for contact in prefs['frequent_contacts'][:5]:
71
  st.write(f"- {contact}")
72
 
73
+ # Command input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  command = st.text_area(
75
+ "What would you like to do?",
76
  height=100,
77
+ placeholder="Examples:\n- Schedule a meeting with Alex next week\n- Find a good time to meet with Taylor\n- Set up a 30 minute call with Morgan tomorrow"
78
  )
79
 
80
+ # Process the command
81
  if st.button("Process"):
82
  if not command:
83
  st.warning("Please enter a command first.")
84
  return
85
 
86
  with st.spinner("Processing your request..."):
87
+ result = agent.process_command(command)
 
88
 
89
+ # Display results based on status
90
+ if result["status"] == "created":
91
+ st.success(result["message"])
92
+ st.markdown(f"[View in Calendar]({result['event_link']})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ # Show alternatives if available
95
+ if "alternatives" in result and result["alternatives"]:
96
+ st.markdown("**Alternative times that would also work:**")
97
+ for i, alt in enumerate(result["alternatives"]):
98
+ if isinstance(alt, dict) and 'start' in alt:
99
+ start_dt = datetime.fromisoformat(alt['start'].replace('Z', '+00:00'))
100
+ st.write(f"{i+1}. {start_dt.strftime('%A, %b %d at %I:%M %p')}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ elif result["status"] == "rescheduled":
103
+ st.warning(result["message"])
104
+ st.markdown(f"[View in Calendar]({result['event_link']})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ elif result["status"] == "suggestions":
107
+ st.info(result["message"])
108
+ for i, slot in enumerate(result["slots"]):
109
+ st.write(f"{i+1}. {slot}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  else:
112
+ st.error(result["message"])
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  except Exception as e:
115
  st.error(f"Error: {str(e)}")
 
117
  st.session_state['authenticated'] = False
118
  st.rerun()
119
 
120
+ # Main app logic
121
  if 'authenticated' not in st.session_state:
122
  st.session_state['authenticated'] = False
123
 
124
+ # Add logout button in sidebar
125
  if st.session_state['authenticated']:
126
  if st.sidebar.button("Logout"):
127
  st.session_state['authenticated'] = False
 
129
  del st.session_state['user_token']
130
  st.rerun()
131
 
132
+ # Show appropriate page
133
  if st.session_state['authenticated']:
134
  agent_page()
135
  else: