Spaces:
Sleeping
Sleeping
| 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) | |