Spaces:
Sleeping
Sleeping
File size: 2,797 Bytes
8d39e37 9c54e4c 8d39e37 9c54e4c 8d39e37 9c54e4c 8d39e37 9c54e4c 8d39e37 9c54e4c 8d39e37 9c54e4c |
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import streamlit as st
import json
from googleapiclient.discovery import build
# ---------------- Sidebar Configuration ----------------
st.sidebar.header("Configuration")
default_api_key = "AIzaSyAYdqy4sQzUPFXuSXVDJn3WHIEaHMXMv5I"
API_KEY = st.sidebar.text_input(
"Enter your PageSpeed Insights API Key",
value=default_api_key,
help="Don't have one? Get your API key from [Google PageSpeed Insights Get Started](https://developers.google.com/speed/docs/insights/v5/get-started)."
)
url = st.sidebar.text_input("URL", "https://www.ocoya.com/")
strategy = st.sidebar.radio("Select Strategy", ("DESKTOP", "MOBILE"), index=0)
st.sidebar.markdown("### About")
st.sidebar.info(
"This app uses the Google PageSpeed Insights API to analyze the performance of a web page. "
"You can use your own API key or the default key provided above."
)
# ---------------- Helper Functions ----------------
def run_pagespeed(service, url, strategy="DESKTOP"):
st.info(f"Running PageSpeed Insights for {url} with strategy {strategy}...")
try:
result = service.pagespeedapi().runpagespeed(url=url, strategy=strategy).execute()
except Exception as e:
st.error(f"Error running PageSpeed Insights on {url}: {e}")
return None
return result
def process_result(result):
"""
Extract key metrics from the API response.
Scores are converted to percentages (0-100).
"""
data = {}
try:
lighthouse_result = result.get("lighthouseResult", {})
categories = lighthouse_result.get("categories", {})
for cat, details in categories.items():
score = details.get("score", None)
data[cat] = round(score * 100, 2) if score is not None else None
data["requestedUrl"] = result.get("id", "")
config_settings = lighthouse_result.get("configSettings", {})
data["strategy"] = config_settings.get("formFactor", "")
data["fetchTime"] = lighthouse_result.get("fetchTime", "")
except Exception as e:
st.error(f"Error processing result: {e}")
return data
# ---------------- Main App Content ----------------
st.title("PageSpeed Insights Analyzer")
st.write(
"Use the sidebar to configure the analysis by entering a URL, selecting a strategy, and providing an API key. "
"Then click **Run Analysis** in the sidebar."
)
if st.sidebar.button("Run Analysis"):
# Build the API service object
service = build('pagespeedonline', 'v5', developerKey=API_KEY)
with st.spinner("Running analysis..."):
result = run_pagespeed(service, url, strategy=strategy)
if result:
metrics = process_result(result)
st.subheader("Extracted Metrics")
st.write(metrics)
st.subheader("Full JSON Response")
st.json(result)
|