Tngarg commited on
Commit
0788734
·
verified ·
1 Parent(s): befaa94

Update performance_agent.py

Browse files
Files changed (1) hide show
  1. performance_agent.py +63 -63
performance_agent.py CHANGED
@@ -1,63 +1,63 @@
1
- # performance_agent.py
2
-
3
- import os
4
- import requests
5
-
6
- class PerformanceAgent:
7
- """
8
- Wraps the PageSpeed Insights API to fetch
9
- Lighthouse scores for a given URL.
10
- On any network/API failure, returns all-100% defaults.
11
- """
12
-
13
- EXPECTED_CATEGORIES = ("performance", "accessibility", "best-practices", "seo")
14
-
15
- def __init__(self):
16
- self.api_key = os.getenv("PAGESPEED_API_KEY","AIzaSyAKyKYao-FVDmhqcwLojv6DDl7nALjwghg")
17
- self.endpoint = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
18
- if not self.api_key:
19
- raise ValueError("PAGESPEED_API_KEY not set in .env")
20
-
21
- def fetch_performance(self, url: str, strategy: str = "mobile") -> dict:
22
- params = {
23
- "url": url,
24
- "strategy": strategy, # "mobile" or "desktop"
25
- "key": self.api_key
26
- }
27
-
28
- try:
29
- resp = requests.get(self.endpoint, params=params, timeout=30)
30
- resp.raise_for_status()
31
- data = resp.json()
32
- lh = data.get("lighthouseResult", {})
33
- cats = lh.get("categories", {})
34
- audits = lh.get("audits", {})
35
-
36
- # Build scores, default missing/unparsable → 100.0
37
- scores = {}
38
- for cat in self.EXPECTED_CATEGORIES:
39
- raw = cats.get(cat, {}).get("score")
40
- if isinstance(raw, (int, float)):
41
- scores[cat] = round(raw * 100, 1)
42
- else:
43
- scores[cat] = 100.0
44
-
45
- # Collect audits < 100% for suggestions
46
- audit_suggestions = {}
47
- for audit_id, info in audits.items():
48
- sc = info.get("score")
49
- if isinstance(sc, (int, float)) and sc < 1:
50
- audit_suggestions[audit_id] = info.get("displayValue", "").strip()
51
-
52
- return {
53
- "scores": scores,
54
- "audit_suggestions": audit_suggestions
55
- }
56
-
57
- except requests.exceptions.RequestException as e:
58
- # Log the error and return an all-100% default, with no suggestions
59
- print(f"[PerformanceAgent] PSI API error: {e}")
60
- return {
61
- "scores": {cat: 100.0 for cat in self.EXPECTED_CATEGORIES},
62
- "audit_suggestions": {}
63
- }
 
1
+ # performance_agent.py
2
+
3
+ import os
4
+ import requests
5
+
6
+ class PerformanceAgent:
7
+ """
8
+ Wraps the PageSpeed Insights API to fetch
9
+ Lighthouse scores for a given URL.
10
+ On any network/API failure, returns all-100% defaults.
11
+ """
12
+
13
+ EXPECTED_CATEGORIES = ("performance", "accessibility", "best-practices", "seo")
14
+
15
+ def __init__(self):
16
+ self.api_key = os.getenv("PAGESPEED_API_KEY","AAIzaSyBcFCQnfZLrAa2azkYvD-0ytIvQe32LlFs")
17
+ self.endpoint = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
18
+ if not self.api_key:
19
+ raise ValueError("PAGESPEED_API_KEY not set in .env")
20
+
21
+ def fetch_performance(self, url: str, strategy: str = "mobile") -> dict:
22
+ params = {
23
+ "url": url,
24
+ "strategy": strategy, # "mobile" or "desktop"
25
+ "key": self.api_key
26
+ }
27
+
28
+ try:
29
+ resp = requests.get(self.endpoint, params=params, timeout=30)
30
+ resp.raise_for_status()
31
+ data = resp.json()
32
+ lh = data.get("lighthouseResult", {})
33
+ cats = lh.get("categories", {})
34
+ audits = lh.get("audits", {})
35
+
36
+ # Build scores, default missing/unparsable → 100.0
37
+ scores = {}
38
+ for cat in self.EXPECTED_CATEGORIES:
39
+ raw = cats.get(cat, {}).get("score")
40
+ if isinstance(raw, (int, float)):
41
+ scores[cat] = round(raw * 100, 1)
42
+ else:
43
+ scores[cat] = 100.0
44
+
45
+ # Collect audits < 100% for suggestions
46
+ audit_suggestions = {}
47
+ for audit_id, info in audits.items():
48
+ sc = info.get("score")
49
+ if isinstance(sc, (int, float)) and sc < 1:
50
+ audit_suggestions[audit_id] = info.get("displayValue", "").strip()
51
+
52
+ return {
53
+ "scores": scores,
54
+ "audit_suggestions": audit_suggestions
55
+ }
56
+
57
+ except requests.exceptions.RequestException as e:
58
+ # Log the error and return an all-100% default, with no suggestions
59
+ print(f"[PerformanceAgent] PSI API error: {e}")
60
+ return {
61
+ "scores": {cat: 100.0 for cat in self.EXPECTED_CATEGORIES},
62
+ "audit_suggestions": {}
63
+ }