GSC-analytics / app.py
blazingbunny's picture
Update app.py
ec26d3d verified
raw
history blame
2.2 kB
import streamlit as st
from requests_oauthlib import OAuth2Session
import os # For loading credentials from environment variables
# ************ SECURITY: Replace placeholders with your actual credentials ***************
CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID') # Obtain from Google Cloud Console
CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET') # Obtain from Google Cloud Console
REDIRECT_URI = 'https://your-huggingface-space-app-url.hf.space' # Must match Google Project setting
# ************************************************************************************
# OAuth Configuration
AUTHORIZATION_BASE_URL = 'https://accounts.google.com/o/oauth2/v2/auth'
TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'
SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
# Streamlit UI
st.title("Search Analytics Viewer")
site_url = st.text_input("Enter your website URL:", "https://www.example.com")
start_date = st.date_input("Start Date")
end_date = st.date_input("End Date")
if st.button("Fetch Data"):
# Initiate OAuth Flow
google_oauth = OAuth2Session(CLIENT_ID, scopes=SCOPES, redirect_uri=REDIRECT_URI)
authorization_url, state = google_oauth.authorization_url(AUTHORIZATION_BASE_URL, access_type="offline", prompt="select_account")
st.write("Please authenticate with Google:", authorization_url)
# Handle Redirect
redirect_response = st.text_input("Paste the full redirect URL here:")
token = google_oauth.fetch_token(TOKEN_URL, client_secret=CLIENT_SECRET, authorization_response=redirect_response)
# Use Authorized Session to Make API Requests
credentials = google_oauth.authorized
service = build('webmasters', 'v3', credentials=credentials)
request = {
'startDate': start_date.strftime("%Y-%m-%d"),
'endDate': end_date.strftime("%Y-%m-%d"),
'dimensions': ['query', 'page'],
'siteUrl': site_url
}
response = service.searchanalytics().query(siteUrl=request['siteUrl'], body=request).execute()
# Display Search Analytics Data (Customize this!)
if 'rows' in response:
st.dataframe(response['rows'])
else:
st.write('No data found')