Alakbarli commited on
Commit
eedaae8
·
verified ·
1 Parent(s): 38c20a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -254
app.py CHANGED
@@ -3,12 +3,12 @@ import os.path
3
  import os
4
  import time
5
  import base64
6
- import openai
7
  import re
8
  import datetime
9
  import json
10
- from datetime import date, timedelta
11
  import pytz
 
12
 
13
  from google.auth.transport.requests import Request
14
  from google.oauth2.credentials import Credentials
@@ -16,26 +16,22 @@ from google_auth_oauthlib.flow import InstalledAppFlow
16
  from googleapiclient.discovery import build
17
  from googleapiclient.errors import HttpError
18
 
 
19
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
20
 
21
- # --- CONFIGURATION FROM SECRETS (Hugging Face) ---
22
- # Pulling from Settings > Variables and secrets
23
- OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
24
  GCP_CREDENTIALS_STR = os.environ.get("GCP_CREDENTIALS")
25
-
26
- CHATGPT_MODEL = "openai/gpt-oss-20b:free"
27
- OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1'
28
-
29
- # We still use this for the session, but HF might delete it on restart
30
  TOKEN_FILE = "token.json"
31
  TIMEZONES = pytz.common_timezones
32
 
33
- GMAIL_SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
34
- CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.events']
35
- ALL_SCOPES = GMAIL_SCOPES + CALENDAR_SCOPES
36
 
37
  # --- LLM Client Initialization ---
38
- client = None
39
  if OPENROUTER_API_KEY:
40
  try:
41
  client = openai.OpenAI(
@@ -46,22 +42,21 @@ if OPENROUTER_API_KEY:
46
  except Exception as e:
47
  st.error(f"❌ Error during LLM client initialization: {e}")
48
 
49
-
50
  def authenticate_service():
51
- # 1. ONLY check the current user's session memory
52
- # if 'google_creds' in st.session_state:
53
- # return st.session_state.google_creds
54
 
55
- # If we are calling from the Telegram Bot, it will pass creds directly
56
- if bot_creds:
57
- return bot_creds
58
 
59
- # 2. If no session memory, we MUST log in (No more token.json check)
60
  client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
61
  redirect_uri = "https://alakbarli-assistant.hf.space/"
62
-
63
  flow = InstalledAppFlow.from_client_config(
64
- client_config,
65
  scopes=ALL_SCOPES,
66
  redirect_uri=redirect_uri
67
  )
@@ -70,10 +65,7 @@ def authenticate_service():
70
  if "code" in query_params:
71
  flow.fetch_token(code=query_params["code"])
72
  creds = flow.credentials
73
-
74
- # 3. Store ONLY in session state (this is unique to each visitor)
75
  st.session_state.google_creds = creds
76
-
77
  st.query_params.clear()
78
  st.rerun()
79
  else:
@@ -81,11 +73,10 @@ def authenticate_service():
81
  st.info("⚠️ Please sign in to your Google Account.")
82
  st.link_button("🔑 Login with Google", auth_url)
83
  return None
84
-
85
- return st.session_state.google_creds
86
-
87
 
 
88
 
 
89
  def normalize_event_json(event_data):
90
  """Ensures JSON from AI or Google uses the same keys."""
91
  return {
@@ -98,14 +89,11 @@ def normalize_event_json(event_data):
98
  'description': event_data.get('description', '')
99
  }
100
 
101
-
102
-
103
-
104
  def create_calendar_event(creds, event_json, user_timezone_str, create_meet=False):
105
  try:
106
  service = build('calendar', 'v3', credentials=creds)
107
  attendees_list = [{'email': e.strip()} for e in event_json.get('attendees', []) if '@' in e]
108
-
109
  event = {
110
  'summary': event_json.get('title', 'Untitled Event'),
111
  'location': event_json.get('location', ''),
@@ -115,7 +103,6 @@ def create_calendar_event(creds, event_json, user_timezone_str, create_meet=Fals
115
  'attendees': attendees_list,
116
  }
117
 
118
- # If meet is requested, add the conference configuration
119
  if create_meet:
120
  event['conferenceData'] = {
121
  'createRequest': {
@@ -124,30 +111,25 @@ def create_calendar_event(creds, event_json, user_timezone_str, create_meet=Fals
124
  }
125
  }
126
 
127
- # CRITICAL: conferenceDataVersion=1 is required to generate the link
128
  res = service.events().insert(
129
- calendarId='primary',
130
- body=event,
131
  conferenceDataVersion=1
132
  ).execute()
133
-
134
  meet_link = res.get('hangoutLink', '')
135
  success_msg = f"✅ Event **'{res.get('summary')}'** created!"
136
  if meet_link:
137
  success_msg += f"\n\n🔗 **Google Meet Link:** {meet_link}"
138
-
139
  return success_msg
140
  except Exception as e:
141
  return f"❌ Error: {str(e)}"
142
 
143
-
144
-
145
-
146
  def update_calendar_event(creds, event_id, updated_json, user_timezone_str, create_meet=False):
147
  try:
148
  service = build('calendar', 'v3', credentials=creds)
149
  attendees_list = [{'email': e.strip()} for e in updated_json.get('attendees', []) if '@' in e]
150
-
151
  body = {
152
  'summary': updated_json.get('title'),
153
  'location': updated_json.get('location'),
@@ -157,7 +139,6 @@ def update_calendar_event(creds, event_id, updated_json, user_timezone_str, crea
157
  'attendees': attendees_list,
158
  }
159
 
160
- # If user wants an online meeting, add conference data
161
  if create_meet:
162
  body['conferenceData'] = {
163
  'createRequest': {
@@ -166,30 +147,23 @@ def update_calendar_event(creds, event_id, updated_json, user_timezone_str, crea
166
  }
167
  }
168
  else:
169
- # If specifically switching to offline, we remove the link
170
- body['conferenceData'] = None
171
 
172
  res = service.events().patch(
173
- calendarId='primary',
174
- eventId=event_id,
175
  body=body,
176
- conferenceDataVersion=1 # Required to modify/remove Meet links
177
  ).execute()
178
-
179
  meet_link = res.get('hangoutLink', '')
180
  success_msg = "✅ Event updated successfully!"
181
  if meet_link and create_meet:
182
  success_msg += f"\n\n🔗 **New Google Meet Link:** {meet_link}"
183
-
184
  return success_msg
185
  except Exception as e:
186
  return f"❌ Update failed: {str(e)}"
187
 
188
-
189
-
190
-
191
-
192
-
193
  def delete_calendar_event(creds, event_id):
194
  try:
195
  service = build('calendar', 'v3', credentials=creds)
@@ -198,104 +172,63 @@ def delete_calendar_event(creds, event_id):
198
  except Exception as e:
199
  return f"❌ Deletion failed: {str(e)}"
200
 
201
- # --- AGENT PARSERS ---
202
-
203
- def parse_schedule_prompt(prompt, current_date, user_timezone_str):
204
- global client
205
- tz = pytz.timezone(user_timezone_str)
206
- now_aware = datetime.datetime.now(tz)
207
- offset = now_aware.strftime('%z')
208
- offset = f"{offset[:3]}:{offset[3:]}" if offset else "+00:00"
209
- system_prompt = f"You are a scheduling assistant. Return ONLY JSON. Date: {current_date}. TZ: {user_timezone_str}. Keys: title, start_time, end_time, location, attendees, description."
210
  try:
211
- resp = client.chat.completions.create(
212
- model=CHATGPT_MODEL,
213
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}],
214
- temperature=0.1
215
- )
216
- return resp.choices[0].message.content.strip().strip("```json").strip("```")
217
- except Exception as e: return json.dumps({"error": str(e)})
218
-
219
-
220
- def get_change_summary(old_event, new_event):
221
- changes = []
222
- fields_to_check = {
223
- 'title': 'Title',
224
- 'start_time': 'Start Time',
225
- 'end_time': 'End Time',
226
- 'location': 'Location',
227
- 'description': 'Description'
228
- }
229
-
230
- for key, label in fields_to_check.items():
231
- old_val = str(old_event.get(key, '')).strip()
232
- new_val = str(new_event.get(key, '')).strip()
233
- if old_val != new_val:
234
- changes.append(f"{label} (from '{old_val}' to '{new_val}')")
235
-
236
- return ", ".join(changes) if changes else "General updates"
237
-
238
-
239
- def draft_specific_notification(event_json, change_summary, is_new_invite=False):
240
- global client
241
- if not client: return "LLM client not configured."
242
-
243
- # Specific instructions for the professional "Change-First" format
244
- system_prompt = (
245
- "You are a professional corporate coordinator. "
246
- "When an event is updated, your email MUST follow this structure:\n"
247
- "1. A clear subject line.\n"
248
- "2. An opening sentence that IMMEDIATELY highlights the specific changes mentioned.\n"
249
- "3. A concise summary table or list of ALL current event details (Time, Location, etc.) "
250
- "to ensure everyone has the latest information."
251
- )
252
-
253
- if is_new_invite:
254
- user_content = f"Write a warm invitation for a NEW attendee to: {event_json.get('title')}."
255
- else:
256
- user_content = (
257
- f"The event '{event_json.get('title')}' has been updated. "
258
- f"SPECIFIC CHANGES: {change_summary}. "
259
- f"FULL CURRENT DETAILS: Time: {event_json.get('start_time')}, "
260
- f"Location: {event_json.get('location')}, Description: {event_json.get('description')}."
261
- )
262
 
 
263
  try:
264
- res = client.chat.completions.create(
265
- model=CHATGPT_MODEL,
266
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}]
267
- )
268
- return res.choices[0].message.content.strip()
269
- except Exception as e:
270
- return f"Error drafting: {e}"
271
-
272
 
 
 
 
 
 
 
 
273
 
274
- def parse_modification_prompt(original_event, mod_request, current_date, user_timezone_str):
275
- global client
276
- system_prompt = f"Update the following JSON based on user request. Maintain ISO 8601. Date: {current_date}. Return ONLY JSON."
277
- user_input = f"EXISTING: {json.dumps(original_event)}\nREQUEST: {mod_request}"
278
- try:
279
- resp = client.chat.completions.create(
280
- model=CHATGPT_MODEL,
281
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}],
282
- temperature=0.1
283
- )
284
- return resp.choices[0].message.content.strip().strip("```json").strip("```")
285
- except Exception as e: return json.dumps({"error": str(e)})
286
 
 
287
  def fetch_unread_emails(service):
288
- structured_emails = []
289
  try:
290
  results = service.users().messages().list(userId="me", maxResults=5, q="is:unread").execute()
291
  for m_info in results.get("messages", []):
292
  msg = service.users().messages().get(userId='me', id=m_info['id']).execute()
293
  headers = {h['name']: h['value'] for h in msg['payload']['headers']}
294
-
295
- # --- IMPROVED BODY EXTRACTION ---
296
  body = ""
297
  payload = msg.get('payload', {})
298
-
299
  def get_body(parts):
300
  for part in parts:
301
  mimeType = part.get('mimeType')
@@ -313,158 +246,95 @@ def fetch_unread_emails(service):
313
  data = payload.get('body', {}).get('data')
314
  if data:
315
  body = base64.urlsafe_b64decode(data).decode('utf-8')
316
- # -------------------------------
317
 
318
  structured_emails.append({
319
- 'id': msg['id'],
320
  'time': time.strftime('%Y-%m-%d %I:%M %p', time.localtime(int(msg['internalDate'])/1000)),
321
- 'from': headers.get('From', 'N/A'),
322
  'subject': headers.get('Subject', 'N/A'),
323
  'body': body if body else "No readable text found",
324
  'summary': ''
325
  })
326
  return structured_emails
327
- except Exception as e:
328
  st.error(f"Error fetching emails: {e}")
329
  return []
330
-
331
-
332
 
333
-
334
- def get_conflicting_events(creds, start_iso, end_iso, exclude_id=None):
335
- """Checks if any events exist between the proposed times, excluding a specific ID."""
 
 
336
  try:
337
- service = build('calendar', 'v3', credentials=creds)
338
- results = service.events().list(
339
- calendarId='primary',
340
- timeMin=start_iso,
341
- timeMax=end_iso,
342
- singleEvents=True,
343
- orderBy='startTime'
344
- ).execute()
345
- events = results.get('items', [])
346
- # Filter out the event we are currently modifying
347
- if exclude_id:
348
- events = [e for e in events if e.get('id') != exclude_id]
349
- return events
350
- except Exception as e:
351
- st.error(f"Error checking conflicts: {e}")
352
- return []
353
-
354
 
355
- def fetch_upcoming_events(creds, start_date=None, end_date=None):
 
 
356
  try:
357
- service = build('calendar', 'v3', credentials=creds)
358
- time_min = start_date.isoformat() + 'Z' if start_date else datetime.datetime.utcnow().isoformat() + 'Z'
359
- time_max = end_date.isoformat() + 'Z' if end_date else None
360
-
361
- results = service.events().list(
362
- calendarId='primary',
363
- timeMin=time_min,
364
- timeMax=time_max,
365
- singleEvents=True,
366
- orderBy='startTime'
367
- ).execute()
368
-
369
- events = results.get('items', [])
370
- return [{
371
- 'id': e['id'],
372
- 'summary': e.get('summary', 'No Title'),
373
- 'start': e['start'].get('dateTime', e['start'].get('date')),
374
- 'end': e['end'].get('dateTime', e['end'].get('date')),
375
- 'attendees': [a.get('email') for a in e.get('attendees', [])],
376
- 'location': e.get('location', 'N/A')
377
- } for e in events]
378
- except Exception as e:
379
- st.error(f"Error fetching: {e}")
380
- return []
381
-
382
 
383
  def summarize_email(email_text, email_from, email_subject):
384
- global client
385
  if not client:
386
  return "• ⚠️ Summary failed: LLM client is not configured."
387
-
388
  match = re.search(r'^(.*?) <', email_from)
389
  sender_name = match.group(1).strip() if match else email_from.split('<')[0].strip()
390
-
391
- system_prompt = (
392
- "You are an AI assistant specialized in converting long emails "
393
- "into a single, concise, and actionable bullet point. The summary "
394
- "must be less than 15 words and **MUST begin with the sender's simple name** "
395
- "followed by the action. The entire summary MUST start with a bullet point ('•'). "
396
- "Example format: • Fatima asks for a review of the policy draft."
397
- )
398
- user_input = f"Summarize the following email into one actionable bullet point, starting with the sender's name:\nSender's Name: {sender_name}\nFrom: {email_from}\nSubject: {email_subject}\n---\nBody:\n{email_text}"
399
-
400
- messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}]
401
 
402
  try:
403
  response = client.chat.completions.create(
404
- model=CHATGPT_MODEL, messages=messages, temperature=0.3
 
 
405
  )
406
  summary = response.choices[0].message.content.strip()
407
  return summary if summary.startswith('•') else '• ' + summary
408
  except Exception as e:
409
- error_message = str(e)
410
- return f"• Error during summarization: {error_message[:50]}..."
411
-
412
- def draft_event_notification(event_json, change_type, target_email=None):
413
- """
414
- Drafts an email based on calendar changes.
415
- change_type: 'reschedule', 'location_change', 'new_invite', 'cancel'
416
- """
417
- global client
418
- if not client:
419
- return "LLM client not configured."
420
 
421
- system_prompt = "You are a professional assistant. Draft a short, clear email notification about a calendar event update."
422
-
423
- context = f"""
424
- Event Title: {event_json.get('title')}
425
- Time: {event_json.get('start_time')}
426
- Location: {event_json.get('location')}
427
- Description: {event_json.get('description')}
428
- Change Type: {change_type}
429
- """
430
 
431
- if change_type == "new_invite":
432
- user_input = f"Draft an invitation email to a new attendee for this event: {context}"
433
  else:
434
- user_input = f"Draft an update email to all attendees explaining the {change_type} for this event: {context}"
435
 
436
  try:
437
  res = client.chat.completions.create(
438
- model=CHATGPT_MODEL,
439
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}]
440
  )
441
  return res.choices[0].message.content.strip()
442
  except Exception as e:
443
- return f"Error drafting notification: {e}"
444
-
445
-
446
-
447
- def find_email_by_sender(email_list, sender_name):
448
- for e in email_list:
449
- if sender_name.lower() in e['from'].lower(): return e
450
- return None
451
-
452
- def draft_reply_email(subject, body, summary):
453
- global client
454
- sys = "Draft a professional short reply."
455
- usr = f"Summary: {summary}\nSubject: {subject}\nBody: {body}"
456
- try:
457
- res = client.chat.completions.create(model=CHATGPT_MODEL, messages=[{"role":"system","content":sys},{"role":"user","content":usr}])
458
- return res.choices[0].message.content.strip()
459
- except: return "Draft error"
460
-
461
- # --- HELPER: WINDOW NAVIGATION ---
462
 
 
463
  def render_window_controls():
 
 
 
464
  start_dt = st.session_state.calendar_window_start
465
  end_dt = start_dt + timedelta(days=90)
466
  st.write(f"📅 Window: **{start_dt.strftime('%b %Y')}** — **{end_dt.strftime('%b %Y')}**")
467
-
468
  col_prev, col_next = st.columns(2)
469
  if col_next.button("➡️ Next 3 Months", use_container_width=True):
470
  st.session_state.calendar_window_start = end_dt
@@ -477,8 +347,6 @@ def render_window_controls():
477
 
478
 
479
 
480
-
481
-
482
  # --- MAIN APP ---
483
 
484
  def main():
 
3
  import os
4
  import time
5
  import base64
6
+ import openai
7
  import re
8
  import datetime
9
  import json
 
10
  import pytz
11
+ from datetime import date, timedelta
12
 
13
  from google.auth.transport.requests import Request
14
  from google.oauth2.credentials import Credentials
 
16
  from googleapiclient.discovery import build
17
  from googleapiclient.errors import HttpError
18
 
19
+ # --- CONFIGURATION ---
20
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
21
 
22
+ OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
 
 
23
  GCP_CREDENTIALS_STR = os.environ.get("GCP_CREDENTIALS")
24
+ CHATGPT_MODEL = "openai/gpt-oss-20b:free"
25
+ OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1'
 
 
 
26
  TOKEN_FILE = "token.json"
27
  TIMEZONES = pytz.common_timezones
28
 
29
+ GMAIL_SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
30
+ CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.events']
31
+ ALL_SCOPES = GMAIL_SCOPES + CALENDAR_SCOPES
32
 
33
  # --- LLM Client Initialization ---
34
+ client = None
35
  if OPENROUTER_API_KEY:
36
  try:
37
  client = openai.OpenAI(
 
42
  except Exception as e:
43
  st.error(f"❌ Error during LLM client initialization: {e}")
44
 
45
+ # --- AUTHENTICATION ---
46
  def authenticate_service():
47
+ """Handles Google OAuth2 flow using Streamlit session state."""
48
+ if 'google_creds' in st.session_state:
49
+ return st.session_state.google_creds
50
 
51
+ if not os.environ.get("GCP_CREDENTIALS"):
52
+ st.error("GCP_CREDENTIALS secret is missing!")
53
+ return None
54
 
 
55
  client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
56
  redirect_uri = "https://alakbarli-assistant.hf.space/"
57
+
58
  flow = InstalledAppFlow.from_client_config(
59
+ client_config,
60
  scopes=ALL_SCOPES,
61
  redirect_uri=redirect_uri
62
  )
 
65
  if "code" in query_params:
66
  flow.fetch_token(code=query_params["code"])
67
  creds = flow.credentials
 
 
68
  st.session_state.google_creds = creds
 
69
  st.query_params.clear()
70
  st.rerun()
71
  else:
 
73
  st.info("⚠️ Please sign in to your Google Account.")
74
  st.link_button("🔑 Login with Google", auth_url)
75
  return None
 
 
 
76
 
77
+ return st.session_state.google_creds
78
 
79
+ # --- CALENDAR OPERATIONS ---
80
  def normalize_event_json(event_data):
81
  """Ensures JSON from AI or Google uses the same keys."""
82
  return {
 
89
  'description': event_data.get('description', '')
90
  }
91
 
 
 
 
92
  def create_calendar_event(creds, event_json, user_timezone_str, create_meet=False):
93
  try:
94
  service = build('calendar', 'v3', credentials=creds)
95
  attendees_list = [{'email': e.strip()} for e in event_json.get('attendees', []) if '@' in e]
96
+
97
  event = {
98
  'summary': event_json.get('title', 'Untitled Event'),
99
  'location': event_json.get('location', ''),
 
103
  'attendees': attendees_list,
104
  }
105
 
 
106
  if create_meet:
107
  event['conferenceData'] = {
108
  'createRequest': {
 
111
  }
112
  }
113
 
 
114
  res = service.events().insert(
115
+ calendarId='primary',
116
+ body=event,
117
  conferenceDataVersion=1
118
  ).execute()
119
+
120
  meet_link = res.get('hangoutLink', '')
121
  success_msg = f"✅ Event **'{res.get('summary')}'** created!"
122
  if meet_link:
123
  success_msg += f"\n\n🔗 **Google Meet Link:** {meet_link}"
 
124
  return success_msg
125
  except Exception as e:
126
  return f"❌ Error: {str(e)}"
127
 
 
 
 
128
  def update_calendar_event(creds, event_id, updated_json, user_timezone_str, create_meet=False):
129
  try:
130
  service = build('calendar', 'v3', credentials=creds)
131
  attendees_list = [{'email': e.strip()} for e in updated_json.get('attendees', []) if '@' in e]
132
+
133
  body = {
134
  'summary': updated_json.get('title'),
135
  'location': updated_json.get('location'),
 
139
  'attendees': attendees_list,
140
  }
141
 
 
142
  if create_meet:
143
  body['conferenceData'] = {
144
  'createRequest': {
 
147
  }
148
  }
149
  else:
150
+ body['conferenceData'] = None
 
151
 
152
  res = service.events().patch(
153
+ calendarId='primary',
154
+ eventId=event_id,
155
  body=body,
156
+ conferenceDataVersion=1
157
  ).execute()
158
+
159
  meet_link = res.get('hangoutLink', '')
160
  success_msg = "✅ Event updated successfully!"
161
  if meet_link and create_meet:
162
  success_msg += f"\n\n🔗 **New Google Meet Link:** {meet_link}"
 
163
  return success_msg
164
  except Exception as e:
165
  return f"❌ Update failed: {str(e)}"
166
 
 
 
 
 
 
167
  def delete_calendar_event(creds, event_id):
168
  try:
169
  service = build('calendar', 'v3', credentials=creds)
 
172
  except Exception as e:
173
  return f"❌ Deletion failed: {str(e)}"
174
 
175
+ def get_conflicting_events(creds, start_iso, end_iso, exclude_id=None):
 
 
 
 
 
 
 
 
176
  try:
177
+ service = build('calendar', 'v3', credentials=creds)
178
+ results = service.events().list(
179
+ calendarId='primary',
180
+ timeMin=start_iso,
181
+ timeMax=end_iso,
182
+ singleEvents=True,
183
+ orderBy='startTime'
184
+ ).execute()
185
+ events = results.get('items', [])
186
+ if exclude_id:
187
+ events = [e for e in events if e.get('id') != exclude_id]
188
+ return events
189
+ except Exception as e:
190
+ st.error(f"Error checking conflicts: {e}")
191
+ return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ def fetch_upcoming_events(creds, start_date=None, end_date=None):
194
  try:
195
+ service = build('calendar', 'v3', credentials=creds)
196
+ time_min = start_date.isoformat() + 'Z' if start_date else datetime.datetime.utcnow().isoformat() + 'Z'
197
+ time_max = end_date.isoformat() + 'Z' if end_date else None
 
 
 
 
 
198
 
199
+ results = service.events().list(
200
+ calendarId='primary',
201
+ timeMin=time_min,
202
+ timeMax=time_max,
203
+ singleEvents=True,
204
+ orderBy='startTime'
205
+ ).execute()
206
 
207
+ events = results.get('items', [])
208
+ return [{
209
+ 'id': e['id'],
210
+ 'summary': e.get('summary', 'No Title'),
211
+ 'start': e['start'].get('dateTime', e['start'].get('date')),
212
+ 'end': e['end'].get('dateTime', e['end'].get('date')),
213
+ 'attendees': [a.get('email') for a in e.get('attendees', [])],
214
+ 'location': e.get('location', 'N/A')
215
+ } for e in events]
216
+ except Exception as e:
217
+ st.error(f"Error fetching: {e}")
218
+ return []
219
 
220
+ # --- GMAIL OPERATIONS ---
221
  def fetch_unread_emails(service):
222
+ structured_emails = []
223
  try:
224
  results = service.users().messages().list(userId="me", maxResults=5, q="is:unread").execute()
225
  for m_info in results.get("messages", []):
226
  msg = service.users().messages().get(userId='me', id=m_info['id']).execute()
227
  headers = {h['name']: h['value'] for h in msg['payload']['headers']}
228
+
 
229
  body = ""
230
  payload = msg.get('payload', {})
231
+
232
  def get_body(parts):
233
  for part in parts:
234
  mimeType = part.get('mimeType')
 
246
  data = payload.get('body', {}).get('data')
247
  if data:
248
  body = base64.urlsafe_b64decode(data).decode('utf-8')
 
249
 
250
  structured_emails.append({
251
+ 'id': msg['id'],
252
  'time': time.strftime('%Y-%m-%d %I:%M %p', time.localtime(int(msg['internalDate'])/1000)),
253
+ 'from': headers.get('From', 'N/A'),
254
  'subject': headers.get('Subject', 'N/A'),
255
  'body': body if body else "No readable text found",
256
  'summary': ''
257
  })
258
  return structured_emails
259
+ except Exception as e:
260
  st.error(f"Error fetching emails: {e}")
261
  return []
 
 
262
 
263
+ # --- AI AGENT PARSERS ---
264
+ def parse_schedule_prompt(prompt, current_date, user_timezone_str):
265
+ tz = pytz.timezone(user_timezone_str)
266
+ now_aware = datetime.datetime.now(tz)
267
+ system_prompt = f"You are a scheduling assistant. Return ONLY JSON. Date: {current_date}. TZ: {user_timezone_str}. Keys: title, start_time, end_time, location, attendees, description."
268
  try:
269
+ resp = client.chat.completions.create(
270
+ model=CHATGPT_MODEL,
271
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}],
272
+ temperature=0.1
273
+ )
274
+ return resp.choices[0].message.content.strip().strip("```json").strip("```")
275
+ except Exception as e:
276
+ return json.dumps({"error": str(e)})
 
 
 
 
 
 
 
 
 
277
 
278
+ def parse_modification_prompt(original_event, mod_request, current_date, user_timezone_str):
279
+ system_prompt = f"Update the following JSON based on user request. Maintain ISO 8601. Date: {current_date}. Return ONLY JSON."
280
+ user_input = f"EXISTING: {json.dumps(original_event)}\nREQUEST: {mod_request}"
281
  try:
282
+ resp = client.chat.completions.create(
283
+ model=CHATGPT_MODEL,
284
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}],
285
+ temperature=0.1
286
+ )
287
+ return resp.choices[0].message.content.strip().strip("```json").strip("```")
288
+ except Exception as e:
289
+ return json.dumps({"error": str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  def summarize_email(email_text, email_from, email_subject):
 
292
  if not client:
293
  return "• ⚠️ Summary failed: LLM client is not configured."
294
+
295
  match = re.search(r'^(.*?) <', email_from)
296
  sender_name = match.group(1).strip() if match else email_from.split('<')[0].strip()
297
+ system_prompt = "You are an AI assistant. Summarize into one concise bullet point (<15 words) starting with the sender's name."
298
+ user_input = f"Sender: {sender_name}\nSubject: {email_subject}\nBody: {email_text}"
 
 
 
 
 
 
 
 
 
299
 
300
  try:
301
  response = client.chat.completions.create(
302
+ model=CHATGPT_MODEL,
303
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}],
304
+ temperature=0.3
305
  )
306
  summary = response.choices[0].message.content.strip()
307
  return summary if summary.startswith('•') else '• ' + summary
308
  except Exception as e:
309
+ return f"• Error during summarization: {str(e)[:50]}..."
 
 
 
 
 
 
 
 
 
 
310
 
311
+ def draft_specific_notification(event_json, change_summary, is_new_invite=False):
312
+ if not client: return "LLM client not configured."
313
+ system_prompt = "You are a professional corporate coordinator. Draft a change-first email."
 
 
 
 
 
 
314
 
315
+ if is_new_invite:
316
+ user_content = f"Write a warm invitation for a NEW attendee to: {event_json.get('title')}."
317
  else:
318
+ user_content = f"Event '{event_json.get('title')}' updated. Changes: {change_summary}."
319
 
320
  try:
321
  res = client.chat.completions.create(
322
+ model=CHATGPT_MODEL,
323
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}]
324
  )
325
  return res.choices[0].message.content.strip()
326
  except Exception as e:
327
+ return f"Error drafting: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
329
+ # --- NAVIGATION HELPER ---
330
  def render_window_controls():
331
+ if 'calendar_window_start' not in st.session_state:
332
+ st.session_state.calendar_window_start = datetime.datetime.utcnow()
333
+
334
  start_dt = st.session_state.calendar_window_start
335
  end_dt = start_dt + timedelta(days=90)
336
  st.write(f"📅 Window: **{start_dt.strftime('%b %Y')}** — **{end_dt.strftime('%b %Y')}**")
337
+
338
  col_prev, col_next = st.columns(2)
339
  if col_next.button("➡️ Next 3 Months", use_container_width=True):
340
  st.session_state.calendar_window_start = end_dt
 
347
 
348
 
349
 
 
 
350
  # --- MAIN APP ---
351
 
352
  def main():