GSC-analytics / app.py
blazingbunny's picture
Update app.py
15434c2 verified
raw
history blame
2.16 kB
import streamlit as st
from requests_oauthlib import OAuth2Session
from googleapiclient.discovery import build
from datetime import datetime, timedelta
# ************ Credentials (Important Security Note - See above warning) ***************
CLIENT_ID = "243651188615-q9970hsa72e028jnu3qqsup6vl02epnn.apps.googleusercontent.com"
CLIENT_SECRET = st.secrets["google_search_console_api"] # Retrieve from Hugging Face Secrets
REDIRECT_URI = 'https://huggingface.co/spaces/blazingbunny/GSC-analytics/'
# *********************************************
# 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, redirect_uri=REDIRECT_URI, scope=SCOPES)
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.credentials
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')