Introduction
Creating an application that allows users to securely sign in with their Google account to access and display images from their Google Drive involves integrating Google OAuth 2.0 authentication and the Google Drive API. In this guide, we will build a web application using Streamlit, a popular Python library for building interactive web apps, and deploy it on a HuggingFace Space.
This application will:
- Allow users to sign in with their Google account.
- Let users navigate through their Google Drive folders.
- Display images from a selected folder in a randomized order.
- Provide a user-friendly and mobile-compatible interface.
- Ensure user account security is not compromised.
Prerequisites
Before we begin, make sure you have the following:
- A Google Cloud Platform (GCP) project with the Google Drive API enabled.
- OAuth 2.0 Client ID and Client Secret obtained from the GCP console.
- Streamlit installed (
pip install streamlit).
- Python 3.7+ installed.
Step 1: Set Up Google Cloud Project and OAuth Credentials
1.1 Create a Google Cloud Project
1.2 Enable Google Drive API
- In the Cloud Console, navigate to APIs & Services > Library.
- Search for Google Drive API and click Enable.
1.3 Configure OAuth Consent Screen
- Go to APIs & Services > OAuth consent screen.
- Select External user type.
- Fill in the required app information (App name, User support email, Developer contact information).
- Add Scopes:
.../auth/drive.readonly - To read files from Google Drive.
- Save and continue through the remaining steps.
1.4 Create OAuth 2.0 Credentials
-
Navigate to APIs & Services > Credentials.
-
Click Create Credentials > OAuth client ID.
-
Choose Web application as the application type.
-
Add Authorized JavaScript origins:
https://your-huggingface-space.hf.space
-
Add Authorized redirect URIs:
https://your-huggingface-space.hf.space
https://your-huggingface-space.hf.space/
-
Replace your-huggingface-space with the actual URL of your HuggingFace Space.
-
Click Create to obtain your Client ID and Client Secret.
Step 2: Application Code
Below is the complete code for the application. This code should be placed in a file named app.py.
import streamlit as st
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from google.oauth2 import credentials
import os
import pickle
import random
from io import BytesIO
from PIL import Image
import requests
# Constants
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
CLIENT_SECRETS_FILE = 'client_secrets.json'
# Function to create the OAuth flow
def create_flow():
return Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE,
scopes=SCOPES,
redirect_uri=REDIRECT_URI
)
# Main function
def main():
st.title("Google Drive Image Viewer")
if 'credentials' not in st.session_state:
st.session_state['credentials'] = None
if st.session_state['credentials'] is None:
auth_url, _ = flow.authorization_url(prompt='consent')
st.write("Please [authorize]({}) to continue.".format(auth_url))
else:
creds = credentials.Credentials(**st.session_state['credentials'])
service = build('drive', 'v3', credentials=creds)
# List files and folders
folders = list_folders(service)
folder_id = st.selectbox("Select a folder", folders.keys(), format_func=lambda x: folders[x])
if folder_id:
# Get images from the selected folder
images = list_images_in_folder(service, folder_id)
if images:
# Shuffle images
random.shuffle(images)
# Display images one by one
for image in images:
img_data = download_image(service, image['id'])
image_pil = Image.open(BytesIO(img_data))
st.image(image_pil, caption=image['name'])
if st.button("Next Image"):
continue
else:
break
else:
st.write("No images found in this folder.")
else:
st.write("No folders found in your Drive.")
# Function to list folders in Google Drive
def list_folders(service):
results = service.files().list(
q="mimeType='application/vnd.google-apps.folder' and trashed=false",
spaces='drive',
fields='nextPageToken, files(id, name)').execute()
items = results.get('files', [])
folders = {item['id']: item['name'] for item in items}
return folders
# Function to list images in a folder
def list_images_in_folder(service, folder_id):
query = f"parents='{folder_id}' and mimeType contains 'image/' and trashed=false"
results = service.files().list(
q=query,
spaces='drive',
fields='nextPageToken, files(id, name, mimeType)').execute()
items = results.get('files', [])
return items
# Function to download image file
def download_image(service, file_id):
request = service.files().get_media(fileId=file_id)
fh = BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
fh.seek(0)
return fh.read()
# Streamlit runs from here
if __name__ == '__main__':
import os
from urllib.parse import urlparse, parse_qs
from googleapiclient.http import MediaIoBaseDownload
# Set REDIRECT_URI
if 'REDIRECT_URI' not in st.session_state:
# Get the full URL of the app
REDIRECT_URI = st.secrets["REDIRECT_URI"]
st.session_state['REDIRECT_URI'] = REDIRECT_URI
else:
REDIRECT_URI = st.session_state['REDIRECT_URI']
# Load the client secrets file
if not os.path.exists(CLIENT_SECRETS_FILE):
st.error("Client secrets file not found.")
else:
flow = create_flow()
# Check for authorization response
if 'code' in st.experimental_get_query_params():
code = st.experimental_get_query_params()['code']
flow.fetch_token(code=code)
creds = flow.credentials
st.session_state['credentials'] = {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes
}
st.experimental_rerun()
else:
main()
Additional Files
client_secrets.json
Download the client_secrets.json file from your Google Cloud Console (where you obtained your Client ID and Client Secret) and include it in the root directory of your application.
requirements.txt
Create a requirements.txt file with the following contents:
streamlit==1.25.0
google-auth==2.23.4
google-auth-oauthlib==1.0.0
google-api-python-client==2.100.0
Pillow==10.0.1
Step 3: Instructions for Implementation in a HuggingFace Space
3.1 Create a New HuggingFace Space
- Go to HuggingFace Spaces.
- Click New Space.
- Fill in the details:
- Repository name: A unique name for your app.
- License: Choose an appropriate license.
- Space Hardware: Select the hardware (CPU is sufficient).
- SDK: Choose Streamlit.
- Click Create Space.
3.2 Upload Files to the Space
- Upload the following files to the root of your Space repository:
app.py (the main application code).
client_secrets.json (your OAuth 2.0 credentials).
requirements.txt (the list of dependencies).
3.3 Set Streamlit Secrets
HuggingFace Spaces allows you to set secret environment variables.
- In your Space, go to the Settings tab.
- Scroll down to Secrets.
- Add a new secret:
- Name:
REDIRECT_URI
- Value:
https://your-space-name.hf.space/
- Replace
your-space-name with your actual Space name.
3.4 Update Authorized Redirect URIs in Google Cloud Console
Ensure that the Authorized redirect URIs in your OAuth 2.0 Client ID settings match the URL of your HuggingFace Space.
- Go back to the Credentials section in the Google Cloud Console.
- Edit your OAuth 2.0 Client ID.
- Update the Authorized redirect URIs to include:
https://your-space-name.hf.space
https://your-space-name.hf.space/
- Save your changes.
3.5 Deploy and Test the Application
- Once all files are uploaded, the app will automatically start building.
- After the build process completes, navigate to the App tab to view your running application.
- Test the application by attempting to sign in with your Google account.
Important Notes on Security and Verification
-
User Data Privacy: Ensure that user credentials and tokens are not stored persistently on the server or logs. In this application, credentials are stored in the st.session_state, which is temporary and specific to each user's session.
-
OAuth Consent Screen Verification: For an application that accesses sensitive scopes (like https://www.googleapis.com/auth/drive.readonly) and is available to external users, Google may require you to go through a verification process to ensure compliance with their OAuth Application Verification requirements.
-
Usage Limits: Unverified apps have usage limits and display an "unverified app" screen during the OAuth process.
-
Testing: You can add test users in the OAuth consent screen configuration in the Google Cloud Console to allow specific accounts to bypass verification during development.
Conclusion
You now have a fully functional application that allows users to securely sign in with their Google account, navigate their Google Drive folders, and display images in a randomized order. By deploying it on HuggingFace Spaces, you've made it accessible with minimal infrastructure overhead.
Troubleshooting
-
Error: redirect_uri_mismatch: Ensure that the REDIRECT_URI in your app matches exactly with one of the Authorized redirect URIs in your Google Cloud Console.
-
Credentials Not Found: Make sure that your client_secrets.json file is correctly named and placed in the root directory.
-
Session State Issues: If the app isn't retaining session state, confirm that you're not running into limitations with stateless hosting on HuggingFace Spaces. Consider using a database or encrypted cookies for session management if necessary.
-
Application Verification Required: If users see a "This app isn't verified" screen, you'll need to submit your app for verification by Google.
References
Disclaimer: Be sure to comply with Google's policies when using their APIs and handle user data responsibly.