Spaces:
Sleeping

IP-Safe / authenticate_oauth.py
Yash
Initial commit: IP/QC + Narration Matching + Character Generation pipelines
68697dc
Raw History Blame Contribute Delete
2.58 kB
"""One-time OAuth authentication for Google Sheets."""
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os
from loguru import logger
# Scopes required for Google Sheets and Drive
SCOPES = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive',
]
def authenticate():
"""
Perform OAuth authentication and save token.
This only needs to be run once.
"""
creds = None
token_path = 'token.pickle'
# Check if we already have a token
if os.path.exists(token_path):
logger.info("Found existing token")
with open(token_path, 'rb') as token:
creds = pickle.load(token)
# Validate that the token has all required scopes
if creds and creds.valid:
required = set(SCOPES)
granted = set(creds.scopes or [])
if not required.issubset(granted):
logger.warning("Existing token is missing required scopes. Re-authenticating...")
print("\n⚠ Token scope mismatch — re-authenticating to get full Drive access.")
creds = None
os.remove(token_path)
# If no valid credentials, perform OAuth flow
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
logger.info("Refreshing expired token...")
creds.refresh(Request())
else:
logger.info("Starting OAuth authentication flow...")
logger.info("A browser window will open. Please sign in with your Google account.")
flow = InstalledAppFlow.from_client_secrets_file(
'oauth_credentials.json',
SCOPES
)
# Run local server for OAuth callback
# Use fixed port 8080 for easier redirect URI configuration
creds = flow.run_local_server(port=8080)
# Save the credentials for future use
with open(token_path, 'wb') as token:
pickle.dump(creds, token)
logger.success("Authentication successful! Token saved to token.pickle")
print("\n✓ Authentication complete!")
print(" Token saved. You won't need to authenticate again.")
print(" You can now run upload_to_sheets.py to upload with thumbnails!")
else:
logger.info("Already authenticated!")
print("\n✓ Already authenticated!")
print(" Your token is valid. Ready to upload!")
if __name__ == "__main__":
authenticate()