gsc-cli 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gsc/__init__.py +9 -0
- gsc/auth.py +178 -0
- gsc/benchmarks.py +34 -0
- gsc/cli/__init__.py +3 -0
- gsc/cli/auth_cmd.py +147 -0
- gsc/cli/genai.py +240 -0
- gsc/cli/inspect_cmd.py +26 -0
- gsc/cli/main.py +52 -0
- gsc/cli/multimodal.py +203 -0
- gsc/cli/query.py +108 -0
- gsc/cli/sitemaps.py +62 -0
- gsc/cli/sites.py +54 -0
- gsc/client.py +90 -0
- gsc/data/seo-benchmarks.json +54 -0
- gsc/formatters.py +55 -0
- gsc/models.py +178 -0
- gsc_cli-0.2.0.dist-info/METADATA +173 -0
- gsc_cli-0.2.0.dist-info/RECORD +21 -0
- gsc_cli-0.2.0.dist-info/WHEEL +4 -0
- gsc_cli-0.2.0.dist-info/entry_points.txt +2 -0
- gsc_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
gsc/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""gsc-cli: Google Search Console CLI and SEO-analysis backend."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from gsc.benchmarks import expected_ctr, is_ctr_opportunity, load_benchmarks
|
|
6
|
+
|
|
7
|
+
__version__ = "0.2.0"
|
|
8
|
+
|
|
9
|
+
__all__ = ["__version__", "load_benchmarks", "expected_ctr", "is_ctr_opportunity"]
|
gsc/auth.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""OAuth2 + service-account auth and a YAML-backed profile store.
|
|
2
|
+
|
|
3
|
+
Profiles live in ``config.yaml`` under a top-level ``profiles:`` mapping. Each
|
|
4
|
+
profile records its ``auth_type``, a ``credentials`` path, and an optional list
|
|
5
|
+
of ``sites`` used for profile auto-detection from a target site URL.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
from google.oauth2 import service_account
|
|
15
|
+
from google.oauth2.credentials import Credentials
|
|
16
|
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
17
|
+
|
|
18
|
+
from .models import Profile
|
|
19
|
+
|
|
20
|
+
SCOPES_READONLY = ["https://www.googleapis.com/auth/webmasters.readonly"]
|
|
21
|
+
SCOPES_READWRITE = ["https://www.googleapis.com/auth/webmasters"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _config_dir() -> Path:
|
|
25
|
+
override = os.environ.get("GSC_CONFIG_DIR")
|
|
26
|
+
if override:
|
|
27
|
+
return Path(override).expanduser()
|
|
28
|
+
return Path.home() / ".config" / "gsc"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
CONFIG_DIR = _config_dir()
|
|
32
|
+
CONFIG_PATH = CONFIG_DIR / "config.yaml"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_config(config_path: Path | str | None = None) -> dict:
|
|
36
|
+
"""Load the profile store, returning ``{"profiles": {}}`` if absent."""
|
|
37
|
+
path = Path(config_path) if config_path else CONFIG_PATH
|
|
38
|
+
if not path.exists():
|
|
39
|
+
return {"profiles": {}}
|
|
40
|
+
with path.open("r", encoding="utf-8") as fh:
|
|
41
|
+
data = yaml.safe_load(fh) or {}
|
|
42
|
+
data.setdefault("profiles", {})
|
|
43
|
+
return data
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def save_config(config: dict, config_path: Path | str | None = None) -> None:
|
|
47
|
+
"""Persist the profile store, creating the config dir if needed."""
|
|
48
|
+
path = Path(config_path) if config_path else CONFIG_PATH
|
|
49
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
with path.open("w", encoding="utf-8") as fh:
|
|
51
|
+
yaml.safe_dump(config, fh, default_flow_style=False, sort_keys=True)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def list_profiles(config_path: Path | str | None = None) -> list[Profile]:
|
|
55
|
+
"""Return every stored profile."""
|
|
56
|
+
config = load_config(config_path)
|
|
57
|
+
profiles = []
|
|
58
|
+
for name, data in config.get("profiles", {}).items():
|
|
59
|
+
entry = dict(data or {})
|
|
60
|
+
entry["name"] = name
|
|
61
|
+
profiles.append(Profile.from_api(entry))
|
|
62
|
+
return profiles
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_profile(name: str, config_path: Path | str | None = None) -> Profile | None:
|
|
66
|
+
"""Return a profile by name, or ``None`` if it does not exist."""
|
|
67
|
+
config = load_config(config_path)
|
|
68
|
+
data = config.get("profiles", {}).get(name)
|
|
69
|
+
if data is None:
|
|
70
|
+
return None
|
|
71
|
+
entry = dict(data)
|
|
72
|
+
entry["name"] = name
|
|
73
|
+
return Profile.from_api(entry)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve_profile(
|
|
77
|
+
name: str | None = None,
|
|
78
|
+
site_url: str | None = None,
|
|
79
|
+
config_path: Path | str | None = None,
|
|
80
|
+
) -> Profile | None:
|
|
81
|
+
"""Resolve a profile by precedence: explicit name, site-URL match, default.
|
|
82
|
+
|
|
83
|
+
1. If ``name`` is given, return that profile (or ``None`` if missing).
|
|
84
|
+
2. Else if ``site_url`` matches a profile's ``sites`` list, return it.
|
|
85
|
+
3. Else fall back to the ``default`` profile.
|
|
86
|
+
"""
|
|
87
|
+
if name:
|
|
88
|
+
return get_profile(name, config_path)
|
|
89
|
+
|
|
90
|
+
if site_url:
|
|
91
|
+
for profile in list_profiles(config_path):
|
|
92
|
+
if site_url in profile.sites:
|
|
93
|
+
return profile
|
|
94
|
+
|
|
95
|
+
return get_profile("default", config_path)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def add_service_account_profile(
|
|
99
|
+
name: str,
|
|
100
|
+
credentials: str,
|
|
101
|
+
sites: list[str] | None = None,
|
|
102
|
+
config_path: Path | str | None = None,
|
|
103
|
+
) -> Profile:
|
|
104
|
+
"""Create / overwrite a service-account profile and persist it."""
|
|
105
|
+
config = load_config(config_path)
|
|
106
|
+
config.setdefault("profiles", {})[name] = {
|
|
107
|
+
"auth_type": "service_account",
|
|
108
|
+
"credentials": str(credentials),
|
|
109
|
+
"sites": list(sites or []),
|
|
110
|
+
}
|
|
111
|
+
save_config(config, config_path)
|
|
112
|
+
return Profile(
|
|
113
|
+
name=name,
|
|
114
|
+
auth_type="service_account",
|
|
115
|
+
credentials=str(credentials),
|
|
116
|
+
sites=list(sites or []),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def remove_profile(name: str, config_path: Path | str | None = None) -> bool:
|
|
121
|
+
"""Remove a profile by name; return ``True`` if one was removed."""
|
|
122
|
+
config = load_config(config_path)
|
|
123
|
+
profiles = config.get("profiles", {})
|
|
124
|
+
if name not in profiles:
|
|
125
|
+
return False
|
|
126
|
+
del profiles[name]
|
|
127
|
+
save_config(config, config_path)
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def get_credentials(profile: Profile, writable: bool = False):
|
|
132
|
+
"""Build Google credentials for ``profile``.
|
|
133
|
+
|
|
134
|
+
OAuth profiles load the saved authorized-user token. Service accounts pick
|
|
135
|
+
the scope based on ``writable``.
|
|
136
|
+
"""
|
|
137
|
+
if profile.is_service_account:
|
|
138
|
+
scopes = SCOPES_READWRITE if writable else SCOPES_READONLY
|
|
139
|
+
return service_account.Credentials.from_service_account_file(
|
|
140
|
+
profile.credentials, scopes=scopes
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
token_path = (
|
|
144
|
+
Path(profile.credentials)
|
|
145
|
+
if profile.credentials
|
|
146
|
+
else (CONFIG_DIR / "oauth" / "default.json")
|
|
147
|
+
)
|
|
148
|
+
return Credentials.from_authorized_user_file(str(token_path), SCOPES_READWRITE)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def run_oauth_flow(
|
|
152
|
+
client_secrets: str,
|
|
153
|
+
config_path: Path | str | None = None,
|
|
154
|
+
) -> Profile:
|
|
155
|
+
"""Run the InstalledAppFlow, save the token, and write the ``default`` profile."""
|
|
156
|
+
flow = InstalledAppFlow.from_client_secrets_file(client_secrets, SCOPES_READWRITE)
|
|
157
|
+
creds = flow.run_local_server(port=0)
|
|
158
|
+
|
|
159
|
+
token_dir = CONFIG_DIR / "oauth"
|
|
160
|
+
token_dir.mkdir(parents=True, exist_ok=True)
|
|
161
|
+
token_path = token_dir / "default.json"
|
|
162
|
+
with token_path.open("w", encoding="utf-8") as fh:
|
|
163
|
+
fh.write(creds.to_json())
|
|
164
|
+
|
|
165
|
+
config = load_config(config_path)
|
|
166
|
+
config.setdefault("profiles", {})["default"] = {
|
|
167
|
+
"auth_type": "oauth2",
|
|
168
|
+
"credentials": str(token_path),
|
|
169
|
+
"sites": [],
|
|
170
|
+
}
|
|
171
|
+
save_config(config, config_path)
|
|
172
|
+
|
|
173
|
+
return Profile(
|
|
174
|
+
name="default",
|
|
175
|
+
auth_type="oauth2",
|
|
176
|
+
credentials=str(token_path),
|
|
177
|
+
sites=[],
|
|
178
|
+
)
|
gsc/benchmarks.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Loader for the bundled open SEO benchmarks dataset.
|
|
2
|
+
|
|
3
|
+
The dataset (``gsc/data/seo-benchmarks.json``) is CC BY 4.0 — attribution to the
|
|
4
|
+
source is required when you reuse it. See ``data/README.md`` in the repository.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from importlib import resources
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@lru_cache(maxsize=1)
|
|
16
|
+
def load_benchmarks() -> dict[str, Any]:
|
|
17
|
+
"""Return the bundled SEO benchmarks dataset as a dict."""
|
|
18
|
+
data = resources.files("gsc.data").joinpath("seo-benchmarks.json").read_text("utf-8")
|
|
19
|
+
return json.loads(data)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def expected_ctr(position: int) -> float | None:
|
|
23
|
+
"""Expected organic CTR (fraction) for a 1-based ranking ``position``.
|
|
24
|
+
|
|
25
|
+
Returns ``None`` for positions outside the benchmarked 1-10 range.
|
|
26
|
+
"""
|
|
27
|
+
values = load_benchmarks()["ctr_by_position"]["values"]
|
|
28
|
+
return values.get(str(position))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def is_ctr_opportunity(position: int, actual_ctr: float, tolerance: float = 0.7) -> bool:
|
|
32
|
+
"""True if ``actual_ctr`` is materially below the expected band for ``position``."""
|
|
33
|
+
expected = expected_ctr(position)
|
|
34
|
+
return expected is not None and actual_ctr < expected * tolerance
|
gsc/cli/__init__.py
ADDED
gsc/cli/auth_cmd.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""``gsc auth`` command group and a ``--config-path`` decorator for test isolation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from ..auth import (
|
|
11
|
+
CONFIG_PATH,
|
|
12
|
+
add_service_account_profile,
|
|
13
|
+
get_credentials,
|
|
14
|
+
list_profiles,
|
|
15
|
+
remove_profile,
|
|
16
|
+
resolve_profile,
|
|
17
|
+
run_oauth_flow,
|
|
18
|
+
)
|
|
19
|
+
from ..formatters import format_output
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _config_path_option(func):
|
|
23
|
+
"""Attach a ``--config-path`` option that flows into ``ctx.obj``."""
|
|
24
|
+
|
|
25
|
+
def callback(ctx: click.Context, param, value):
|
|
26
|
+
ctx.ensure_object(dict)
|
|
27
|
+
if value:
|
|
28
|
+
ctx.obj["config_path"] = value
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
return click.option(
|
|
32
|
+
"--config-path",
|
|
33
|
+
default=None,
|
|
34
|
+
expose_value=False,
|
|
35
|
+
is_eager=True,
|
|
36
|
+
callback=callback,
|
|
37
|
+
help="Override the config.yaml path (for testing / isolation).",
|
|
38
|
+
)(func)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _get_config_path(ctx: click.Context) -> Path:
|
|
42
|
+
"""Resolve the active config path from ctx.obj, else the default."""
|
|
43
|
+
path = ctx.obj.get("config_path") if ctx.obj else None
|
|
44
|
+
return Path(path) if path else CONFIG_PATH
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@click.group()
|
|
48
|
+
def auth() -> None:
|
|
49
|
+
"""Manage authentication and profiles."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@auth.command("login")
|
|
53
|
+
@_config_path_option
|
|
54
|
+
@click.option(
|
|
55
|
+
"--client-secrets",
|
|
56
|
+
default=lambda: os.environ.get("GSC_CLIENT_SECRETS"),
|
|
57
|
+
help="Path to OAuth2 client_secrets.json (default: $GSC_CLIENT_SECRETS).",
|
|
58
|
+
)
|
|
59
|
+
@click.pass_context
|
|
60
|
+
def login(ctx: click.Context, client_secrets: str | None) -> None:
|
|
61
|
+
"""Run the OAuth2 browser flow and save the 'default' profile."""
|
|
62
|
+
if not client_secrets:
|
|
63
|
+
raise click.ClickException("Provide --client-secrets or set $GSC_CLIENT_SECRETS.")
|
|
64
|
+
profile = run_oauth_flow(client_secrets, config_path=_get_config_path(ctx))
|
|
65
|
+
click.echo(f"Logged in. Saved profile '{profile.name}' ({profile.credentials}).")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@auth.command("add-profile")
|
|
69
|
+
@_config_path_option
|
|
70
|
+
@click.argument("name")
|
|
71
|
+
@click.option(
|
|
72
|
+
"--service-account",
|
|
73
|
+
"credentials",
|
|
74
|
+
required=True,
|
|
75
|
+
help="Path to the service-account JSON key file.",
|
|
76
|
+
)
|
|
77
|
+
@click.option(
|
|
78
|
+
"--site",
|
|
79
|
+
"sites",
|
|
80
|
+
multiple=True,
|
|
81
|
+
help="Site URL this profile manages (repeatable; enables auto-detection).",
|
|
82
|
+
)
|
|
83
|
+
@click.pass_context
|
|
84
|
+
def add_profile(ctx: click.Context, name: str, credentials: str, sites: tuple[str, ...]) -> None:
|
|
85
|
+
"""Add a service-account profile NAME."""
|
|
86
|
+
profile = add_service_account_profile(
|
|
87
|
+
name=name,
|
|
88
|
+
credentials=credentials,
|
|
89
|
+
sites=list(sites),
|
|
90
|
+
config_path=_get_config_path(ctx),
|
|
91
|
+
)
|
|
92
|
+
click.echo(f"Added service-account profile '{profile.name}'.")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@auth.command("list-profiles")
|
|
96
|
+
@_config_path_option
|
|
97
|
+
@click.pass_context
|
|
98
|
+
def list_profiles_cmd(ctx: click.Context) -> None:
|
|
99
|
+
"""List all configured profiles."""
|
|
100
|
+
profiles = list_profiles(config_path=_get_config_path(ctx))
|
|
101
|
+
rows = [
|
|
102
|
+
{
|
|
103
|
+
"name": p.name,
|
|
104
|
+
"auth_type": p.auth_type,
|
|
105
|
+
"credentials": p.credentials,
|
|
106
|
+
"sites": ", ".join(p.sites),
|
|
107
|
+
}
|
|
108
|
+
for p in profiles
|
|
109
|
+
]
|
|
110
|
+
click.echo(format_output(rows, fmt=ctx.obj["format"]))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@auth.command("remove-profile")
|
|
114
|
+
@_config_path_option
|
|
115
|
+
@click.argument("name")
|
|
116
|
+
@click.pass_context
|
|
117
|
+
def remove_profile_cmd(ctx: click.Context, name: str) -> None:
|
|
118
|
+
"""Remove profile NAME."""
|
|
119
|
+
removed = remove_profile(name, config_path=_get_config_path(ctx))
|
|
120
|
+
if not removed:
|
|
121
|
+
raise click.ClickException(f"No such profile: {name}")
|
|
122
|
+
click.echo(f"Removed profile '{name}'.")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@auth.command("status")
|
|
126
|
+
@_config_path_option
|
|
127
|
+
@click.pass_context
|
|
128
|
+
def status(ctx: click.Context) -> None:
|
|
129
|
+
"""Show the active profile and whether its credentials load."""
|
|
130
|
+
profile = resolve_profile(name=ctx.obj.get("profile"), config_path=_get_config_path(ctx))
|
|
131
|
+
if profile is None:
|
|
132
|
+
raise click.ClickException("No active profile. Run 'gsc auth login'.")
|
|
133
|
+
|
|
134
|
+
info: dict = {
|
|
135
|
+
"name": profile.name,
|
|
136
|
+
"auth_type": profile.auth_type,
|
|
137
|
+
"credentials": profile.credentials,
|
|
138
|
+
"sites": ", ".join(profile.sites),
|
|
139
|
+
}
|
|
140
|
+
try:
|
|
141
|
+
get_credentials(profile)
|
|
142
|
+
info["credentials_ok"] = True
|
|
143
|
+
except Exception as exc: # noqa: BLE001
|
|
144
|
+
info["credentials_ok"] = False
|
|
145
|
+
if ctx.obj.get("verbose"):
|
|
146
|
+
info["error"] = str(exc)
|
|
147
|
+
click.echo(format_output(info, fmt=ctx.obj["format"]))
|
gsc/cli/genai.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""``gsc genai`` — ingest a Search Console Generative AI report export (AI Overviews + AI Mode).
|
|
2
|
+
|
|
3
|
+
The Generative AI performance report (launched 2026-06-03) is UI/Export only: neither the
|
|
4
|
+
Search Analytics API nor the BigQuery bulk export returns it. It carries impressions only
|
|
5
|
+
(no clicks, CTR, position or queries), grouped by page, country, device or date, and the
|
|
6
|
+
export is capped at 1,000 rows.
|
|
7
|
+
|
|
8
|
+
``--compare`` joins the page table with API ``web`` for the same dates and computes an AI
|
|
9
|
+
lift index per page: the page's share of AI impressions divided by its share of organic
|
|
10
|
+
impressions, both inside the matched sample (method: iamveru.com, "Google AI visibility and
|
|
11
|
+
organic ranking data", 2026). Lift > 1 means the page takes more AI visibility than its
|
|
12
|
+
organic weight predicts. Tiny denominators produce absurd ratios, so rows below the
|
|
13
|
+
``--min-ai`` / ``--min-organic`` floors are marked ``qualified: false``.
|
|
14
|
+
|
|
15
|
+
Export layout (verified on a live property, 2026-09-28): Pages.csv, Countries.csv,
|
|
16
|
+
Devices.csv, Chart.csv (daily) and Filters.csv, each ``key,Impressions``; Filters.csv
|
|
17
|
+
records ``Search type,Web`` and the UI filter reads "Web (text)", so API ``web`` is the
|
|
18
|
+
matching organic denominator. The impressions column is still found by header name
|
|
19
|
+
(localized stems) with a positional fallback, in case a localized UI changes headers.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import csv
|
|
25
|
+
import io
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from urllib.parse import unquote
|
|
28
|
+
|
|
29
|
+
import click
|
|
30
|
+
|
|
31
|
+
from ..client import GSCClient
|
|
32
|
+
from ..formatters import format_output
|
|
33
|
+
from .multimodal import _number, _pct, _read_export_file
|
|
34
|
+
from .sites import get_client
|
|
35
|
+
|
|
36
|
+
_API_PAGE_SIZE = 25000
|
|
37
|
+
# Verified on a live export 2026-09-28: the daily table is Chart.csv, not Dates.csv.
|
|
38
|
+
_EXPORT_FILES = {
|
|
39
|
+
"page": "Pages.csv",
|
|
40
|
+
"country": "Countries.csv",
|
|
41
|
+
"device": "Devices.csv",
|
|
42
|
+
"date": "Chart.csv",
|
|
43
|
+
}
|
|
44
|
+
# Band labels follow the gsc-core benchmarks.
|
|
45
|
+
_BANDS = (("1-3", 3.0), ("4-10", 10.0), ("11-20", 20.0), ("21+", float("inf")))
|
|
46
|
+
_IMPRESSION_HEADERS = ("impression", "показван", "импресии", "zobrazen", "afișăr", "показы")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _impressions_column(header: list[str]) -> int:
|
|
50
|
+
"""Index of the impressions column: by (localized) name, else by layout."""
|
|
51
|
+
for index, name in enumerate(header):
|
|
52
|
+
if any(stem in name.strip().lower() for stem in _IMPRESSION_HEADERS):
|
|
53
|
+
return index
|
|
54
|
+
# Impressions-only export: key, impressions. Performance layout: key, clicks, impressions.
|
|
55
|
+
return 1 if len(header) <= 2 else 2
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_genai_rows(text: str, key_name: str) -> list[dict]:
|
|
59
|
+
"""Parse a Generative AI export CSV into ``{key_name, ai_impressions}`` rows."""
|
|
60
|
+
reader = csv.reader(io.StringIO(text))
|
|
61
|
+
header = next(reader, None) or []
|
|
62
|
+
column = _impressions_column(header)
|
|
63
|
+
rows: list[dict] = []
|
|
64
|
+
for record in reader:
|
|
65
|
+
if len(record) <= column or not record[0].strip():
|
|
66
|
+
continue
|
|
67
|
+
rows.append({key_name: record[0].strip(), "ai_impressions": int(_number(record[column]))})
|
|
68
|
+
return rows
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _band(position: float) -> str:
|
|
72
|
+
for label, upper in _BANDS:
|
|
73
|
+
if position <= upper:
|
|
74
|
+
return label
|
|
75
|
+
return _BANDS[-1][0]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _fetch_organic_by_page(
|
|
79
|
+
client: GSCClient, site_url: str, start_date: str, end_date: str
|
|
80
|
+
) -> dict[str, tuple[int, int, float]]:
|
|
81
|
+
"""All pages' API ``web`` clicks, impressions and position, keyed by decoded URL."""
|
|
82
|
+
totals: dict[str, tuple[int, int, float]] = {}
|
|
83
|
+
start_row = 0
|
|
84
|
+
while True:
|
|
85
|
+
body = GSCClient.build_query_body(
|
|
86
|
+
start_date=start_date,
|
|
87
|
+
end_date=end_date,
|
|
88
|
+
dimensions=["page"],
|
|
89
|
+
search_type="web",
|
|
90
|
+
row_limit=_API_PAGE_SIZE,
|
|
91
|
+
start_row=start_row,
|
|
92
|
+
)
|
|
93
|
+
response = client.query(site_url, body)
|
|
94
|
+
for row in response.rows:
|
|
95
|
+
totals[unquote(row.keys[0])] = (
|
|
96
|
+
int(row.clicks),
|
|
97
|
+
int(row.impressions),
|
|
98
|
+
float(row.position),
|
|
99
|
+
)
|
|
100
|
+
if len(response.rows) < _API_PAGE_SIZE:
|
|
101
|
+
return totals
|
|
102
|
+
start_row += _API_PAGE_SIZE
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _lift(ai_share: float, organic_share: float) -> float | None:
|
|
106
|
+
return round(ai_share / organic_share, 3) if organic_share else None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def compare_rows(
|
|
110
|
+
rows: list[dict],
|
|
111
|
+
organic_by_page: dict[str, tuple[int, int, float]],
|
|
112
|
+
min_ai: int,
|
|
113
|
+
min_organic: int,
|
|
114
|
+
) -> tuple[list[dict], int]:
|
|
115
|
+
"""Join AI page rows with organic totals; return (matched rows, unmatched count).
|
|
116
|
+
|
|
117
|
+
Shares are computed inside the matched sample, so both sides cover the same URLs.
|
|
118
|
+
"""
|
|
119
|
+
matched: list[dict] = []
|
|
120
|
+
for row in rows:
|
|
121
|
+
organic = organic_by_page.get(unquote(row["page"]))
|
|
122
|
+
if not organic or not organic[1]:
|
|
123
|
+
continue
|
|
124
|
+
clicks, impressions, position = organic
|
|
125
|
+
matched.append(
|
|
126
|
+
{
|
|
127
|
+
**row,
|
|
128
|
+
"organic_clicks": clicks,
|
|
129
|
+
"organic_impressions": impressions,
|
|
130
|
+
"organic_position": round(position, 1),
|
|
131
|
+
"band": _band(position),
|
|
132
|
+
}
|
|
133
|
+
)
|
|
134
|
+
ai_total = sum(r["ai_impressions"] for r in matched)
|
|
135
|
+
organic_total = sum(r["organic_impressions"] for r in matched)
|
|
136
|
+
for row in matched:
|
|
137
|
+
ai_share = row["ai_impressions"] / ai_total if ai_total else 0.0
|
|
138
|
+
organic_share = row["organic_impressions"] / organic_total if organic_total else 0.0
|
|
139
|
+
row["ai_share"] = f"{ai_share * 100:.3f}%"
|
|
140
|
+
row["organic_share"] = f"{organic_share * 100:.3f}%"
|
|
141
|
+
row["ai_lift"] = _lift(ai_share, organic_share)
|
|
142
|
+
row["qualified"] = (
|
|
143
|
+
row["ai_impressions"] >= min_ai and row["organic_impressions"] >= min_organic
|
|
144
|
+
)
|
|
145
|
+
return matched, len(rows) - len(matched)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def band_summary(matched: list[dict]) -> list[dict]:
|
|
149
|
+
"""AI vs organic impressions per organic position band, with the band's lift."""
|
|
150
|
+
ai_total = sum(r["ai_impressions"] for r in matched)
|
|
151
|
+
organic_total = sum(r["organic_impressions"] for r in matched)
|
|
152
|
+
summary: list[dict] = []
|
|
153
|
+
for label, _ in _BANDS:
|
|
154
|
+
members = [r for r in matched if r["band"] == label]
|
|
155
|
+
ai = sum(r["ai_impressions"] for r in members)
|
|
156
|
+
organic = sum(r["organic_impressions"] for r in members)
|
|
157
|
+
summary.append(
|
|
158
|
+
{
|
|
159
|
+
"band": label,
|
|
160
|
+
"urls": len(members),
|
|
161
|
+
"ai_impressions": ai,
|
|
162
|
+
"ai_share": _pct(ai, ai_total),
|
|
163
|
+
"organic_impressions": organic,
|
|
164
|
+
"organic_share": _pct(organic, organic_total),
|
|
165
|
+
"ai_lift": _lift(
|
|
166
|
+
ai / ai_total if ai_total else 0.0,
|
|
167
|
+
organic / organic_total if organic_total else 0.0,
|
|
168
|
+
),
|
|
169
|
+
}
|
|
170
|
+
)
|
|
171
|
+
return summary
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@click.command()
|
|
175
|
+
@click.argument("site_url")
|
|
176
|
+
@click.argument("export", type=click.Path(exists=True, path_type=Path))
|
|
177
|
+
@click.option(
|
|
178
|
+
"--by",
|
|
179
|
+
"grouping",
|
|
180
|
+
type=click.Choice(sorted(_EXPORT_FILES)),
|
|
181
|
+
default="page",
|
|
182
|
+
help="Which export table to read (default: page). The report has no query table.",
|
|
183
|
+
)
|
|
184
|
+
@click.option("--start-date", default=None, help="Export start date, for --compare.")
|
|
185
|
+
@click.option("--end-date", default=None, help="Export end date, for --compare.")
|
|
186
|
+
@click.option(
|
|
187
|
+
"--compare",
|
|
188
|
+
is_flag=True,
|
|
189
|
+
help="Join with API web by page for the same dates and add the AI lift index.",
|
|
190
|
+
)
|
|
191
|
+
@click.option(
|
|
192
|
+
"--bands",
|
|
193
|
+
is_flag=True,
|
|
194
|
+
help="With --compare: output the per-position-band summary instead of page rows.",
|
|
195
|
+
)
|
|
196
|
+
@click.option("--min-ai", default=100, show_default=True, help="AI impressions floor.")
|
|
197
|
+
@click.option("--min-organic", default=1000, show_default=True, help="Organic impr. floor.")
|
|
198
|
+
@click.pass_context
|
|
199
|
+
def genai(
|
|
200
|
+
ctx: click.Context,
|
|
201
|
+
site_url: str,
|
|
202
|
+
export: Path,
|
|
203
|
+
grouping: str,
|
|
204
|
+
start_date: str | None,
|
|
205
|
+
end_date: str | None,
|
|
206
|
+
compare: bool,
|
|
207
|
+
bands: bool,
|
|
208
|
+
min_ai: int,
|
|
209
|
+
min_organic: int,
|
|
210
|
+
) -> None:
|
|
211
|
+
"""Parse a Generative AI report export (AI Overviews + AI Mode) for SITE_URL.
|
|
212
|
+
|
|
213
|
+
EXPORT is the downloaded zip, its extracted folder, or one CSV from it.
|
|
214
|
+
"""
|
|
215
|
+
text, _ = _read_export_file(export, _EXPORT_FILES[grouping])
|
|
216
|
+
rows = parse_genai_rows(text, grouping)
|
|
217
|
+
if len(rows) >= 1000:
|
|
218
|
+
click.echo("Note: 1,000 rows = the export cap; the tail of the site is cut off.", err=True)
|
|
219
|
+
|
|
220
|
+
if bands and not compare:
|
|
221
|
+
raise click.UsageError("--bands needs --compare.")
|
|
222
|
+
if compare:
|
|
223
|
+
if grouping != "page" or not (start_date and end_date):
|
|
224
|
+
raise click.UsageError("--compare needs --by page plus --start-date and --end-date.")
|
|
225
|
+
ctx.obj["site_url"] = site_url
|
|
226
|
+
organic = _fetch_organic_by_page(get_client(ctx), site_url, start_date, end_date)
|
|
227
|
+
rows, unmatched = compare_rows(rows, organic, min_ai, min_organic)
|
|
228
|
+
if unmatched:
|
|
229
|
+
click.echo(
|
|
230
|
+
f"Note: {unmatched} AI page(s) had no organic web impressions in the window "
|
|
231
|
+
"and were left out of the shares.",
|
|
232
|
+
err=True,
|
|
233
|
+
)
|
|
234
|
+
if bands:
|
|
235
|
+
click.echo(format_output(band_summary(rows), fmt=ctx.obj["format"]))
|
|
236
|
+
return
|
|
237
|
+
|
|
238
|
+
if grouping != "date":
|
|
239
|
+
rows.sort(key=lambda r: r["ai_impressions"], reverse=True)
|
|
240
|
+
click.echo(format_output(rows, fmt=ctx.obj["format"]))
|
gsc/cli/inspect_cmd.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""``gsc inspect`` command: single-URL index inspection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from ..formatters import format_output
|
|
10
|
+
from .sites import get_client
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@click.command()
|
|
14
|
+
@click.argument("site_url")
|
|
15
|
+
@click.argument("inspection_url")
|
|
16
|
+
@click.pass_context
|
|
17
|
+
def inspect_url(ctx: click.Context, site_url: str, inspection_url: str) -> None:
|
|
18
|
+
"""Inspect INSPECTION_URL in SITE_URL's index."""
|
|
19
|
+
ctx.obj["site_url"] = site_url
|
|
20
|
+
client = get_client(ctx)
|
|
21
|
+
result = client.inspect_url(site_url, inspection_url)
|
|
22
|
+
|
|
23
|
+
out: dict = {"inspection_result_link": result.inspection_result_link}
|
|
24
|
+
if result.index_status is not None:
|
|
25
|
+
out.update(asdict(result.index_status))
|
|
26
|
+
click.echo(format_output(out, fmt=ctx.obj["format"]))
|
gsc/cli/main.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Root Click group with global options, registering all subcommands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from .. import __version__
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.group()
|
|
13
|
+
@click.option(
|
|
14
|
+
"--profile",
|
|
15
|
+
"-p",
|
|
16
|
+
default=lambda: os.environ.get("GSC_PROFILE"),
|
|
17
|
+
help="Auth profile name (default: $GSC_PROFILE, else auto-detect).",
|
|
18
|
+
)
|
|
19
|
+
@click.option(
|
|
20
|
+
"--format",
|
|
21
|
+
"-f",
|
|
22
|
+
"fmt",
|
|
23
|
+
type=click.Choice(["table", "json", "csv"]),
|
|
24
|
+
default="table",
|
|
25
|
+
help="Output format. Global; precedes the subcommand.",
|
|
26
|
+
)
|
|
27
|
+
@click.option("--verbose", "-v", is_flag=True, help="Verbose error output.")
|
|
28
|
+
@click.version_option(__version__, prog_name="gsc")
|
|
29
|
+
@click.pass_context
|
|
30
|
+
def cli(ctx: click.Context, profile: str | None, fmt: str, verbose: bool) -> None:
|
|
31
|
+
"""gsc — Google Search Console from the command line."""
|
|
32
|
+
ctx.ensure_object(dict)
|
|
33
|
+
ctx.obj["profile"] = profile
|
|
34
|
+
ctx.obj["format"] = fmt
|
|
35
|
+
ctx.obj["verbose"] = verbose
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
from .auth_cmd import auth # noqa: E402
|
|
39
|
+
from .genai import genai # noqa: E402
|
|
40
|
+
from .inspect_cmd import inspect_url # noqa: E402
|
|
41
|
+
from .multimodal import multimodal # noqa: E402
|
|
42
|
+
from .query import query # noqa: E402
|
|
43
|
+
from .sitemaps import sitemaps # noqa: E402
|
|
44
|
+
from .sites import sites # noqa: E402
|
|
45
|
+
|
|
46
|
+
cli.add_command(auth)
|
|
47
|
+
cli.add_command(sites)
|
|
48
|
+
cli.add_command(query)
|
|
49
|
+
cli.add_command(sitemaps)
|
|
50
|
+
cli.add_command(inspect_url, name="inspect")
|
|
51
|
+
cli.add_command(multimodal)
|
|
52
|
+
cli.add_command(genai)
|