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

Update scheduler.py

Browse files
Files changed (1) hide show
  1. scheduler.py +22 -87
scheduler.py CHANGED
@@ -11,15 +11,10 @@ SCOPES = ['https://www.googleapis.com/auth/calendar']
11
  def get_calendar_service():
12
  """
13
  Returns a Google Calendar service object for the current user.
14
- Modified for Hugging Face Spaces compatibility.
15
  """
16
  import streamlit as st
17
- import json
18
- import os
19
-
20
- # Define paths for credentials
21
- credentials_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'credentials')
22
- credentials_file = os.path.join(credentials_dir, 'credentials.json')
23
 
24
  creds = None
25
 
@@ -35,88 +30,28 @@ def get_calendar_service():
35
  del st.session_state['user_token']
36
  st.rerun()
37
  creds = Credentials.from_authorized_user_info(user_token, SCOPES)
38
- return build('calendar', 'v3', credentials=creds)
39
-
40
- # For Hugging Face Spaces: Manual OAuth flow
41
- st.markdown("### Google Calendar Authentication")
42
- st.info("This app needs access to your Google Calendar.")
43
-
44
- # Check multiple paths for credentials file
45
- credentials_paths = [
46
- credentials_file, # ./credentials/credentials.json
47
- 'credentials.json', # ./credentials.json (root directory)
48
- os.path.join('credentials', 'credentials.json') # relative path
49
- ]
50
-
51
- credentials_exist = False
52
- for path in credentials_paths:
53
- if os.path.exists(path):
54
- credentials_exist = True
55
- credentials_file = path
56
- break
57
-
58
- if not credentials_exist:
59
- st.error("Missing credentials.json file.")
60
- st.info("""
61
- To get your credentials.json:
62
- 1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
63
- 2. Create a new project
64
- 3. Enable the Google Calendar API
65
- 4. Create OAuth credentials (Desktop or Web application)
66
- 5. Download the credentials.json
67
- """)
68
-
69
- # Allow direct input of credentials
70
- creds_json = st.text_area("Paste your credentials JSON here:")
71
- if creds_json and st.button("Save Credentials"):
72
- try:
73
- creds_data = json.loads(creds_json)
74
- # Ensure credentials directory exists
75
- os.makedirs(credentials_dir, exist_ok=True)
76
- with open(credentials_file, 'w') as f:
77
- json.dump(creds_data, f)
78
- st.success("Credentials saved. Reloading...")
79
- st.rerun()
80
- except Exception as e:
81
- st.error(f"Error saving credentials: {e}")
82
-
83
- st.stop()
84
 
85
- # Set up OAuth device flow using found credentials file
86
- try:
87
- from google_auth_oauthlib.flow import InstalledAppFlow
88
- flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
89
-
90
- # Generate URL and code for device auth flow
91
- auth_url, _ = flow.authorization_url(prompt='consent')
92
-
93
- st.markdown("### Please complete these steps to authorize access:")
94
- st.markdown("**1. Visit this URL in your browser:**")
95
- st.code(auth_url)
96
- st.markdown("**2. Sign in and authorize the app**")
97
- st.markdown("**3. Copy the authorization code and paste it below:**")
98
-
99
- auth_code = st.text_input("Enter the authorization code:", key="auth_code")
100
-
101
- if auth_code and st.button("Submit Authorization Code"):
102
- try:
103
- flow.fetch_token(code=auth_code)
104
- creds = flow.credentials
105
- st.session_state['user_token'] = json.loads(creds.to_json())
106
- st.success("Authentication successful!")
107
- st.rerun()
108
- except Exception as e:
109
- st.error(f"Authorization failed: {e}")
110
- st.info("Please try again with a new code.")
111
-
112
- st.stop()
113
-
114
- except Exception as e:
115
- st.error(f"Authentication setup error: {e}")
116
- st.stop()
117
 
118
- # This should not be reached
119
- return None
120
 
121
  def parse_command(command):
122
  summary = "Meeting"
 
11
  def get_calendar_service():
12
  """
13
  Returns a Google Calendar service object for the current user.
14
+ Uses session-based token storage for multi-user/public apps.
15
  """
16
  import streamlit as st
17
+ import json # Import json at the top level to avoid the reference error
 
 
 
 
 
18
 
19
  creds = None
20
 
 
30
  del st.session_state['user_token']
31
  st.rerun()
32
  creds = Credentials.from_authorized_user_info(user_token, SCOPES)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ # If no valid credentials, authenticate
35
+ if not creds:
36
+ try:
37
+ flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
38
+ creds = flow.run_local_server(port=0)
39
+ # Save token in session_state
40
+ st.session_state['user_token'] = json.loads(creds.to_json())
41
+ except Exception as e:
42
+ st.error(f"Authentication Error: {str(e)}")
43
+ # Display clear instructions for troubleshooting
44
+ st.warning("""
45
+ Authentication failed. Please ensure:
46
+ 1. You have a valid credentials.json file in the app directory
47
+ 2. You're running this app on a machine with a web browser
48
+ 3. Port 0 is available for the authentication callback
49
+
50
+ If you're running this on a server without a browser, please run it locally first to generate the token.json file.
51
+ """)
52
+ raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ return build('calendar', 'v3', credentials=creds)
 
55
 
56
  def parse_command(command):
57
  summary = "Meeting"