awacke1 commited on
Commit
dbf031b
Β·
verified Β·
1 Parent(s): 23945b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -71
app.py CHANGED
@@ -11,49 +11,120 @@ CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY')
11
  AUTHORITY_URL = 'https://login.microsoftonline.com/common'
12
  REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI'
13
 
14
- # Define product to scope mapping and links
15
  PRODUCT_SCOPES = {
16
- "πŸ“§ Outlook": ['Mail.Read', 'Mail.Send', 'Calendars.ReadWrite'],
17
- "πŸ“’ OneNote": ['Notes.Read', 'Notes.Create'],
18
- "πŸ“Š Excel": ['Files.ReadWrite.All'],
19
- "πŸ“„ Word": ['Files.ReadWrite.All'],
20
- "πŸ—ƒοΈ SharePoint": ['Sites.Read.All', 'Sites.ReadWrite.All'],
21
- "πŸ“… Teams": ['Team.ReadBasic.All', 'Channel.ReadBasic.All'],
22
- "πŸ’¬ Viva": ['Analytics.Read'],
23
- "πŸš€ Power Platform": ['Flow.Read.All'],
24
- "🧠 Copilot": ['Cognitive.Read'],
25
- "πŸ—‚οΈ OneDrive": ['Files.ReadWrite.All'],
26
- "πŸ’‘ PowerPoint": ['Files.ReadWrite.All'],
27
- "πŸ“š Microsoft Bookings": ['Bookings.Read.All', 'Bookings.ReadWrite.All'],
28
- "πŸ““ Loop": ['Files.ReadWrite.All'],
29
- "πŸ—£οΈ Translator": ['Translation.Read'],
30
- "πŸ“‹ To Do & Planner": ['Tasks.ReadWrite'],
31
- "πŸ”— Azure OpenAI Service": ['AzureAIServices.ReadWrite.All']
32
- }
33
-
34
- # Add links to the products dictionary
35
- products = {
36
  "πŸ“§ Outlook": {
37
- "ai_capabilities": "Copilot for enhanced email writing, calendar management, and scheduling.",
38
- "graph_api": "Access to mail, calendar, contacts, and events.",
39
- "link": "https://outlook.office.com/mail/"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  },
41
  "πŸ“’ OneNote": {
42
- "ai_capabilities": "Content suggestion, note organization, and OCR for extracting text from images.",
43
- "graph_api": "Manage notebooks, sections, and pages.",
44
- "link": "https://www.onenote.com/"
 
45
  },
46
  "πŸ“Š Excel": {
47
- "ai_capabilities": "Copilot for advanced data analysis, data insights, and formula generation.",
48
- "graph_api": "Create and manage worksheets, tables, charts, and workbooks.",
49
- "link": "https://www.office.com/excel"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  },
51
- # Add links for other products as needed...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  }
53
 
54
  BASE_SCOPES = ['User.Read']
55
 
56
- # MSAL App Instance
57
  def get_msal_app():
58
  return msal.ConfidentialClientApplication(
59
  client_id=APPLICATION_ID_KEY,
@@ -61,7 +132,6 @@ def get_msal_app():
61
  authority=AUTHORITY_URL
62
  )
63
 
64
- # Get Access Token
65
  def get_access_token(code):
66
  client_instance = get_msal_app()
67
  try:
@@ -78,7 +148,6 @@ def get_access_token(code):
78
  st.error(f"Exception in get_access_token: {str(e)}")
79
  raise
80
 
81
- # Make API call
82
  def make_api_call(access_token, endpoint, method='GET', data=None):
83
  headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
84
  url = f'https://graph.microsoft.com/v1.0/{endpoint}'
@@ -96,10 +165,10 @@ def make_api_call(access_token, endpoint, method='GET', data=None):
96
  st.error(f"API call failed: {response.status_code} - {response.text}")
97
  return None
98
 
99
- # Define product integration handlers
100
  def handle_outlook_integration(access_token):
101
  st.subheader("πŸ“§ Outlook Integration")
102
- st.markdown(f"[Open Outlook]({products['πŸ“§ Outlook']['link']})") # Use products dictionary for link
 
103
  emails = make_api_call(access_token, 'me/messages?$top=10&$orderby=receivedDateTime desc')
104
  if emails and 'value' in emails:
105
  for email in emails['value']:
@@ -109,44 +178,142 @@ def handle_outlook_integration(access_token):
109
  else:
110
  st.write("No emails found or unable to fetch emails.")
111
 
112
- # More handlers for other products like Calendar, OneDrive, etc., go here...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- # Main Function
115
  def main():
116
  st.title("πŸ¦„ MS Graph API with AI & Cloud Integration for M365")
117
-
118
- # Sidebar product selection
119
  st.sidebar.title("πŸ“ M365 Products")
120
  st.sidebar.write("Select products to integrate:")
121
 
122
  selected_products = {}
123
- for product, info in products.items():
124
  selected = st.sidebar.checkbox(product)
125
  if selected:
126
  selected_products[product] = True
127
- st.sidebar.write(f"**AI Capabilities:** {info['ai_capabilities']}")
128
- st.sidebar.write(f"**Graph API:** {info['graph_api']}")
129
 
130
- # Request scopes based on selected products
131
  request_scopes = BASE_SCOPES.copy()
132
  for product in selected_products:
133
- request_scopes.extend(PRODUCT_SCOPES[product])
134
- request_scopes = list(set(request_scopes)) # Remove duplicates
 
135
  st.session_state['request_scopes'] = request_scopes
136
 
137
- # MSAL login and token handling
138
  if 'access_token' not in st.session_state:
139
  client_instance = get_msal_app()
140
  auth_url = client_instance.get_authorization_request_url(
141
  scopes=request_scopes,
142
  redirect_uri=REDIRECT_URI
143
  )
144
- st.write(f'πŸ‘‹ Please [click here]({auth_url}) to log in and authorize the app.')
145
 
146
  query_params = st.query_params
147
  if 'code' in query_params:
148
  code = query_params.get('code')
149
- st.write(f'πŸ”‘ Authorization Code Obtained: {code[:10]}...')
150
 
151
  try:
152
  access_token = get_access_token(code)
@@ -164,33 +331,19 @@ def main():
164
  st.sidebar.write(f"πŸ‘‹ Hello, {user_info.get('displayName', 'User')}!")
165
 
166
  if selected_products:
167
- # Integrate selected products
168
  for product in selected_products:
169
  if product == "πŸ“§ Outlook":
170
  handle_outlook_integration(access_token)
171
- # Add other product integration handlers as needed
 
 
 
 
 
 
172
  else:
173
  st.write("No products selected. Please select products from the sidebar.")
174
 
175
- # Sidebar navigation menu with AI capabilities and Graph API descriptions
176
- st.sidebar.title("Navigation")
177
- menu = st.sidebar.radio("Go to", [
178
- "1️⃣ Dashboard",
179
- "🏠 Landing Page",
180
- "πŸ“… Upcoming Events",
181
- "πŸ“† Schedule",
182
- "πŸ“ Agenda",
183
- "πŸ” Event Details",
184
- "βž• Add Event",
185
- "πŸ”Ž Filter By"
186
- ])
187
-
188
- # Display AI Capabilities and Graph API Information for the selected menu
189
- if menu in selected_products:
190
- product_info = products.get(menu, None)
191
- if product_info:
192
- st.write(f"**AI Capabilities for {menu}:** {product_info['ai_capabilities']}")
193
- st.write(f"**Graph API for {menu}:** {product_info['graph_api']}")
194
-
195
  if __name__ == "__main__":
196
  main()
 
 
11
  AUTHORITY_URL = 'https://login.microsoftonline.com/common'
12
  REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI'
13
 
14
+ # Define product to scope mapping, links, AI capabilities, and Graph solutions
15
  PRODUCT_SCOPES = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  "πŸ“§ Outlook": {
17
+ 'scopes': ['Mail.Read', 'Mail.Send'],
18
+ 'link': 'https://outlook.office.com/mail/',
19
+ 'ai_capabilities': "πŸ€–βœοΈ Smart email & scheduling",
20
+ 'graph_solution': "πŸ“¨πŸ“… Mail, calendar & contacts API"
21
+ },
22
+ "πŸ“… Calendar": {
23
+ 'scopes': ['Calendars.ReadWrite'],
24
+ 'link': 'https://outlook.office.com/calendar/',
25
+ 'ai_capabilities': "πŸ€–πŸ“… Smart scheduling & reminders",
26
+ 'graph_solution': "πŸ“… Calendar management API"
27
+ },
28
+ "πŸ“‹ Tasks": {
29
+ 'scopes': ['Tasks.ReadWrite'],
30
+ 'link': 'https://to-do.office.com/tasks/',
31
+ 'ai_capabilities': "πŸ€–πŸ“ Task prioritization",
32
+ 'graph_solution': "βœ… Task management API"
33
+ },
34
+ "πŸ—‚οΈ OneDrive": {
35
+ 'scopes': ['Files.ReadWrite.All'],
36
+ 'link': 'https://onedrive.live.com/',
37
+ 'ai_capabilities': "πŸ€–πŸ” Smart file organization",
38
+ 'graph_solution': "πŸ“ File & folder API"
39
  },
40
  "πŸ“’ OneNote": {
41
+ 'scopes': ['Notes.Read', 'Notes.Create'],
42
+ 'link': 'https://www.onenote.com/notebooks',
43
+ 'ai_capabilities': "πŸ€–πŸ“ Content suggestion & OCR",
44
+ 'graph_solution': "πŸ“” Notebook & page API"
45
  },
46
  "πŸ“Š Excel": {
47
+ 'scopes': ['Files.ReadWrite.All'],
48
+ 'link': 'https://www.office.com/launch/excel',
49
+ 'ai_capabilities': "πŸ€–πŸ“ˆ Data analysis & insights",
50
+ 'graph_solution': "πŸ“Š Workbook & chart API"
51
+ },
52
+ "πŸ“„ Word": {
53
+ 'scopes': ['Files.ReadWrite.All'],
54
+ 'link': 'https://www.office.com/launch/word',
55
+ 'ai_capabilities': "πŸ€–βœοΈ Smart drafting & editing",
56
+ 'graph_solution': "πŸ“ Document content API"
57
+ },
58
+ "πŸ—ƒοΈ SharePoint": {
59
+ 'scopes': ['Sites.Read.All', 'Sites.ReadWrite.All'],
60
+ 'link': 'https://www.microsoft.com/microsoft-365/sharepoint/collaboration',
61
+ 'ai_capabilities': "πŸ€–πŸ” Smart search & tagging",
62
+ 'graph_solution': "🌐 Sites & lists API"
63
+ },
64
+ "πŸ“… Teams": {
65
+ 'scopes': ['Team.ReadBasic.All', 'Channel.ReadBasic.All'],
66
+ 'link': 'https://teams.microsoft.com/',
67
+ 'ai_capabilities': "πŸ€–πŸ’¬ Meeting insights & summaries",
68
+ 'graph_solution': "πŸ‘₯ Teams & chats API"
69
+ },
70
+ "πŸ’¬ Viva": {
71
+ 'scopes': ['Analytics.Read'],
72
+ 'link': 'https://www.microsoft.com/microsoft-viva',
73
+ 'ai_capabilities': "πŸ€–πŸ“Š Personalized insights",
74
+ 'graph_solution': "πŸ“ˆ Analytics & learning API"
75
+ },
76
+ "πŸš€ Power Platform": {
77
+ 'scopes': ['Flow.Read.All'],
78
+ 'link': 'https://powerplatform.microsoft.com/',
79
+ 'ai_capabilities': "πŸ€–βš™οΈ AI-powered automation",
80
+ 'graph_solution': "πŸ”§ Workflow & app API"
81
  },
82
+ "🧠 Copilot": {
83
+ 'scopes': ['Cognitive.Read'],
84
+ 'link': 'https://www.microsoft.com/microsoft-365/copilot',
85
+ 'ai_capabilities': "πŸ€–πŸš€ Cross-app AI assistance",
86
+ 'graph_solution': "🧠 AI integration API"
87
+ },
88
+ "πŸ’‘ PowerPoint": {
89
+ 'scopes': ['Files.ReadWrite.All'],
90
+ 'link': 'https://www.office.com/launch/powerpoint',
91
+ 'ai_capabilities': "πŸ€–πŸŽ¨ Design & coaching AI",
92
+ 'graph_solution': "πŸ“Š Presentation API"
93
+ },
94
+ "πŸ“š Microsoft Bookings": {
95
+ 'scopes': ['Bookings.Read.All', 'Bookings.ReadWrite.All'],
96
+ 'link': 'https://outlook.office.com/bookings/',
97
+ 'ai_capabilities': "πŸ€–πŸ“… Smart scheduling",
98
+ 'graph_solution': "πŸ“† Booking services API"
99
+ },
100
+ "πŸ““ Loop": {
101
+ 'scopes': ['Files.ReadWrite.All'],
102
+ 'link': 'https://loop.microsoft.com/',
103
+ 'ai_capabilities': "πŸ€–πŸ”„ Real-time collaboration AI",
104
+ 'graph_solution': "πŸ” Workspace API"
105
+ },
106
+ "πŸ—£οΈ Translator": {
107
+ 'scopes': ['Translation.Read'],
108
+ 'link': 'https://www.microsoft.com/translator/',
109
+ 'ai_capabilities': "πŸ€–πŸŒ Real-time translation",
110
+ 'graph_solution': "πŸ—¨οΈ Translation services API"
111
+ },
112
+ "πŸ“‹ To Do & Planner": {
113
+ 'scopes': ['Tasks.ReadWrite'],
114
+ 'link': 'https://todo.microsoft.com/',
115
+ 'ai_capabilities': "πŸ€–πŸ“ Smart task management",
116
+ 'graph_solution': "βœ… Task & plan API"
117
+ },
118
+ "πŸ”— Azure OpenAI Service": {
119
+ 'scopes': ['AzureAIServices.ReadWrite.All'],
120
+ 'link': 'https://azure.microsoft.com/products/cognitive-services/openai-service/',
121
+ 'ai_capabilities': "πŸ€–πŸ§  Custom AI model access",
122
+ 'graph_solution': "πŸ”Œ AI model integration API"
123
+ }
124
  }
125
 
126
  BASE_SCOPES = ['User.Read']
127
 
 
128
  def get_msal_app():
129
  return msal.ConfidentialClientApplication(
130
  client_id=APPLICATION_ID_KEY,
 
132
  authority=AUTHORITY_URL
133
  )
134
 
 
135
  def get_access_token(code):
136
  client_instance = get_msal_app()
137
  try:
 
148
  st.error(f"Exception in get_access_token: {str(e)}")
149
  raise
150
 
 
151
  def make_api_call(access_token, endpoint, method='GET', data=None):
152
  headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
153
  url = f'https://graph.microsoft.com/v1.0/{endpoint}'
 
165
  st.error(f"API call failed: {response.status_code} - {response.text}")
166
  return None
167
 
 
168
  def handle_outlook_integration(access_token):
169
  st.subheader("πŸ“§ Outlook Integration")
170
+ st.markdown(f"[Open Outlook]({PRODUCT_SCOPES['πŸ“§ Outlook']['link']})")
171
+
172
  emails = make_api_call(access_token, 'me/messages?$top=10&$orderby=receivedDateTime desc')
173
  if emails and 'value' in emails:
174
  for email in emails['value']:
 
178
  else:
179
  st.write("No emails found or unable to fetch emails.")
180
 
181
+ def handle_calendar_integration(access_token):
182
+ st.subheader("πŸ“… Calendar Integration")
183
+ st.markdown(f"[Open Calendar]({PRODUCT_SCOPES['πŸ“… Calendar']['link']})")
184
+
185
+ # Get the current month's start and end dates
186
+ now = datetime.now()
187
+ start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
188
+ end_of_month = start_of_month.replace(month=start_of_month.month % 12 + 1, day=1) - timedelta(days=1)
189
+
190
+ events = make_api_call(access_token, f"me/calendarView?startDateTime={start_of_month.isoformat()}&endDateTime={end_of_month.isoformat()}&$orderby=start/dateTime")
191
+
192
+ if events and 'value' in events:
193
+ # Create a calendar view
194
+ cal = calendar.monthcalendar(now.year, now.month)
195
+ st.write(f"Calendar for {now.strftime('%B %Y')}")
196
+
197
+ # Create a placeholder for each day
198
+ day_placeholders = {}
199
+ for week in cal:
200
+ cols = st.columns(7)
201
+ for i, day in enumerate(week):
202
+ if day != 0:
203
+ day_placeholders[day] = cols[i].empty()
204
+ day_placeholders[day].write(f"**{day}**")
205
+
206
+ # Populate the calendar with events
207
+ for event in events['value']:
208
+ start_date = datetime.fromisoformat(event['start']['dateTime'][:-1]) # Remove 'Z' from the end
209
+ day = start_date.day
210
+ if day in day_placeholders:
211
+ day_placeholders[day].write(f"{start_date.strftime('%H:%M')} - {event['subject']}")
212
+ else:
213
+ st.write("No events found or unable to fetch events.")
214
+
215
+ st.write("Add a new event:")
216
+ event_subject = st.text_input("Event Subject")
217
+ event_date = st.date_input("Event Date")
218
+ event_time = st.time_input("Event Time")
219
+ if st.button("Add Event"):
220
+ event_start = datetime.combine(event_date, event_time)
221
+ event_end = event_start + timedelta(hours=1)
222
+ new_event = {
223
+ "subject": event_subject,
224
+ "start": {
225
+ "dateTime": event_start.isoformat(),
226
+ "timeZone": "UTC"
227
+ },
228
+ "end": {
229
+ "dateTime": event_end.isoformat(),
230
+ "timeZone": "UTC"
231
+ }
232
+ }
233
+ result = make_api_call(access_token, 'me/events', method='POST', data=new_event)
234
+ if result:
235
+ st.success("Event added successfully!")
236
+ else:
237
+ st.error("Failed to add event.")
238
+
239
+ def handle_tasks_integration(access_token):
240
+ st.subheader("πŸ“‹ Tasks Integration")
241
+ st.markdown(f"[Open Tasks]({PRODUCT_SCOPES['πŸ“‹ Tasks']['link']})")
242
+
243
+ tasks = make_api_call(access_token, 'me/todo/lists')
244
+ if tasks and 'value' in tasks:
245
+ default_list = next((list for list in tasks['value'] if list['wellknownListName'] == 'defaultList'), None)
246
+ if default_list:
247
+ tasks = make_api_call(access_token, f"me/todo/lists/{default_list['id']}/tasks")
248
+ if tasks and 'value' in tasks:
249
+ for task in tasks['value']:
250
+ st.write(f"Task: {task['title']}")
251
+ st.write(f"Status: {'Completed' if task['status'] == 'completed' else 'Not Completed'}")
252
+ st.write("---")
253
+ else:
254
+ st.write("No tasks found or unable to fetch tasks.")
255
+ else:
256
+ st.write("Default task list not found.")
257
+ else:
258
+ st.write("Unable to fetch task lists.")
259
+
260
+ st.write("Add a new task:")
261
+ task_title = st.text_input("Task Title")
262
+ if st.button("Add Task"):
263
+ new_task = {
264
+ "title": task_title
265
+ }
266
+ result = make_api_call(access_token, f"me/todo/lists/{default_list['id']}/tasks", method='POST', data=new_task)
267
+ if result:
268
+ st.success("Task added successfully!")
269
+ else:
270
+ st.error("Failed to add task.")
271
+
272
+ def handle_onedrive_integration(access_token):
273
+ st.subheader("πŸ—‚οΈ OneDrive Integration")
274
+ st.markdown(f"[Open OneDrive]({PRODUCT_SCOPES['πŸ—‚οΈ OneDrive']['link']})")
275
+
276
+ files = make_api_call(access_token, 'me/drive/root/children')
277
+ if files and 'value' in files:
278
+ for file in files['value']:
279
+ st.write(f"Name: {file['name']}")
280
+ st.write(f"Type: {'Folder' if 'folder' in file else 'File'}")
281
+ st.write(f"Last Modified: {file['lastModifiedDateTime']}")
282
+ st.write("---")
283
+ else:
284
+ st.write("No files found or unable to fetch files.")
285
 
 
286
  def main():
287
  st.title("πŸ¦„ MS Graph API with AI & Cloud Integration for M365")
288
+
 
289
  st.sidebar.title("πŸ“ M365 Products")
290
  st.sidebar.write("Select products to integrate:")
291
 
292
  selected_products = {}
293
+ for product in PRODUCT_SCOPES.keys():
294
  selected = st.sidebar.checkbox(product)
295
  if selected:
296
  selected_products[product] = True
 
 
297
 
 
298
  request_scopes = BASE_SCOPES.copy()
299
  for product in selected_products:
300
+ request_scopes.extend(PRODUCT_SCOPES[product]['scopes'])
301
+ request_scopes = list(set(request_scopes))
302
+
303
  st.session_state['request_scopes'] = request_scopes
304
 
 
305
  if 'access_token' not in st.session_state:
306
  client_instance = get_msal_app()
307
  auth_url = client_instance.get_authorization_request_url(
308
  scopes=request_scopes,
309
  redirect_uri=REDIRECT_URI
310
  )
311
+ st.write('πŸ‘‹ Please [click here]({}) to log in and authorize the app.'.format(auth_url))
312
 
313
  query_params = st.query_params
314
  if 'code' in query_params:
315
  code = query_params.get('code')
316
+ st.write('πŸ”‘ Authorization Code Obtained:', code[:10] + '...')
317
 
318
  try:
319
  access_token = get_access_token(code)
 
331
  st.sidebar.write(f"πŸ‘‹ Hello, {user_info.get('displayName', 'User')}!")
332
 
333
  if selected_products:
 
334
  for product in selected_products:
335
  if product == "πŸ“§ Outlook":
336
  handle_outlook_integration(access_token)
337
+ elif product == "πŸ“… Calendar":
338
+ handle_calendar_integration(access_token)
339
+ elif product == "πŸ“‹ Tasks":
340
+ handle_tasks_integration(access_token)
341
+ elif product == "πŸ—‚οΈ OneDrive":
342
+ handle_onedrive_integration(access_token)
343
+ # Add more product integrations here
344
  else:
345
  st.write("No products selected. Please select products from the sidebar.")
346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  if __name__ == "__main__":
348
  main()
349
+