feat: rank search pages by clicks lost

Search Console rows are merged across page anchors. The expected click
rate is the site's own rate at each rounded position, so a search is
flagged when clicked less than half of it. A by-page table ranks pages
by clicks lost, with changes against the period before. Each section
states its period, and release downloads show the change since the
snapshot the previous run left in .cache/insights/.
This commit is contained in:
Abdessamad Derraz committed 2026-11-19 16:51:32 +01:00
1 parent 624601272a
commit 7623ead3db
4 files changed
+467 -64

No files matched your search

+27 -6
View File
@@ -3,12 +3,15 @@
Four sources, none of which names a person:
- Google Search Console: the searches that showed the site, by page.
- Google Search Console: the searches that showed the site, by page,
against the period of the same length just before.
- GoatCounter: page views, the domains readers came from, and the actions
website/src/scripts/count.ts counts (searches that found nothing,
"Did this page help?", downloads, broken links). wiki/privacy.md says
what is sent.
- GitHub: repository traffic (14 days) and release download counts.
- GitHub: repository traffic (14 days) and release download counts,
all-time counters compared with the snapshot the previous run left in
.cache/insights/downloads.json.
- The collection: which searched file names it holds, and which no
emulator profile declares.
@@ -22,6 +25,7 @@ Usage:
python scripts/site_insights.py
python scripts/site_insights.py --days 90 --output report.md
python scripts/site_insights.py --skip gsc,github
python scripts/site_insights.py --downloads-snapshot tmp/downloads.json
"""
from __future__ import annotations
@@ -30,6 +34,7 @@ import argparse
import datetime as dt
import os
import sys
from dataclasses import replace
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
@@ -39,11 +44,15 @@ from core.cli import run_cli
from core.paths import REPO_ROOT
from sitegen.insights import (
SOURCES,
Readings,
collection_names,
downloads_snapshot,
fetch_github,
fetch_goatcounter,
fetch_queries,
load_snapshot,
report,
save_snapshot,
)
@@ -52,25 +61,37 @@ def main() -> int:
parser.add_argument("--days", type=int, default=28, help="days to read, ending 3 days ago (default 28)")
parser.add_argument("--skip", default="", help=f"sources to leave out, among {', '.join(SOURCES)}")
parser.add_argument("--output", type=Path, help="write the report here instead of stdout")
parser.add_argument("--downloads-snapshot", type=Path, default=REPO_ROOT / ".cache" / "insights" / "downloads.json",
help="release download counts of the previous run, rewritten after each run")
args = parser.parse_args()
skip = {name.strip() for name in args.skip.split(",") if name.strip()}
unknown = skip - set(SOURCES)
if unknown:
parser.error(f"unknown source(s): {', '.join(sorted(unknown))}")
if args.days < 1:
parser.error("--days must be at least 1")
# Search Console data settles two to three days after the fact.
end = dt.date.today() - dt.timedelta(days=3)
start = end - dt.timedelta(days=args.days - 1)
held, declared = collection_names(load_database(str(REPO_ROOT / "database.json")),
load_emulator_profiles(str(REPO_ROOT / "emulators")))
queries = None if "gsc" in skip else fetch_queries(start, end)
goat = None if "goatcounter" in skip else fetch_goatcounter(start, dt.date.today())
github = None if "github" in skip else fetch_github()
text = report(start, end, queries, goat, github, held, declared)
now = dt.datetime.now(dt.timezone.utc)
readings = Readings(start, end, now, held, declared)
if "gsc" not in skip:
readings = replace(readings, queries=fetch_queries(start, end),
previous=fetch_queries(*readings.previous_span))
if "goatcounter" not in skip:
readings = replace(readings, goat=fetch_goatcounter(start, now.date()), goat_end=now.date())
if "github" not in skip:
readings = replace(readings, github=fetch_github(), snapshot=load_snapshot(args.downloads_snapshot))
text = report(readings)
if args.output:
args.output.write_text(text, encoding="utf-8")
print(f"Wrote {args.output}", file=sys.stderr)
else:
sys.stdout.write(text)
if readings.github is not None:
save_snapshot(args.downloads_snapshot, downloads_snapshot(readings.github["downloads"], now))
return 0
+281 -51
View File
@@ -17,6 +17,7 @@ from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from core.artifacts import write_text_atomic
from core.github import github_token
@@ -32,6 +33,15 @@ GOAT_MAX_EXCLUDED = 1000
RATE_LIMIT_TRIES = 8
RATE_LIMIT_LONGEST_WAIT = 60
# Expected click-through rate: the site's own rate at each rounded
# position, positions past 20 pooled in LAST_BUCKET. A bucket under
# BUCKET_FLOOR impressions borrows its neighbours. A search on the first
# page is rarely clicked below MISSED_SHARE of its bucket's rate.
LAST_BUCKET = 21
BUCKET_FLOOR = 500
MISSED_SHARE = 0.5
FILE_ROWS = 40
# A word of a search that names a file: "scph5501.bin", "prod.keys".
FILE_TOKEN = re.compile(r"\b[\w.+-]+\.(?:bin|rom|zip|pup|keys|img|dat|bios|ic\d+|u\d+|sys|nvm|mec|"
r"rom1|j64|pce|col|sms|gb|gbc|gba|nds|cfg|chd|iso|txt|fw|dll|xml|yaml)\b", re.I)
@@ -114,7 +124,7 @@ def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]),
float(r["position"])) for r in batch]
if len(batch) < 25000:
return rows
return merge_fragments(rows)
def _goat_object(url: str, auth: dict[str, str]) -> dict:
@@ -231,11 +241,59 @@ def searched_files(queries: list[Query], held: set[str], declared: set[str]) ->
return sorted(((shown[key], seen[key], state[key]) for key in seen), key=lambda row: -row[1])
def missed_clicks(queries: list[Query], least: int = 100) -> list[Query]:
"""On the first page but rarely clicked: what the result says loses
the reader."""
return sorted((q for q in queries if q.position <= 10 and q.impressions >= least and q.ctr < 0.03),
key=lambda q: -q.impressions)
def merge_fragments(queries: list[Query]) -> list[Query]:
"""One row per search and page: Search Console reports /page/#anchor
apart from /page/, so the same search appears once per anchor."""
groups: dict[tuple[str, str], list[Query]] = defaultdict(list)
for query in queries:
groups[(query.text, query.page.partition("#")[0])].append(query)
return [_combined(text, page, rows) for (text, page), rows in groups.items()]
def _combined(text: str, page: str, rows: list[Query]) -> Query:
"""Clicks and impressions add up, the position is weighted by impressions."""
shown = sum(q.impressions for q in rows)
position = (sum(q.position * q.impressions for q in rows) / shown if shown
else sum(q.position for q in rows) / len(rows))
return Query(text, page, sum(q.clicks for q in rows), shown, position)
def _bucket(position: float) -> int:
return min(max(1, int(position + 0.5)), LAST_BUCKET)
def expected_ctr(queries: list[Query]) -> dict[int, float]:
"""The site's own click-through rate at each rounded position: clicks
over impressions of every search in the bucket, positions past 20 in
one bucket. A bucket under BUCKET_FLOOR impressions is pooled with its
neighbours, one on each side at a time, until the window holds that many."""
clicks = [0] * (LAST_BUCKET + 1)
shown = [0] * (LAST_BUCKET + 1)
for query in queries:
clicks[_bucket(query.position)] += query.clicks
shown[_bucket(query.position)] += query.impressions
expected: dict[int, float] = {}
for bucket in range(1, LAST_BUCKET + 1):
for reach in range(LAST_BUCKET):
window = range(max(1, bucket - reach), min(LAST_BUCKET, bucket + reach) + 1)
seen = sum(shown[i] for i in window)
if seen >= BUCKET_FLOOR:
break
expected[bucket] = sum(clicks[i] for i in window) / seen if seen else 0.0
return expected
def _expected_clicks(expected: dict[int, float], query: Query) -> float:
return expected.get(_bucket(query.position), 0.0) * query.impressions
def missed_clicks(queries: list[Query], expected: dict[int, float], least: int = 100) -> list[Query]:
"""On the first page, shown at least `least` times, and clicked less
than MISSED_SHARE of what the site gets at that position: what the
result says loses the reader. Most clicks lost first."""
return sorted((q for q in queries if q.position <= 10 and q.impressions >= least
and q.ctr < MISSED_SHARE * expected.get(_bucket(q.position), 0.0)),
key=lambda q: (q.clicks - _expected_clicks(expected, q), q.text))
def near_first_page(queries: list[Query], least: int = 50) -> list[Query]:
@@ -243,6 +301,36 @@ def near_first_page(queries: list[Query], least: int = 50) -> list[Query]:
key=lambda q: -q.impressions)
@dataclass(frozen=True)
class PageReading:
page: str
clicks: int
impressions: int
position: float
lost: float
top: tuple[str, ...]
@property
def ctr(self) -> float:
return self.clicks / self.impressions if self.impressions else 0.0
def by_page(queries: list[Query], expected: dict[int, float]) -> list[PageReading]:
"""Searches summed by page, the page that loses the most clicks against
the site's own rate at each position first. `lost` is expected minus
actual clicks, negative when the page does better than its positions."""
groups: dict[str, list[Query]] = defaultdict(list)
for query in queries:
groups[query.page].append(query)
readings = []
for page, rows in groups.items():
total = _combined("", page, rows)
top = tuple(q.text for q in sorted(rows, key=lambda q: (-q.impressions, q.text))[:3])
readings.append(PageReading(page, total.clicks, total.impressions, total.position,
sum(_expected_clicks(expected, q) - q.clicks for q in rows), top))
return sorted(readings, key=lambda r: (-r.lost, r.page))
def site_actions(hits: list[tuple[str, int]]) -> dict[str, list[tuple[str, int]]]:
"""Events by kind ("search-none", "helpful", "download"...), pages apart."""
groups: dict[str, list[tuple[str, int]]] = defaultdict(list)
@@ -257,9 +345,70 @@ def site_actions(hits: list[tuple[str, int]]) -> dict[str, list[tuple[str, int]]
return {kind: sorted(rows, key=lambda row: -row[1]) for kind, rows in groups.items()}
# Release download counts are all-time counters: a snapshot of the last
# run's counts gives the change between two runs.
def downloads_snapshot(downloads: list[tuple[str, str, int]], taken: dt.datetime) -> dict:
return {"taken": taken.strftime("%Y-%m-%d %H:%M UTC"),
"counts": {f"{tag}/{name}": count for tag, name, count in downloads}}
def load_snapshot(path: Path) -> dict | None:
if not path.exists():
return None
try:
snapshot = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
raise SystemExit(f"{path} is not a download snapshot ({error}); move it away to start again") from error
if not isinstance(snapshot, dict) or not isinstance(snapshot.get("counts"), dict) or "taken" not in snapshot:
raise SystemExit(f"{path} is not a download snapshot; move it away to start again")
return snapshot
def save_snapshot(path: Path, snapshot: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
write_text_atomic(str(path), json.dumps(snapshot, indent=2, sort_keys=True) + "\n")
def download_rows(downloads: list[tuple[str, str, int]], snapshot: dict | None) -> list[tuple]:
"""(release, file, change, all time) by change, or (release, file, all
time) by count without a snapshot. A file the snapshot lacks is new."""
if snapshot is None:
return [(tag, name, f"{count:,}") for tag, name, count in sorted(downloads, key=lambda row: -row[2])]
before = snapshot["counts"]
rows = [(tag, name, count - int(before.get(f"{tag}/{name}", 0)), count, f"{tag}/{name}" not in before)
for tag, name, count in downloads]
rows.sort(key=lambda row: (-row[2], -row[3]))
return [(tag, name, f"{change:+,}" + (" (new)" if new else ""), f"{count:,}")
for tag, name, change, count, new in rows]
# The report
@dataclass(frozen=True)
class Readings:
"""What one run read. A source left out is None."""
start: dt.date
end: dt.date
now: dt.datetime
held: set[str]
declared: set[str]
queries: list[Query] | None = None
previous: list[Query] | None = None
goat: dict | None = None
goat_end: dt.date | None = None
github: dict | None = None
snapshot: dict | None = None
@property
def previous_span(self) -> tuple[dt.date, dt.date]:
"""The period of the same length just before."""
last = self.start - dt.timedelta(days=1)
return last - (self.end - self.start), last
def _table(header: tuple[str, ...], rows: list[tuple], limit: int = 25) -> list[str]:
if not rows:
return ["None.", ""]
@@ -272,51 +421,132 @@ def _page(url: str) -> str:
return url.removeprefix(SITE_PROPERTY.rstrip("/")) or "/"
def report(start: dt.date, end: dt.date, queries: list[Query] | None, goat: dict | None,
github: dict | None, held: set[str], declared: set[str]) -> str:
out = [f"# Site insights, {start.isoformat()} to {end.isoformat()}", ""]
if queries is not None:
clicks = sum(q.clicks for q in queries)
shown = sum(q.impressions for q in queries)
out += ["## Google searches", "",
f"{clicks:,} clicks, {shown:,} impressions, {len({q.text for q in queries}):,} searches.", "",
"### On the first page, rarely clicked", "",
*_table(("Search", "Page", "Impressions", "CTR", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.ctr:.1%}", f"{q.position:.1f}")
for q in missed_clicks(queries)]),
"### Just past the first page", "",
*_table(("Search", "Page", "Impressions", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.position:.1f}")
for q in near_first_page(queries)]),
"### File names searched", "",
*_table(("File", "Impressions", "In the project"),
[(f"`{name}`", f"{seen:,}", state)
for name, seen, state in searched_files(queries, held, declared)], limit=40)]
if goat is not None:
actions = site_actions(goat["hits"])
named = {"search-none": "Site searches that found nothing", "404": "Broken addresses",
"helpful": "Did this page help?", "get": "Pack pages opened",
"download": "Release downloads", "file": "File downloads", "copy": "Copy buttons",
"out": "Links leaving the site", "pages": "Pages"}
out += ["## On the site", "",
f"{goat.get('visits', 0):,} page views, {goat.get('actions', 0):,} actions.", ""]
for kind, title in named.items():
if kind in actions:
out += [f"### {title}", "", *_table(("Name", "Visits"), [(n, f"{c:,}") for n, c in actions[kind]])]
out += ["### Came from", "", *_table(("Site", "Visits"), [(n, f"{c:,}") for n, c in goat["referrers"]])]
if github is not None:
views, clones = github["views"], github["clones"]
out += ["## GitHub", "",
f"Last 14 days: {views.get('count', 0):,} views by {views.get('uniques', 0):,} visitors, "
f"{clones.get('count', 0):,} clones.", "",
"### Came from", "",
*_table(("Site", "Views", "Visitors"),
[(r["referrer"], r["count"], r["uniques"]) for r in github["referrers"]]),
"### Most viewed", "",
*_table(("Path", "Views"), [(p["path"], p["count"]) for p in github["paths"]]),
"### Release downloads", "",
*_table(("Release", "File", "Downloads"),
sorted(github["downloads"], key=lambda row: -row[2]), limit=40)]
def _span(start: dt.date, end: dt.date) -> str:
return f"{start.isoformat()} to {end.isoformat()} ({(end - start).days + 1} days)"
def _google_totals(readings: Readings, queries: list[Query]) -> str:
clicks = sum(q.clicks for q in queries)
shown = sum(q.impressions for q in queries)
line = (f"{_span(readings.start, readings.end)}: {clicks:,} clicks, {shown:,} impressions, "
f"{len({q.text for q in queries}):,} searches.")
if readings.previous is None:
return line
first, last = readings.previous_span
if not readings.previous:
return f"{line} Search Console holds nothing for the period before, {_span(first, last)}."
before_clicks = sum(q.clicks for q in readings.previous)
before_shown = sum(q.impressions for q in readings.previous)
return (f"{line} Against {_span(first, last)}: {clicks - before_clicks:+,} clicks, "
f"{shown - before_shown:+,} impressions.")
def _change(now: PageReading, then: PageReading | None, field: str, compared: bool) -> str:
"""A figure, and its change against the period before when there is one."""
value = getattr(now, field)
shown = f"{value:.1f}" if field == "position" else f"{value:,}"
if not compared:
return shown
if then is None:
return f"{shown} (new)"
diff = value - getattr(then, field)
return f"{shown} ({diff:+.1f})" if field == "position" else f"{shown} ({diff:+,})"
def _page_rows(readings: Readings, pages: list[PageReading]) -> list[tuple]:
before = {r.page: r for r in by_page(readings.previous or [], {})}
compared = bool(before)
return [(_page(r.page), f"{r.lost:,.0f}", _change(r, before.get(r.page), "clicks", compared),
_change(r, before.get(r.page), "impressions", compared), f"{r.ctr:.1%}",
_change(r, before.get(r.page), "position", compared), "; ".join(r.top))
for r in pages]
def _file_names(queries: list[Query], held: set[str], declared: set[str]) -> list[str]:
rows = searched_files(queries, held, declared)
missing = [(f"`{name}`", f"{seen:,}", state) for name, seen, state in rows if state != "held"]
if not rows:
return ["No search named a file.", ""]
if not missing:
return [f"All {len(rows):,} searched file names are held.", ""]
shown = "" if len(missing) <= FILE_ROWS else f", the {FILE_ROWS} most searched"
return [f"{len(rows) - len(missing):,} of {len(rows):,} searched file names are held. "
f"Not held ({len(missing):,}{shown}):", "",
*_table(("File", "Impressions", "In the project"), missing, limit=FILE_ROWS)]
def _google(readings: Readings, queries: list[Query]) -> list[str]:
expected = expected_ctr(queries)
return ["## Google searches", "", _google_totals(readings, queries), "",
"### By page", "",
"Lost clicks: what the page's searches would get at the site's own click rate for each "
"position, minus what they got. Changes are against the period before.", "",
*_table(("Page", "Lost clicks", "Clicks", "Impressions", "CTR", "Position", "Top searches"),
_page_rows(readings, by_page(queries, expected)), limit=30),
"### On the first page, rarely clicked", "",
f"Clicked less than half the site's rate at that position, {_span(readings.start, readings.end)}.", "",
*_table(("Search", "Page", "Impressions", "CTR", "Expected CTR", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.ctr:.1%}",
f"{expected.get(_bucket(q.position), 0.0):.1%}", f"{q.position:.1f}")
for q in missed_clicks(queries, expected)]),
"### Just past the first page", "",
*_table(("Search", "Page", "Impressions", "Position"),
[(q.text, _page(q.page), f"{q.impressions:,}", f"{q.position:.1f}")
for q in near_first_page(queries)]),
"### File names searched", "",
*_file_names(queries, readings.held, readings.declared)]
SITE_ACTIONS = {"search-none": "Site searches that found nothing", "404": "Broken addresses",
"helpful": "Did this page help?", "get": "Pack pages opened",
"download": "Release downloads", "file": "File downloads", "copy": "Copy buttons",
"out": "Links leaving the site", "pages": "Pages"}
def _goatcounter(readings: Readings, goat: dict) -> list[str]:
actions = site_actions(goat["hits"])
out = ["## On the site", "",
f"{_span(readings.start, readings.goat_end or readings.end)}, UTC days: "
f"{goat.get('visits', 0):,} page views, {goat.get('actions', 0):,} actions.", ""]
for kind, title in SITE_ACTIONS.items():
if kind in actions:
out += [f"### {title}", "", *_table(("Name", "Visits"), [(n, f"{c:,}") for n, c in actions[kind]])]
return [*out, "### Came from", "", *_table(("Site", "Visits"), [(n, f"{c:,}") for n, c in goat["referrers"]])]
def _github(readings: Readings, github: dict) -> list[str]:
views, clones = github["views"], github["clones"]
days = [day["timestamp"][:10] for day in views.get("views", [])]
span = f"{days[0]} to {days[-1]}" if days else "the last 14 days"
snapshot = readings.snapshot
if snapshot is None:
downloads = ("All-time counters. No earlier snapshot: this run writes the first, "
"the next run shows the change since.")
header: tuple[str, ...] = ("Release", "File", "Downloads, all time")
else:
downloads = f"Change since the snapshot of {snapshot['taken']}, and the all-time counters."
header = ("Release", "File", f"Since {snapshot['taken']}", "All time")
return ["## GitHub", "",
f"Traffic as the API keeps it, 14 days ({span}): {views.get('count', 0):,} views by "
f"{views.get('uniques', 0):,} visitors, {clones.get('count', 0):,} clones.", "",
"### Came from", "",
*_table(("Site", "Views", "Visitors"),
[(r["referrer"], f"{r['count']:,}", f"{r['uniques']:,}") for r in github["referrers"]]),
"### Most viewed", "",
*_table(("Path", "Views"), [(p["path"], f"{p['count']:,}") for p in github["paths"]]),
"### Release downloads", "", downloads, "",
*_table(header, download_rows(github["downloads"], snapshot), limit=40)]
def report(readings: Readings) -> str:
out = ["# Site insights", "", f"Written {readings.now.strftime('%Y-%m-%d %H:%M UTC')}. "
"Each section gives its own period.", ""]
if readings.queries is not None:
out += _google(readings, readings.queries)
if readings.goat is not None:
out += _goatcounter(readings, readings.goat)
if readings.github is not None:
out += _github(readings, readings.github)
return "\n".join(out).rstrip() + "\n"