Guilherme Favaron Claude commited on
Commit
ed17ba2
·
1 Parent(s): e5bd1d5

Remove public API - require Google Cloud authentication

Browse files

- Removed public API access as requested by user
- App now requires either GOOGLE_API_KEY or GOOGLE_SERVICE_ACCOUNT_JSON
- Added comprehensive setup instructions in error screen
- Shows clear guidance for both API key and Service Account options
- App will not start without proper Google Cloud authentication

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (3) hide show
  1. google_auth.py +9 -5
  2. pagespeed_client.py +2 -1
  3. ui.py +32 -3
google_auth.py CHANGED
@@ -87,10 +87,10 @@ class PageSpeedAPI:
87
  }
88
 
89
  # Try different authentication methods in order of preference
 
90
  auth_methods = [
91
  ('api_key', self._get_api_key_auth),
92
- ('oauth2', self._get_oauth2_auth),
93
- ('public', self._get_public_auth)
94
  ]
95
 
96
  last_response = None
@@ -168,6 +168,10 @@ class PageSpeedAPI:
168
  return {}, {}
169
 
170
  def is_available(self) -> bool:
171
- """Check if the PageSpeed API is available."""
172
- # API is always available - we'll try different auth methods
173
- return True
 
 
 
 
 
87
  }
88
 
89
  # Try different authentication methods in order of preference
90
+ # Removed public API as per user request
91
  auth_methods = [
92
  ('api_key', self._get_api_key_auth),
93
+ ('oauth2', self._get_oauth2_auth)
 
94
  ]
95
 
96
  last_response = None
 
168
  return {}, {}
169
 
170
  def is_available(self) -> bool:
171
+ """Check if the PageSpeed API is available with authentication."""
172
+ # Check if we have any authentication method available
173
+ api_key = os.environ.get('GOOGLE_API_KEY')
174
+ has_api_key = api_key and len(api_key) < 100
175
+ has_oauth = self.authenticator.is_authenticated()
176
+
177
+ return has_api_key or has_oauth
pagespeed_client.py CHANGED
@@ -12,7 +12,8 @@ class PageSpeedClient:
12
  """Client for PageSpeed Insights API with OAuth2 authentication."""
13
  def __init__(self):
14
  self.api_client = PageSpeedAPI()
15
- # API is now always available - we'll try different auth methods
 
16
 
17
  def extract_pagespeed_data(self, report_url: str) -> Optional[PageSpeedData]:
18
  """Extract PageSpeed data from a PageSpeed Insights report URL."""
 
12
  """Client for PageSpeed Insights API with OAuth2 authentication."""
13
  def __init__(self):
14
  self.api_client = PageSpeedAPI()
15
+ if not self.api_client.is_available():
16
+ raise ValueError("Google authentication required. Configure GOOGLE_API_KEY or GOOGLE_SERVICE_ACCOUNT_JSON.")
17
 
18
  def extract_pagespeed_data(self, report_url: str) -> Optional[PageSpeedData]:
19
  """Extract PageSpeed data from a PageSpeed Insights report URL."""
ui.py CHANGED
@@ -28,6 +28,37 @@ class PageSpeedUI:
28
  def create_interface(self) -> gr.Blocks:
29
  """Create and configure the Gradio interface."""
30
  with gr.Blocks(title="PageSpeed Insights Comparator", theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # Check authentication status
32
  has_openai = bool(config.openai_api_key)
33
  has_google_key = bool(os.environ.get('GOOGLE_API_KEY')) and len(os.environ.get('GOOGLE_API_KEY', '')) < 100
@@ -40,7 +71,7 @@ class PageSpeedUI:
40
  elif has_google_service:
41
  auth_status.append("✅ Google Service Account configurado")
42
  else:
43
- auth_status.append(" Usando Google PageSpeed público")
44
 
45
  if has_openai:
46
  auth_status.append("✅ OpenAI configurado")
@@ -60,8 +91,6 @@ class PageSpeedUI:
60
  3. Clique em "Comparar Análises"
61
 
62
  **Exemplo de URL:** `https://pagespeed.web.dev/analysis/https-www-example-com/abc123?form_factor=mobile`
63
-
64
- {"**⚠️ Importante:** API pública tem limites de uso. Se receber erro de rate limit, aguarde alguns minutos ou configure um Google API Key para limites maiores." if not has_google_key and not has_google_service else ""}
65
  """)
66
 
67
  with gr.Row():
 
28
  def create_interface(self) -> gr.Blocks:
29
  """Create and configure the Gradio interface."""
30
  with gr.Blocks(title="PageSpeed Insights Comparator", theme=gr.themes.Soft()) as demo:
31
+ if self.config_error:
32
+ gr.Markdown(f"""
33
+ # ❌ Configuração do Google Cloud Necessária
34
+
35
+ **Erro:** {self.config_error}
36
+
37
+ Para usar este app com seu projeto Google Cloud, você precisa configurar uma das opções:
38
+
39
+ ## **Opção 1: Google API Key (Recomendado)**
40
+ 1. Vá para [Google Cloud Console](https://console.cloud.google.com/)
41
+ 2. Selecione seu projeto
42
+ 3. Vá para **APIs & Services** → **Library**
43
+ 4. Pesquise e ative "PageSpeed Insights API"
44
+ 5. Vá para **APIs & Services** → **Credentials**
45
+ 6. Clique **+ CREATE CREDENTIALS** → **API key**
46
+ 7. Copie sua API key (ex: `AIzaSyD...`)
47
+ 8. Adicione no Space: `GOOGLE_API_KEY` = sua chave
48
+
49
+ ## **Opção 2: Service Account (Avançado)**
50
+ 1. No Google Cloud Console, vá para **IAM & Admin** → **Service Accounts**
51
+ 2. Crie uma Service Account
52
+ 3. Baixe o arquivo JSON
53
+ 4. Adicione no Space: `GOOGLE_SERVICE_ACCOUNT_JSON` = conteúdo do JSON
54
+
55
+ ## **Configurar no Hugging Face:**
56
+ 1. Settings → Variables and secrets
57
+ 2. Adicione uma das variáveis acima
58
+ 3. Reinicie o Space
59
+ """)
60
+ return demo
61
+
62
  # Check authentication status
63
  has_openai = bool(config.openai_api_key)
64
  has_google_key = bool(os.environ.get('GOOGLE_API_KEY')) and len(os.environ.get('GOOGLE_API_KEY', '')) < 100
 
71
  elif has_google_service:
72
  auth_status.append("✅ Google Service Account configurado")
73
  else:
74
+ auth_status.append(" Google authentication não configurado")
75
 
76
  if has_openai:
77
  auth_status.append("✅ OpenAI configurado")
 
91
  3. Clique em "Comparar Análises"
92
 
93
  **Exemplo de URL:** `https://pagespeed.web.dev/analysis/https-www-example-com/abc123?form_factor=mobile`
 
 
94
  """)
95
 
96
  with gr.Row():