Create gemini_report.py
Browse files- gemini_report.py +90 -0
gemini_report.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import google.generativeai as genai
|
3 |
+
from config import GEMINI_API_KEY
|
4 |
+
from models import PageSpeedRequest
|
5 |
+
|
6 |
+
def generate_report_with_gemini(pagespeed_data: dict) -> str:
|
7 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
8 |
+
model = genai.GenerativeModel("gemini-2.0-flash")
|
9 |
+
|
10 |
+
prompt = (
|
11 |
+
"**Role:** You are an **Expert Web Performance Optimization Analyst and Senior Full-Stack Engineer** "
|
12 |
+
"with deep expertise in interpreting Google PageSpeed Insights data, diagnosing frontend and "
|
13 |
+
"backend bottlenecks, and devising actionable, high-impact optimization strategies.\n\n"
|
14 |
+
"**Objective:**\n"
|
15 |
+
"Analyze the provided Google PageSpeed Insights JSON data for the analyzed website. "
|
16 |
+
"Your primary goal is to generate a comprehensive, prioritized, and actionable set of strategies "
|
17 |
+
"to significantly improve its performance. These strategies must directly address the specific "
|
18 |
+
"metrics and audit findings within the report, aiming to elevate both Core Web Vitals "
|
19 |
+
"(LCP, INP, CLS) and other key performance indicators (FCP, TTFB, TBT), and ultimately "
|
20 |
+
"improve the `overall_category` to 'FAST' where possible.\n\n"
|
21 |
+
"**Input Data:**\n"
|
22 |
+
"The following JSON object contains the complete PageSpeed Insights report:\n"
|
23 |
+
f"```json\n{json.dumps(pagespeed_data, indent=2)}\n```\n\n"
|
24 |
+
"**Analysis and Strategy Formulation - Instructions:**\n\n"
|
25 |
+
"1. **Executive Performance Summary:**\n"
|
26 |
+
" * Begin with a concise overview of the website's current performance status based on the provided data.\n"
|
27 |
+
" * Highlight the `overall_category` for both `loadingExperience` (specific URL) and `originLoadingExperience` (entire origin).\n"
|
28 |
+
" * Pinpoint the current values and `category` (e.g., FAST, AVERAGE, SLOW) for each key metric:\n"
|
29 |
+
" * `CUMULATIVE_LAYOUT_SHIFT_SCORE` (CLS)\n"
|
30 |
+
" * `EXPERIMENTAL_TIME_TO_FIRST_BYTE` (TTFB)\n"
|
31 |
+
" * `FIRST_CONTENTFUL_PAINT_MS` (FCP)\n"
|
32 |
+
" * `INTERACTION_TO_NEXT_PAINT` (INP)\n"
|
33 |
+
" * `LARGEST_CONTENTFUL_PAINT_MS` (LCP)\n"
|
34 |
+
" * `total-blocking-time` (TBT) from Lighthouse.\n"
|
35 |
+
" * Identify any significant `metricSavings` opportunities highlighted in the Lighthouse `audits`.\n\n"
|
36 |
+
"2. **Deep-Dive into Bottlenecks & Audit Failures:**\n"
|
37 |
+
" * Systematically go through the `loadingExperience`, `originLoadingExperience`, and `lighthouseResult` (especially the `audits` section).\n"
|
38 |
+
" * For each underperforming metric or failed/suboptimal audit (e.g., Lighthouse scores less than 1, or `notApplicable` audits with clear improvement paths like `lcp-lazy-loaded`, `critical-request-chains`, `dom-size`, `non-composited-animations`), extract the relevant details, display values, and numeric values.\n\n"
|
39 |
+
"3. **Develop Prioritized, Actionable Optimization Strategies:**\n"
|
40 |
+
" For *each* identified performance issue or opportunity, provide the following:\n"
|
41 |
+
" * **A. Issue & Evidence:** Clearly state the problem (e.g., \"High Total Blocking Time,\" \"Suboptimal Largest Contentful Paint due to unoptimized image,\" \"Excessive DOM Size,\" \"Render-blocking resources in critical request chain\"). Refer directly to the JSON data points and audit IDs that support this finding (e.g., `audits['total-blocking-time'].numericValue`, `audits['critical-request-chains'].details.longestChain`).\n"
|
42 |
+
" * **B. Root Cause Analysis (Inferred):** Briefly explain the likely technical reasons behind the issue based on the data.\n"
|
43 |
+
" * **C. Specific, Technical Recommendation(s):** Provide detailed, actionable steps a development team can take. Be specific.\n"
|
44 |
+
" * **D. Targeted Metric Improvement:** Specify which primary and secondary metrics this strategy will positively impact (e.g., \"This will directly reduce LCP and improve FCP,\" or \"This will significantly lower TBT and improve INP.\").\n"
|
45 |
+
" * **E. Priority Level:** Assign a priority (High, Medium, Low) based on:\n"
|
46 |
+
" * Impact on Core Web Vitals.\n"
|
47 |
+
" * Potential for overall score improvement (consider `metricSavings`).\n"
|
48 |
+
" * Severity of the issue (e.g., 'SLOW' or 'AVERAGE' categories).\n"
|
49 |
+
" * Estimated implementation effort (favor high-impact, low/medium-effort tasks for higher priority).\n"
|
50 |
+
" * **F. Justification for Priority:** Briefly explain why this priority was assigned.\n\n"
|
51 |
+
"4. **Strategic Grouping (Optional but Recommended):**\n"
|
52 |
+
" If applicable, group recommendations by area (e.g., Asset Optimization, JavaScript Optimization, Server-Side Improvements, Rendering Path Optimization, CSS Enhancements).\n\n"
|
53 |
+
"5. **Anticipated Overall Impact:**\n"
|
54 |
+
" Conclude with a statement on the anticipated overall improvement in performance and user experience if the high and medium-priority recommendations are implemented.\n\n"
|
55 |
+
"**Output Format:**\n"
|
56 |
+
"Please structure your response clearly. Use headings, subheadings, and bullet points to enhance readability and actionability. For example:\n\n"
|
57 |
+
"---\n"
|
58 |
+
"## Executive Performance Summary\n"
|
59 |
+
"* **Overall URL Loading Experience Category:** [e.g., AVERAGE]\n"
|
60 |
+
"* **Overall Origin Loading Experience Category:** [e.g., AVERAGE]\n"
|
61 |
+
"* **Key Metrics:**\n"
|
62 |
+
" * LCP: [Value] ms ([Category])\n"
|
63 |
+
" * INP: [Value] ms ([Category])\n"
|
64 |
+
" * ...etc.\n\n"
|
65 |
+
"---\n"
|
66 |
+
"## Prioritized Optimization Strategies\n\n"
|
67 |
+
"### High Priority\n"
|
68 |
+
"**1. Issue & Evidence:** [e.g., High Total Blocking Time (TBT) of 1200 ms - `audits['total-blocking-time'].numericValue`]\n"
|
69 |
+
" * **Root Cause Analysis:** [e.g., Long JavaScript tasks on the main thread during page load, likely from unoptimized third-party scripts or complex component rendering.]\n"
|
70 |
+
" * **Specific, Technical Recommendation(s):**\n"
|
71 |
+
" * [Action 1]\n"
|
72 |
+
" * [Action 2]\n"
|
73 |
+
" * **Targeted Metric Improvement:** [e.g., TBT, INP, FCP]\n"
|
74 |
+
" * **Justification for Priority:** [e.g., Directly impacts interactivity (INP) and is a significant contributor to a poor lab score.]\n\n"
|
75 |
+
"**(Continue with other High, Medium, and Low priority items)**\n"
|
76 |
+
"---\n\n"
|
77 |
+
"**Ensure your analysis is based *solely* on the provided JSON data and your expert interpretation of it. "
|
78 |
+
"Avoid generic advice; all recommendations must be tied to specific findings within the report. "
|
79 |
+
"Do not add anything irrelevant in the report.**"
|
80 |
+
)
|
81 |
+
try:
|
82 |
+
response = model.generate_content(prompt)
|
83 |
+
if response and hasattr(response, "text"):
|
84 |
+
return response.text
|
85 |
+
elif response and getattr(response, "candidates", None):
|
86 |
+
if response.candidates[0].finish_reason == "SAFETY":
|
87 |
+
return "Report generation was blocked due to safety settings."
|
88 |
+
return "Report generation failed or returned an incomplete response."
|
89 |
+
except Exception as e:
|
90 |
+
return f"An error occurred during report generation: {str(e)}"
|