File size: 2,157 Bytes
ad91a7c
4e182e6
15434c2
 
ad91a7c
96fbe55
 
 
 
 
ad91a7c
4e182e6
ec26d3d
 
 
ad91a7c
ec26d3d
 
 
 
 
ad91a7c
4e182e6
ec26d3d
15434c2
ec26d3d
4e182e6
ad91a7c
ec26d3d
4e182e6
ec26d3d
ad91a7c
ec26d3d
15434c2
4e182e6
ec26d3d
 
 
 
 
 
 
 
 
 
 
 
 
15434c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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')