#!/usr/bin/env python3 """Analyze a Google Search Console generative AI performance report export. From Promptly Found's guide "How to analyze the Search Console generative AI report": https://promptlyfound.com/measurement/analyze-search-console-ai-report The script reads the export (an .xlsx file, the .zip file of CSV files, or a folder with the CSV files) and writes a results workbook and PNG charts. It runs these analyses: Summary totals, dates and the filters of the export Weekly weekly totals (Sunday to Saturday, as in Search Console) and week-on-week change Weekdays average clicks and impressions for each day of the week CTR quadrant pages by impressions and CTR: which pages are seen in AI features but rarely clicked Page groups totals for each group of pages, by URL pattern Movers pages that gained or lost the most clicks (needs --previous) Countries country mix of clicks and impressions Devices device mix of clicks and impressions AI share share of each page's Web search impressions that come from AI features (needs --web) Checks data checks: chart against table totals, row limit, filters, missing days Usage: python analyze_gsc_ai_report.py EXPORT [--previous EXPORT] [--web EXPORT] [--out DIR] [--groups "Guides=/guides/;Shop=/shop/|/products/"] [--min-impressions 100] [--top 10] [--quiet] EXPORT the generative AI report export for the period to analyze --previous the same report exported for an earlier period of the same length (for movers) --web the Performance report export (search type Web) for the same dates and search type (for AI share) --groups page groups as Name=pattern pairs. A pattern is a regular expression matched against the URL path. Separate groups with ";" and patterns in one group with "|". The first group that matches wins. Without --groups, each page goes in the group of its first folder (/guides/, /shop/ ...). Requirements: Python 3.9 or later, pandas and openpyxl. The PNG charts need matplotlib. Without it, the script skips the PNG files and still writes the workbook, which has its own charts. The script computes CTR from clicks and impressions. It does not average CTR values. It reads only the files you give it and sends nothing anywhere. License: CC BY 4.0, Promptly Found. """ import argparse import re import sys import warnings import zipfile from io import BytesIO from pathlib import Path from urllib.parse import urlparse import pandas as pd # Search Console files have no default style. openpyxl warns about it, and the warning means nothing here. warnings.filterwarnings("ignore", message="Workbook contains no default style") SHEETS = {"chart": ("chart", "dates"), "pages": ("pages",), "countries": ("countr",), "devices": ("device",), "filters": ("filter",)} # ----------------------------------------------------------------------------------------------- Reading the export def _sheet_key(name): low = name.lower() for key, hints in SHEETS.items(): if any(h in low for h in hints): return key return None def _read_csv(data): for enc in ("utf-8-sig", "utf-16", "latin-1"): try: return pd.read_csv(BytesIO(data), encoding=enc, dtype=str, keep_default_na=False) except (UnicodeError, pd.errors.ParserError): continue raise ValueError("could not read a CSV file in the export") def read_export(path): """Return the sheets of an export as {key: DataFrame}. Keys: chart, pages, countries, devices, filters.""" path = Path(path) raw = {} if path.is_dir(): for f in sorted(path.glob("*.csv")): raw[f.stem] = _read_csv(f.read_bytes()) elif path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as z: for n in z.namelist(): if n.lower().endswith(".csv"): raw[Path(n).stem] = _read_csv(z.read(n)) elif path.suffix.lower() in (".xlsx", ".xlsm", ".xls"): raw = pd.read_excel(path, sheet_name=None, dtype=object) else: raise SystemExit(f"{path}: use the .xlsx file, the .zip file of CSV files, or a folder of CSV files") out = {} for name, df in raw.items(): key = _sheet_key(name) if key and key not in out: out[key] = df if "chart" not in out and "pages" not in out: raise SystemExit(f"{path}: found no Chart or Pages sheet (sheets: {', '.join(raw)})") return out def _number(s): """Numbers as Search Console writes them: 12, 12.0 or "1,234".""" return pd.to_numeric(s.astype(str).str.replace(",", "").str.strip().replace({"": None, "nan": None}), errors="coerce").fillna(0) def _ctr_value(v): """An exported CTR: a fraction (0.0123), a percent string ("1.23%") or empty.""" if v is None or (isinstance(v, float) and pd.isna(v)): return float("nan") if isinstance(v, str): v = v.strip() if not v: return float("nan") if v.endswith("%"): return float(v[:-1].replace(",", "")) / 100 return float(v.replace(",", "")) return float(v) def tidy(df): """Rename the columns to key, clicks, impressions, ctr_export (and position) and compute ctr.""" cols = {c: str(c).strip().lower() for c in df.columns} find = lambda word: next((c for c, low in cols.items() if word in low), None) clicks, impressions, ctr, position = find("click"), find("impression"), find("ctr"), find("position") if clicks is None or impressions is None: raise SystemExit(f"a sheet has no Clicks or Impressions column (columns: {', '.join(map(str, df.columns))})") t = pd.DataFrame({"key": df[df.columns[0]].astype(str).str.strip(), "clicks": _number(df[clicks]), "impressions": _number(df[impressions])}) t["ctr_export"] = df[ctr].map(_ctr_value) if ctr is not None else float("nan") if position is not None: t["position"] = _number(df[position]) t = t[t["key"].ne("") & t["key"].ne("nan")].reset_index(drop=True) t["ctr"] = ctr_of(t["clicks"], t["impressions"]) return t def ctr_of(clicks, impressions): return (clicks / impressions.where(impressions > 0)).astype(float) def filters_of(sheets): f = sheets.get("filters") if f is None or f.shape[1] < 2: return {} return {str(a).strip(): str(b).strip() for a, b in zip(f.iloc[:, 0], f.iloc[:, 1])} def load(path): sheets = read_export(path) data = {k: tidy(sheets[k]) for k in ("chart", "pages", "countries", "devices") if k in sheets} if "chart" in data: c = data["chart"] c["date"] = pd.to_datetime(c["key"], errors="coerce") data["chart"] = c.dropna(subset=["date"]).sort_values("date").reset_index(drop=True) data["filters"] = filters_of(sheets) data["source"] = Path(path).name return data # -------------------------------------------------------------------------------------------------------- Analyses def totals(df): c, i = df["clicks"].sum(), df["impressions"].sum() return {"clicks": c, "impressions": i, "ctr": c / i if i else float("nan")} def summary(cur, prev=None): rows = [("Export", cur["source"])] for k, v in cur["filters"].items(): rows.append((f"Filter: {k}", v)) if "chart" in cur: ch = cur["chart"] t = totals(ch) rows += [("First day", ch["date"].min().date().isoformat()), ("Last day", ch["date"].max().date().isoformat()), ("Days", len(ch)), ("Clicks (chart total)", t["clicks"]), ("Impressions (chart total)", t["impressions"]), ("CTR (chart total)", t["ctr"])] if prev is not None and "chart" in prev: p = totals(prev["chart"]) rows += [("Clicks, previous period", p["clicks"]), ("Impressions, previous period", p["impressions"]), ("CTR, previous period", p["ctr"]), ("Change in clicks", pct(t["clicks"], p["clicks"])), ("Change in impressions", pct(t["impressions"], p["impressions"]))] if "pages" in cur: rows.append(("Pages in the table", len(cur["pages"]))) return pd.DataFrame(rows, columns=["Item", "Value"]) def pct(new, old): return (new - old) / old if old else float("nan") def weekly(chart): c = chart.copy() # Search Console weeks run from Sunday to Saturday. Monday is weekday 0 in pandas. c["week_start"] = c["date"] - pd.to_timedelta((c["date"].dt.weekday + 1) % 7, unit="D") w = c.groupby("week_start").agg(days=("date", "count"), clicks=("clicks", "sum"), impressions=("impressions", "sum")).reset_index() w["week_end"] = w["week_start"] + pd.Timedelta(days=6) w["ctr"] = ctr_of(w["clicks"], w["impressions"]) w["complete"] = w["days"].eq(7) ok = w["complete"] & w["complete"].shift(1, fill_value=False) & w["week_start"].diff().eq(pd.Timedelta(days=7)) w["clicks_wow"] = (w["clicks"] / w["clicks"].shift(1) - 1).where(ok) w["impressions_wow"] = (w["impressions"] / w["impressions"].shift(1) - 1).where(ok) w["ctr_change_pts"] = ((w["ctr"] - w["ctr"].shift(1)) * 100).where(ok) return w[["week_start", "week_end", "days", "complete", "clicks", "impressions", "ctr", "clicks_wow", "impressions_wow", "ctr_change_pts"]] def weekdays(chart): c = chart.copy() c["weekday"] = c["date"].dt.day_name() order = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] g = c.groupby("weekday").agg(days=("date", "count"), clicks=("clicks", "sum"), impressions=("impressions", "sum")).reindex(order).dropna().reset_index() g["avg_clicks"] = g["clicks"] / g["days"] g["avg_impressions"] = g["impressions"] / g["days"] g["ctr"] = ctr_of(g["clicks"], g["impressions"]) g["clicks_vs_average"] = g["avg_clicks"] / g["avg_clicks"].mean() - 1 return g[["weekday", "days", "avg_clicks", "avg_impressions", "ctr", "clicks_vs_average"]] def quadrant(pages, min_impressions, groups=None): p = pages[pages["impressions"] >= min_impressions].copy() if p.empty: cols = ["page", "group", "quadrant", "clicks", "impressions", "ctr", "group_ctr", "ctr_vs_group", "clicks_below_average_ctr"] return pd.DataFrame(columns=cols), float("nan"), float("nan") imp_cut = p["impressions"].median() ctr_cut = p["clicks"].sum() / p["impressions"].sum() high_i, high_c = p["impressions"] >= imp_cut, p["ctr"] >= ctr_cut p["quadrant"] = "Rarely seen, rarely clicked" p.loc[high_i & high_c, "quadrant"] = "Seen and clicked" p.loc[high_i & ~high_c, "quadrant"] = "Seen, rarely clicked" p.loc[~high_i & high_c, "quadrant"] = "Rarely seen, well clicked" # Clicks the page would get at the CTR of the pages in the analysis. An estimate for sorting, not a forecast. p["clicks_below_average_ctr"] = (p["impressions"] * ctr_cut - p["clicks"]).clip(lower=0).round() # The CTR of the page's own group, so that a guide is also compared with other guides. p["group"] = p["key"].map(lambda u: group_of(u, groups)) g = p.groupby("group")[["clicks", "impressions"]].transform("sum") p["group_ctr"] = g["clicks"] / g["impressions"] p["ctr_vs_group"] = p["ctr"] / p["group_ctr"] - 1 order = {"Seen, rarely clicked": 0, "Seen and clicked": 1, "Rarely seen, well clicked": 2, "Rarely seen, rarely clicked": 3} p = p.sort_values(["quadrant", "clicks_below_average_ctr", "impressions"], key=lambda s: s.map(order) if s.name == "quadrant" else -s) p = p.rename(columns={"key": "page"})[["page", "group", "quadrant", "clicks", "impressions", "ctr", "group_ctr", "ctr_vs_group", "clicks_below_average_ctr"]] return p.reset_index(drop=True), imp_cut, ctr_cut def parse_groups(text): groups = [] for part in filter(None, (x.strip() for x in (text or "").split(";"))): name, _, pattern = part.partition("=") if not pattern: raise SystemExit(f'--groups: "{part}" has no "=". Use Name=pattern, for example Guides=/guides/') groups.append((name.strip(), re.compile(pattern.strip(), re.I))) return groups def group_of(url, groups): path = urlparse(url).path or "/" if groups: return next((name for name, rx in groups if rx.search(path)), "Other") first = path.strip("/").split("/")[0] if not first: return "Home page" return f"/{first}/" if "/" in path.strip("/") else "Other" def page_groups(pages, groups): p = pages.copy() p["group"] = p["key"].map(lambda u: group_of(u, groups)) g = p.groupby("group").agg(pages=("key", "count"), clicks=("clicks", "sum"), impressions=("impressions", "sum")).reset_index() g["ctr"] = ctr_of(g["clicks"], g["impressions"]) g["share_of_clicks"] = g["clicks"] / g["clicks"].sum() g["share_of_impressions"] = g["impressions"] / g["impressions"].sum() return g.sort_values("impressions", ascending=False).reset_index(drop=True), p def movers(cur_pages, prev_pages): a = cur_pages[["key", "clicks", "impressions"]].rename(columns={"clicks": "clicks_now", "impressions": "impressions_now"}) b = prev_pages[["key", "clicks", "impressions"]].rename(columns={"clicks": "clicks_before", "impressions": "impressions_before"}) m = a.merge(b, on="key", how="outer", indicator=True) m["status"] = m["_merge"].map({"both": "In both", "left_only": "New in this period", "right_only": "Not in this period"}) m = m.drop(columns="_merge").fillna({"clicks_now": 0, "impressions_now": 0, "clicks_before": 0, "impressions_before": 0}) m["click_change"] = m["clicks_now"] - m["clicks_before"] m["click_change_pct"] = (m["click_change"] / m["clicks_before"].where(m["clicks_before"] > 0)).astype(float) m["impression_change"] = m["impressions_now"] - m["impressions_before"] m["impression_change_pct"] = (m["impression_change"] / m["impressions_before"].where(m["impressions_before"] > 0)).astype(float) m["ctr_now"] = ctr_of(m["clicks_now"], m["impressions_now"]) m["ctr_before"] = ctr_of(m["clicks_before"], m["impressions_before"]) m = m.rename(columns={"key": "page"}) return m.sort_values(["click_change", "impression_change"], ascending=False).reset_index(drop=True) def mix(df, top, label, plural): d = df.sort_values(["clicks", "impressions"], ascending=False).reset_index(drop=True) if len(d) > top: rest = d.iloc[top:] other = {"key": f"All other {plural} ({len(rest)})", "clicks": rest["clicks"].sum(), "impressions": rest["impressions"].sum()} d = pd.concat([d.iloc[:top], pd.DataFrame([other])], ignore_index=True) d["ctr"] = ctr_of(d["clicks"], d["impressions"]) d["share_of_clicks"] = d["clicks"] / d["clicks"].sum() d["share_of_impressions"] = d["impressions"] / d["impressions"].sum() return d.rename(columns={"key": label})[[label, "clicks", "impressions", "ctr", "share_of_clicks", "share_of_impressions"]] def ai_share(ai_pages, web_pages, groups): a = ai_pages[["key", "clicks", "impressions"]].rename(columns={"clicks": "ai_clicks", "impressions": "ai_impressions"}) w = web_pages[["key", "clicks", "impressions"]].rename(columns={"clicks": "web_clicks", "impressions": "web_impressions"}) m = a.merge(w, on="key", how="left") m["ai_share_of_impressions"] = (m["ai_impressions"] / m["web_impressions"].where(m["web_impressions"] > 0)).astype(float) m["ai_share_of_clicks"] = (m["ai_clicks"] / m["web_clicks"].where(m["web_clicks"] > 0)).astype(float) m["note"] = "" m.loc[m["web_impressions"].isna(), "note"] = "Not in the Web export (row limit or another URL)" m.loc[m["ai_share_of_impressions"] > 1, "note"] = "Above 100%: check that both exports use the same dates and search type" m["group"] = m["key"].map(lambda u: group_of(u, groups)) m = m.rename(columns={"key": "page"}).sort_values("ai_impressions", ascending=False).reset_index(drop=True) ok = m[m["web_impressions"] > 0] g = ok.groupby("group").agg(pages=("page", "count"), ai_impressions=("ai_impressions", "sum"), web_impressions=("web_impressions", "sum"), ai_clicks=("ai_clicks", "sum"), web_clicks=("web_clicks", "sum")).reset_index() g["ai_share_of_impressions"] = g["ai_impressions"] / g["web_impressions"] g["ai_share_of_clicks"] = g["ai_clicks"] / g["web_clicks"].where(g["web_clicks"] > 0) return m, g.sort_values("ai_impressions", ascending=False).reset_index(drop=True) def checks(cur, prev=None, web=None): rows = [] add = lambda check, result, note="": rows.append((check, result, note)) if "chart" in cur: ch = cur["chart"] t = totals(ch) span = pd.date_range(ch["date"].min(), ch["date"].max()) missing = len(span) - ch["date"].nunique() add("Days in the chart", len(ch), f"{missing} missing days" if missing else "No missing days") zero = int((ch["impressions"] == 0).sum()) add("Days with no impressions", zero, "CTR is empty on these days in the export" if zero else "") for k in ("pages", "countries", "devices"): if k in cur: s = totals(cur[k]) add(f"{k.title()} table: clicks against chart total", f"{pct(s['clicks'], t['clicks']):+.1%}", "By page, each URL counts on its own, so the table total is often higher" if k == "pages" else "Grouped by property, as the chart") add(f"{k.title()} table: impressions against chart total", f"{pct(s['impressions'], t['impressions']):+.1%}", "") if "pages" in cur: n = len(cur["pages"]) add("Rows in the Pages table", n, "1,000 is the export limit: pages after row 1,000 are missing" if n >= 1000 else "") bad = cur["pages"]["ctr_export"].notna() & (cur["pages"]["ctr_export"] - cur["pages"]["ctr"].fillna(0)).abs().gt(0.0005) add("Exported CTR that does not match clicks / impressions", int(bad.sum()), "The script uses clicks / impressions") add("Search type", cur["filters"].get("Search type", "not in the export"), "") add("Date filter", cur["filters"].get("Date", "not in the export"), "") for name, other in (("previous", prev), ("web", web)): if other is None: continue a, b = cur["filters"].get("Search type"), other["filters"].get("Search type") add(f"Search type of the {name} export", b or "not in the export", "Same as the main export" if a == b else "Different from the main export: results are not comparable") if name == "previous" and "chart" in other and "chart" in cur: add("Days in the previous export", len(other["chart"]), "Same length" if len(other["chart"]) == len(cur["chart"]) else "Different length: compare daily averages") return pd.DataFrame(rows, columns=["Check", "Result", "Note"]) # ---------------------------------------------------------------------------------------------------------- Output PCT_COLS = ("ctr", "share", "_wow", "_pct", "vs_average", "vs_group") def write_workbook(path, frames): from openpyxl.chart import BarChart, LineChart, Reference from openpyxl.utils import get_column_letter with pd.ExcelWriter(path, engine="openpyxl") as xw: for name, df in frames.items(): df.to_excel(xw, sheet_name=name, index=False) ws = xw.sheets[name] ws.freeze_panes = "A2" for j, col in enumerate(df.columns, start=1): letter = get_column_letter(j) width = max([len(str(col))] + [len(str(v)) for v in df[col].head(200)]) ws.column_dimensions[letter].width = min(max(10, width + 2), 70) col_l = str(col).lower() fmt = None if any(k in col_l for k in PCT_COLS) and not col_l.endswith("_pts"): fmt = "0.00%" elif df[col].dtype.kind == "f": fmt = "#,##0.##" if col_l.endswith("_pts") else "#,##0" elif df[col].dtype.kind == "M": fmt = "yyyy-mm-dd" if fmt: for cell in ws[letter][1:]: cell.number_format = fmt if "Weekly" in frames and len(frames["Weekly"]): ws, n = xw.sheets["Weekly"], len(frames["Weekly"]) + 1 ch = LineChart(); ch.title = "Weekly clicks"; ch.height, ch.width = 8, 18 ch.add_data(Reference(ws, min_col=5, min_row=1, max_row=n), titles_from_data=True) ch.set_categories(Reference(ws, min_col=1, min_row=2, max_row=n)) ws.add_chart(ch, "L2") ch2 = LineChart(); ch2.title = "Weekly impressions"; ch2.height, ch2.width = 8, 18 ch2.add_data(Reference(ws, min_col=6, min_row=1, max_row=n), titles_from_data=True) ch2.set_categories(Reference(ws, min_col=1, min_row=2, max_row=n)) ws.add_chart(ch2, "L19") if "Page groups" in frames and len(frames["Page groups"]): ws, n = xw.sheets["Page groups"], len(frames["Page groups"]) + 1 ch = BarChart(); ch.type = "bar"; ch.title = "Share of AI impressions and clicks by page group" ch.height, ch.width = 8, 18 ch.add_data(Reference(ws, min_col=6, max_col=7, min_row=1, max_row=n), titles_from_data=True) ch.set_categories(Reference(ws, min_col=1, min_row=2, max_row=n)) ws.add_chart(ch, "J2") def write_pngs(out, wk, quad, cuts, groups, countries): try: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt except ImportError: return [] files = [] ink, accent, grey = "#1f1f1f", "#8a1c3b", "#9a9a9a" plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False}) if wk is not None and len(wk): fig, ax = plt.subplots(figsize=(9, 4)) colors = [accent if c else grey for c in wk["complete"]] ax.bar(wk["week_start"].dt.strftime("%b %d"), wk["clicks"], color=colors) ax.set_title("Clicks from AI features by week (grey: partial week)", loc="left", color=ink) ax.tick_params(axis="x", rotation=45) ax2 = ax.twinx(); ax2.plot(wk["week_start"].dt.strftime("%b %d"), wk["impressions"], color=ink, marker="o", lw=1.5) ax2.set_ylabel("Impressions"); ax.set_ylabel("Clicks"); ax2.spines["top"].set_visible(False) fig.tight_layout(); f = out / "weekly.png"; fig.savefig(f, dpi=150); plt.close(fig); files.append(f) if quad is not None and len(quad): fig, ax = plt.subplots(figsize=(7, 5)) seen = quad["quadrant"].eq("Seen, rarely clicked") ax.scatter(quad.loc[~seen, "impressions"], quad.loc[~seen, "ctr"] * 100, color=grey, s=22, label="Other pages") ax.scatter(quad.loc[seen, "impressions"], quad.loc[seen, "ctr"] * 100, color=accent, s=30, label="Seen, rarely clicked") ax.axvline(cuts[0], color=ink, lw=.8, ls="--"); ax.axhline(cuts[1] * 100, color=ink, lw=.8, ls="--") ax.set_xscale("log"); ax.set_xlabel("Impressions in AI features (log scale)"); ax.set_ylabel("CTR (%)") ax.set_title("Pages by impressions and CTR", loc="left", color=ink); ax.legend(frameon=False) fig.tight_layout(); f = out / "ctr-quadrant.png"; fig.savefig(f, dpi=150); plt.close(fig); files.append(f) if groups is not None and len(groups): fig, ax = plt.subplots(figsize=(7, 0.6 * len(groups) + 1.5)) y = range(len(groups)) ax.barh([i + .2 for i in y], groups["share_of_impressions"] * 100, height=.4, color=grey, label="Impressions") ax.barh([i - .2 for i in y], groups["share_of_clicks"] * 100, height=.4, color=accent, label="Clicks") ax.set_yticks(list(y), groups["group"]); ax.invert_yaxis(); ax.set_xlabel("Share (%)") ax.set_title("Share of AI impressions and clicks by page group", loc="left", color=ink); ax.legend(frameon=False) fig.tight_layout(); f = out / "page-groups.png"; fig.savefig(f, dpi=150); plt.close(fig); files.append(f) if countries is not None and len(countries): c = countries.iloc[::-1] fig, ax = plt.subplots(figsize=(7, 0.35 * len(c) + 1.5)) ax.barh(c.iloc[:, 0], c["share_of_clicks"] * 100, color=accent) ax.set_xlabel("Share of clicks (%)"); ax.set_title("Clicks from AI features by country", loc="left", color=ink) fig.tight_layout(); f = out / "countries.png"; fig.savefig(f, dpi=150); plt.close(fig); files.append(f) return files def main(argv=None): ap = argparse.ArgumentParser(description="Analyze a Search Console generative AI performance report export.") ap.add_argument("export", help="the export: .xlsx file, .zip file of CSV files, or folder of CSV files") ap.add_argument("--previous", help="the same report exported for an earlier period of the same length") ap.add_argument("--web", help="the Performance report export (Web search type) for the same dates") ap.add_argument("--out", default="gsc-ai-results", help="output folder (default: gsc-ai-results)") ap.add_argument("--groups", help='page groups, for example "Guides=/guides/;Shop=/shop/|/products/"') ap.add_argument("--min-impressions", type=float, default=100, help="pages with fewer impressions are left out " "of the CTR quadrant (default: 100)") ap.add_argument("--top", type=int, default=10, help="rows in the top lists (default: 10)") ap.add_argument("--quiet", action="store_true", help="print nothing but errors") a = ap.parse_args(argv) cur = load(a.export) prev = load(a.previous) if a.previous else None web = load(a.web) if a.web else None groups = parse_groups(a.groups) out = Path(a.out); out.mkdir(parents=True, exist_ok=True) frames = {"Summary": summary(cur, prev)} wk = quad = grp = ctry = None cuts = (float("nan"), float("nan")) if "chart" in cur: wk = weekly(cur["chart"]); frames["Weekly"] = wk frames["Weekdays"] = weekdays(cur["chart"]) if "pages" in cur: quad, imp_cut, ctr_cut = quadrant(cur["pages"], a.min_impressions, groups); cuts = (imp_cut, ctr_cut) frames["CTR quadrant"] = quad grp, _ = page_groups(cur["pages"], groups); frames["Page groups"] = grp if prev is not None and "pages" in prev: mv = movers(cur["pages"], prev["pages"]) frames["Movers"] = mv frames["Top gainers"] = mv.head(a.top) frames["Top losers"] = mv.sort_values(["click_change", "impression_change"]).head(a.top) if web is not None and "pages" in web: share, share_g = ai_share(cur["pages"], web["pages"], groups) frames["AI share"] = share frames["AI share by group"] = share_g if "countries" in cur: ctry = mix(cur["countries"], a.top, "country", "countries"); frames["Countries"] = ctry if "devices" in cur: frames["Devices"] = mix(cur["devices"], a.top, "device", "devices") frames["Checks"] = checks(cur, prev, web) if quad is not None and quad.empty: frames["Checks"].loc[len(frames["Checks"])] = [ "Pages in the CTR quadrant", 0, f"No page has {a.min_impressions:,.0f} impressions: run again with a lower " "--min-impressions"] book = out / "gsc-ai-results.xlsx" write_workbook(book, frames) pngs = write_pngs(out, wk, quad, cuts, grp, ctry) if not a.quiet: pd.set_option("display.width", 160, "display.max_columns", 20, "display.max_colwidth", 70) print(frames["Summary"].to_string(index=False)) for name in ("Weekly", "Page groups", "Countries", "Devices", "Checks"): if name in frames: print(f"\n{name}\n{frames[name].to_string(index=False)}") if quad is not None and len(quad): print(f"\nSeen, rarely clicked (impressions >= {cuts[0]:,.0f}, CTR < {cuts[1]:.2%})") print(quad[quad["quadrant"].eq("Seen, rarely clicked")].head(a.top).to_string(index=False)) print(f"\nWrote {book}" + "".join(f"\nWrote {f}" for f in pngs)) if not pngs: print("No PNG charts: install matplotlib to get them (pip install matplotlib).") return 0 if __name__ == "__main__": sys.exit(main())