Spaces:
Sleeping
Sleeping
import streamlit as st | |
from requests_oauthlib import OAuth2Session | |
from googleapiclient.discovery import build | |
from datetime import datetime, timedelta | |
import json | |
# ************ Credentials (Important Security Note - See above warning) *************** | |
CLIENT_ID = "243651188615-q9970hsa72e028jnu3qqsup6vl02epnn.apps.googleusercontent.com" | |
CLIENT_SECRET_JSON = st.secrets["google_search_console_api"] | |
REDIRECT_URI = 'https://huggingface.co/spaces/blazingbunny/GSC-analytics/' | |
# ********************************************* | |
# Load client secret JSON | |
client_secret_data = json.loads(CLIENT_SECRET_JSON) | |
CLIENT_SECRET = st.secrets["CLIENT_SECRET"] | |
# 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'] | |
# Initiate OAuth Flow | |
google_oauth = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI, scope=SCOPES) | |
# Streamlit UI | |
st.title("Search Analytics Viewer") | |
# Authenticate with Google | |
if st.button("Authenticate with Google"): | |
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) | |
# Fetch list of available domains | |
domains_request = service.sites().list().execute() | |
available_domains = [site['siteUrl'] for site in domains_request.get('siteEntry', [])] | |
# Dropdown field for selecting domain | |
selected_domain = st.selectbox("Select Domain:", available_domains) | |
# Date inputs | |
start_date = st.date_input("Start Date") | |
end_date = st.date_input("End Date") | |
# Fetch data for selected domain | |
if st.button("Fetch Data"): | |
request = { | |
'startDate': start_date.strftime("%Y-%m-%d"), | |
'endDate': end_date.strftime("%Y-%m-%d"), | |
'dimensions': ['query', 'page'], | |
'siteUrl': selected_domain | |
} | |
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') | |