Spaces:
Running
Running
File size: 22,171 Bytes
d5816db 22e3a2d 505c44e d5816db d301be5 d5816db 9dc8b13 d5816db 544c7de 41d9a07 544c7de 41d9a07 d5816db 41d9a07 d5816db 22e3a2d d5816db 8f99561 544c7de afca6dc 8f99561 544c7de 41d9a07 544c7de 8f99561 d5816db 3009bf0 544c7de d5816db 544c7de d5816db 544c7de 5927e43 544c7de d5816db 544c7de a325626 544c7de a325626 aef244f a325626 544c7de a325626 d5816db a325626 544c7de a325626 544c7de a325626 544c7de a325626 544c7de a325626 544c7de a325626 544c7de d5816db |
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
import os
import streamlit as st
import requests
import msal
import urllib.parse
import base64
import hashlib
import secrets
# π€ Load environment variables (Ensure these are set!)
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY')
AUTHORITY_URL = 'https://login.microsoftonline.com/common' # Use 'common' for multi-tenant apps
#REDIRECT_URI = 'http://localhost:8501' # π Make sure this matches your app's redirect URI
REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI' # π Make sure this matches your app's redirect URI
# π― Define the scopes your app will need
#SCOPES = ['User.Read', 'Calendars.ReadWrite', 'Mail.ReadWrite', 'Notes.ReadWrite.All', 'Files.ReadWrite.All']
SCOPES = ['User.Read']
# New function to generate PKCE code verifier and challenge
def generate_pkce_codes():
code_verifier = secrets.token_urlsafe(128)[:128]
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().rstrip('=')
return code_verifier, code_challenge
def get_msal_app(code_challenge=None):
return msal.PublicClientApplication(
client_id=APPLICATION_ID_KEY,
authority=AUTHORITY_URL
)
# π οΈ Initialize the MSAL client
def get_msal_app_old():
return msal.ConfidentialClientApplication(
client_id=APPLICATION_ID_KEY,
client_credential=CLIENT_SECRET_KEY,
authority=AUTHORITY_URL
)
# π Acquire access token using authorization code
def get_access_token(code):
client_instance = get_msal_app()
# Debug: Print MSAL app configuration (be careful not to expose secrets)
st.write("Debug: MSAL App Configuration:")
st.write(f"Client ID: {APPLICATION_ID_KEY[:5]}...") # Show first 5 chars
st.write(f"Authority: {AUTHORITY_URL}")
st.write(f"Redirect URI: {REDIRECT_URI}")
try:
result = client_instance.acquire_token_by_authorization_code(
code=code,
scopes=SCOPES,
redirect_uri=REDIRECT_URI
)
if 'access_token' in result:
return result['access_token']
else:
error_description = result.get('error_description', 'No error description provided')
raise Exception(f"Error acquiring token: {error_description}")
except Exception as e:
st.error(f"Exception in get_access_token: {str(e)}")
raise
#st.stop()
def get_access_token(code, code_verifier):
client_instance = get_msal_app()
st.write("Debug: MSAL App Configuration:")
st.write(f"Client ID: {APPLICATION_ID_KEY[:5]}...")
st.write(f"Authority: {AUTHORITY_URL}")
st.write(f"Redirect URI: {REDIRECT_URI}")
try:
result = client_instance.acquire_token_by_authorization_code(
code=code,
scopes=SCOPES,
redirect_uri=REDIRECT_URI,
code_verifier=code_verifier # Include the code verifier here
)
if 'access_token' in result:
return result['access_token']
else:
error_description = result.get('error_description', 'No error description provided')
raise Exception(f"Error acquiring token: {error_description}")
except Exception as e:
st.error(f"Exception in get_access_token: {str(e)}")
raise
def process_query_params():
# βοΈq= Run ArXiv search from query parameters
try:
query_params = st.query_params
st.write("Debug: All query parameters:", query_params)
if 'error' in query_params:
error = query_params.get('error')
error_description = query_params.get('error_description', 'No description provided')
st.error(f"Authentication Error: {error}")
st.error(f"Error Description: {urllib.parse.unquote(error_description)}")
st.stop()
if 'code' in query_params:
code = query_params.get('code')
st.write('π Authorization Code Obtained:', code[:10] + '...')
try:
code_verifier = st.session_state.get('code_verifier')
if not code_verifier:
st.error("Code verifier not found in session state.")
st.stop()
access_token = get_access_token(code, code_verifier)
st.session_state['access_token'] = access_token
st.success("Access token acquired successfully!")
# Clear the code from the URL
st.experimental_set_query_params()
st.rerun()
except Exception as e:
st.error(f"Error acquiring access token: {str(e)}")
st.stop()
else:
st.warning("No authorization code found in the query parameters.")
query = (query_params.get('q') or query_params.get('query') or [''])
if len(query) > 1:
#result = search_arxiv(query)
#result2 = search_glossary(result)
filesearch = PromptPrefix + query
st.markdown(filesearch)
process_text(filesearch)
except:
st.markdown(' ')
if 'action' in st.query_params:
action = st.query_params()['action'][0] # Get the first (or only) 'action' parameter
if action == 'show_message':
st.success("Showing a message because 'action=show_message' was found in the URL.")
elif action == 'clear':
clear_query_params()
#st.rerun()
if 'query' in st.query_params:
query = st.query_params['query'][0] # Get the query parameter
# Display content or image based on the query
display_content_or_image(query)
# πββοΈ Main application function
def main():
st.title("π¦ MS Graph API with AI & Cloud Integration with M365")
process_query_params()
if 'access_token' not in st.session_state:
if 'code_verifier' not in st.session_state:
# Generate PKCE codes
code_verifier, code_challenge = generate_pkce_codes()
st.session_state['code_verifier'] = code_verifier
else:
code_verifier = st.session_state['code_verifier']
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().rstrip('=')
client_instance = get_msal_app()
auth_url = client_instance.get_authorization_request_url(
scopes=SCOPES,
redirect_uri=REDIRECT_URI,
code_challenge=code_challenge,
code_challenge_method="S256"
)
st.write('π Please [click here]({}) to log in and authorize the app.'.format(auth_url))
#st.stop()
# π Sidebar navigation
st.sidebar.title("Navigation")
menu = st.sidebar.radio("Go to", [
"1οΈβ£ Dashboard",
"π Landing Page",
"π
Upcoming Events",
"π Schedule",
"π Agenda",
"π Event Details",
"β Add Event",
"π Filter By"
])
# π M365 Products with MS Graph Integration & AI Features
st.sidebar.title("π M365 Products")
st.sidebar.write("Toggle integration for each product:")
# ποΈ Product Integration Toggles
products = {
"π§ Outlook": {
"ai_capabilities": "Copilot for enhanced email writing, calendar management, and scheduling.",
"graph_api": "Access to mail, calendar, contacts, and events."
},
"π OneNote": {
"ai_capabilities": "Content suggestion, note organization, and OCR for extracting text from images.",
"graph_api": "Manage notebooks, sections, and pages."
},
"π Excel": {
"ai_capabilities": "Copilot for advanced data analysis, data insights, and formula generation.",
"graph_api": "Create and manage worksheets, tables, charts, and workbooks."
},
"π Word": {
"ai_capabilities": "Copilot for document drafting, summarization, and grammar improvements.",
"graph_api": "Document content access, templates, and file management."
},
"ποΈ SharePoint": {
"ai_capabilities": "Intelligent search, document tagging, and metadata extraction.",
"graph_api": "Access to sites, lists, files, and document libraries."
},
"π
Teams": {
"ai_capabilities": "Copilot for meeting summaries, transcription, and chat suggestions.",
"graph_api": "Manage chats, teams, channels, and meetings."
},
"π¬ Viva": {
"ai_capabilities": "Personalized learning insights, well-being insights, and productivity suggestions.",
"graph_api": "Access to user analytics and learning modules."
},
"π Power Platform": {
"ai_capabilities": "Automation with AI Builder, data insights, and custom AI models.",
"graph_api": "Automation workflows, app creation, and data visualization."
},
"π§ Copilot": {
"ai_capabilities": "Embedded across Word, Excel, Outlook, Teams, and more for AI-driven productivity.",
"graph_api": "Underpins Copilot's access to data and integrations."
},
"ποΈ OneDrive": {
"ai_capabilities": "Intelligent file organization and search.",
"graph_api": "File and folder access, sharing, and metadata."
},
"π‘ PowerPoint": {
"ai_capabilities": "Design suggestions, presentation summarization, and speaker coaching.",
"graph_api": "Presentation creation, slide management, and templates."
},
"π Microsoft Bookings": {
"ai_capabilities": "Automated scheduling and reminders.",
"graph_api": "Booking calendars, services, and appointment details."
},
"π Loop": {
"ai_capabilities": "Real-time collaboration and content suggestions.",
"graph_api": "Access to shared workspaces and collaborative pages."
},
"π£οΈ Translator": {
"ai_capabilities": "Real-time language translation and text-to-speech.",
"graph_api": "Integrated into communication and translation services."
},
"π To Do & Planner": {
"ai_capabilities": "Task prioritization and smart reminders.",
"graph_api": "Task creation, management, and synchronization."
},
"π Azure OpenAI Service": {
"ai_capabilities": "Access to GPT models for custom AI implementations.",
"graph_api": "Used indirectly for building custom AI models into workflows."
}
}
# π³οΈ Create toggles for each product
selected_products = {}
for product, info in products.items():
selected = st.sidebar.checkbox(product)
if selected:
st.sidebar.write(f"**AI Capabilities:** {info['ai_capabilities']}")
st.sidebar.write(f"**Graph API:** {info['graph_api']}")
selected_products[product] = True
# π Authentication
if 'access_token' not in st.session_state:
# π΅οΈββοΈ Check for authorization code in query parameters
query_params = st.query_params
query = (query_params.get('code'))
#if len(query) > 1:
#st.write('Parsing query ' + query_params )
if 'code' in query_params:
#code = query_params['code'][0]
code = query_params.get('code')
st.write('πAccess Code Obtained from MS Graph Redirectπ!:' + code)
st.write('π Acquiring access token from redirect URL for code parameter.')
access_token = get_access_token(code)
st.session_state['access_token'] = access_token # π Save it for later
st.rerun() # Reload the app to clear the code from URL
else:
# π’ Prompt user to log in
client_instance = get_msal_app()
authorization_url = client_instance.get_authorization_request_url(
scopes=SCOPES,
redirect_uri=REDIRECT_URI
)
st.write('π Please [click here]({}) to log in and authorize the app.'.format(authorization_url))
st.stop()
else:
# π₯³ User is authenticated, proceed with the app
access_token = st.session_state['access_token']
headers = {'Authorization': 'Bearer ' + access_token}
# π€ Greet the user
response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
if response.status_code == 200:
user_info = response.json()
st.sidebar.write(f"π Hello, {user_info['displayName']}!")
else:
st.error('Failed to fetch user info.')
st.write(response.text)
# ποΈ Handle menu options
if menu == "1οΈβ£ Dashboard with Widgets":
st.header("1οΈβ£ Dashboard with Widgets")
st.write("Widgets will be displayed here. ποΈ")
# Add your widgets here
elif menu == "π Landing Page":
st.header("π Landing Page")
st.write("Welcome to the app! π₯³")
# Add landing page content here
elif menu == "π
Upcoming Events":
st.header("π
Upcoming Events")
events = get_upcoming_events(access_token)
for event in events:
st.write(f"π {event['subject']} on {event['start']['dateTime']}")
# Display upcoming events
elif menu == "π Schedule":
st.header("π Schedule")
schedule = get_schedule(access_token)
st.write(schedule)
# Display schedule
elif menu == "π Agenda":
st.header("π Agenda")
st.write("Your agenda for today. π")
# Display agenda
elif menu == "π Event Details":
st.header("π Event Details")
event_id = st.text_input("Enter Event ID")
if event_id:
event_details = get_event_details(access_token, event_id)
st.write(event_details)
# Display event details based on ID
elif menu == "β Add Event":
st.header("β Add Event")
event_subject = st.text_input("Event Subject")
event_start = st.date_input("Event Start Date")
event_start_time = st.time_input("Event Start Time")
event_end = st.date_input("Event End Date")
event_end_time = st.time_input("Event End Time")
if st.button("Add Event"):
event_details = {
"subject": event_subject,
"start": {
"dateTime": f"{event_start}T{event_start_time}",
"timeZone": "UTC"
},
"end": {
"dateTime": f"{event_end}T{event_end_time}",
"timeZone": "UTC"
}
}
add_event(access_token, event_details)
st.success("Event added successfully! π")
# Form to add new event
elif menu == "π Filter By":
st.header("π Filter Events")
filter_criteria = st.text_input("Enter filter criteria")
if filter_criteria:
filtered_events = filter_events(access_token, filter_criteria)
for event in filtered_events:
st.write(f"π
{event['subject']} on {event['start']['dateTime']}")
# Filter events based on criteria
# 𧩠Handle selected products
if selected_products:
st.header("𧩠M365 Product Integrations")
for product in selected_products:
st.subheader(f"{product}")
# Call the function corresponding to the product
handle_product_integration(access_token, product)
else:
st.write("No products selected.")
pass
# 𧩠Function to handle product integration
def handle_product_integration(access_token, product):
if product == "π§ Outlook":
st.write("Accessing Outlook data...")
# Implement Outlook integration
inbox_messages = get_outlook_messages(access_token)
st.write("Inbox Messages:")
for msg in inbox_messages:
st.write(f"βοΈ {msg['subject']}")
elif product == "π OneNote":
st.write("Accessing OneNote data...")
# Implement OneNote integration
notebooks = get_onenote_notebooks(access_token)
st.write("Notebooks:")
for notebook in notebooks:
st.write(f"π {notebook['displayName']}")
elif product == "π Excel":
st.write("Accessing Excel data...")
# Implement Excel integration
st.write("Excel integration is a placeholder.")
elif product == "π Word":
st.write("Accessing Word documents...")
# Implement Word integration
st.write("Word integration is a placeholder.")
elif product == "ποΈ SharePoint":
st.write("Accessing SharePoint sites...")
# Implement SharePoint integration
sites = get_sharepoint_sites(access_token)
st.write("Sites:")
for site in sites:
st.write(f"π {site['displayName']}")
elif product == "π
Teams":
st.write("Accessing Teams data...")
# Implement Teams integration
teams = get_user_teams(access_token)
st.write("Teams:")
for team in teams:
st.write(f"π₯ {team['displayName']}")
# Add additional product integrations as needed
else:
st.write(f"No integration implemented for {product}.")
# π¨ Function to get Outlook messages
def get_outlook_messages(access_token):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/me/messages?$top=5', headers=headers)
if response.status_code == 200:
messages = response.json().get('value', [])
return messages
else:
st.error('Failed to fetch messages.')
st.write(response.text)
return []
# π Function to get OneNote notebooks
def get_onenote_notebooks(access_token):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/me/onenote/notebooks', headers=headers)
if response.status_code == 200:
notebooks = response.json().get('value', [])
return notebooks
else:
st.error('Failed to fetch notebooks.')
st.write(response.text)
return []
# π Function to get SharePoint sites
def get_sharepoint_sites(access_token):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/sites?search=*', headers=headers)
if response.status_code == 200:
sites = response.json().get('value', [])
return sites
else:
st.error('Failed to fetch sites.')
st.write(response.text)
return []
# π₯ Function to get user's Teams
def get_user_teams(access_token):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/me/joinedTeams', headers=headers)
if response.status_code == 200:
teams = response.json().get('value', [])
return teams
else:
st.error('Failed to fetch teams.')
st.write(response.text)
return []
# π
Function to get upcoming events
def get_upcoming_events(access_token):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime&$top=10', headers=headers)
if response.status_code == 200:
events = response.json().get('value', [])
return events
else:
st.error('Failed to fetch upcoming events.')
st.write(response.text)
return []
# π Function to get schedule (Placeholder)
def get_schedule(access_token):
# Implement API call to get schedule
return "π Your schedule goes here."
# β Function to add a new event
def add_event(access_token, event_details):
headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
response = requests.post('https://graph.microsoft.com/v1.0/me/events', headers=headers, json=event_details)
if response.status_code == 201:
st.success('Event created successfully! π')
else:
st.error('Failed to create event.')
st.write(response.text)
# π Function to get event details
def get_event_details(access_token, event_id):
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get(f'https://graph.microsoft.com/v1.0/me/events/{event_id}', headers=headers)
if response.status_code == 200:
event = response.json()
return event
else:
st.error('Failed to fetch event details.')
st.write(response.text)
return {}
# π Function to filter events
def filter_events(access_token, filter_criteria):
headers = {'Authorization': 'Bearer ' + access_token}
# Implement filtering logic based on criteria
response = requests.get(f"https://graph.microsoft.com/v1.0/me/events?$filter=startswith(subject,'{filter_criteria}')", headers=headers)
if response.status_code == 200:
events = response.json().get('value', [])
return events
else:
st.error('Failed to filter events.')
st.write(response.text)
return []
# π Run the main function
if __name__ == "__main__":
main()
|