diff --git a/scripts/site_insights.py b/scripts/site_insights.py index 3aac322b1..6b3a990bd 100644 --- a/scripts/site_insights.py +++ b/scripts/site_insights.py @@ -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 diff --git a/scripts/sitegen/insights.py b/scripts/sitegen/insights.py index 86a529096..b70eddd29 100644 --- a/scripts/sitegen/insights.py +++ b/scripts/sitegen/insights.py @@ -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" diff --git a/tests/test_site_insights.py b/tests/test_site_insights.py index e42b0fcc5..48b66a75a 100644 --- a/tests/test_site_insights.py +++ b/tests/test_site_insights.py @@ -7,9 +7,11 @@ import datetime as dt import email.message import io import json +import tempfile import unittest import urllib.error import urllib.parse +from pathlib import Path from unittest import mock from sitegen import insights @@ -30,13 +32,152 @@ class FileNamesInSearches(unittest.TestCase): class SearchGaps(unittest.TestCase): - def test_first_page_rarely_clicked(self) -> None: + def test_first_page_rarely_clicked_against_its_position(self) -> None: low = insights.Query("swanstation", PAGE, 3, 540, 5.6) fine = insights.Query("nethersx2 bios", PAGE, 54, 484, 4.6) far = insights.Query("xbox bios", PAGE, 0, 900, 10.7) - self.assertEqual(insights.missed_clicks([low, fine, far]), [low]) + expected = {5: 0.08, 6: 0.05, 11: 0.02} + self.assertEqual(insights.missed_clicks([low, fine, far], expected), [low]) self.assertEqual(insights.near_first_page([low, fine, far]), [far]) + def test_a_low_rate_is_normal_low_on_the_page(self) -> None: + ninth = insights.Query("ps2 bios", PAGE, 9, 600, 8.8) + third = insights.Query("ps1 bios", PAGE, 9, 600, 3.2) + expected = {3: 0.20, 9: 0.013} + self.assertEqual(insights.missed_clicks([ninth, third], expected), [third]) + + def test_the_least_impressions_floor_holds(self) -> None: + rare = insights.Query("dsp1b.rom", PAGE, 0, 99, 2.0) + self.assertEqual(insights.missed_clicks([rare], {2: 0.3}), []) + + def test_most_clicks_lost_comes_first(self) -> None: + small = insights.Query("a", PAGE, 0, 200, 1.0) + large = insights.Query("b", PAGE, 0, 400, 2.0) + self.assertEqual(insights.missed_clicks([small, large], {1: 0.3, 2: 0.2}), [large, small]) + + +class ExpectedRate(unittest.TestCase): + def test_each_bucket_pools_its_searches(self) -> None: + queries = [insights.Query("a", PAGE, 30, 100, 1.2), insights.Query("b", PAGE, 10, 400, 0.9), + insights.Query("c", PAGE, 50, 1000, 8.6)] + with mock.patch.object(insights, "BUCKET_FLOOR", 100): + expected = insights.expected_ctr(queries) + self.assertAlmostEqual(expected[1], 40 / 500) + self.assertAlmostEqual(expected[9], 50 / 1000) + + def test_a_thin_bucket_borrows_its_neighbours(self) -> None: + queries = [insights.Query("a", PAGE, 40, 400, 4.0), insights.Query("b", PAGE, 2, 10, 5.0), + insights.Query("c", PAGE, 20, 400, 6.0)] + with mock.patch.object(insights, "BUCKET_FLOOR", 300): + expected = insights.expected_ctr(queries) + self.assertAlmostEqual(expected[4], 0.1) + self.assertAlmostEqual(expected[5], 62 / 810) + + def test_positions_past_twenty_share_a_bucket(self) -> None: + queries = [insights.Query("a", PAGE, 1, 300, 24.0), insights.Query("b", PAGE, 2, 300, 57.0)] + with mock.patch.object(insights, "BUCKET_FLOOR", 500): + expected = insights.expected_ctr(queries) + self.assertAlmostEqual(expected[insights.LAST_BUCKET], 3 / 600) + + +class Fragments(unittest.TestCase): + def test_anchors_of_one_page_merge(self) -> None: + rows = [insights.Query("pcsx bios", PAGE + "#optional", 2, 100, 4.0), + insights.Query("pcsx bios", PAGE + "#proof", 1, 300, 8.0), + insights.Query("pcsx bios", PAGE, 0, 0, 9.0), + insights.Query("other", PAGE + "#proof", 5, 50, 3.0)] + merged = sorted(insights.merge_fragments(rows), key=lambda q: q.text) + self.assertEqual(merged[0], insights.Query("other", PAGE, 5, 50, 3.0)) + self.assertEqual((merged[1].page, merged[1].clicks, merged[1].impressions), (PAGE, 3, 400)) + self.assertAlmostEqual(merged[1].position, (4.0 * 100 + 8.0 * 300) / 400) + + +class ByPage(unittest.TestCase): + OTHER = "https://abdess.github.io/retrobios/emulators/duckstation/" + + def test_pages_sum_their_searches_and_lose_most_first(self) -> None: + queries = [insights.Query("mgba bios", PAGE, 10, 100, 1.0), insights.Query("gba bios", PAGE, 0, 300, 3.0), + insights.Query("gba bios download", PAGE, 1, 50, 3.0), insights.Query("x", PAGE, 0, 10, 3.0), + insights.Query("duckstation bios", self.OTHER, 30, 100, 1.0)] + pages = insights.by_page(queries, {1: 0.2, 3: 0.1}) + self.assertEqual([p.page for p in pages], [PAGE, self.OTHER]) + mgba = pages[0] + self.assertEqual((mgba.clicks, mgba.impressions), (11, 460)) + self.assertAlmostEqual(mgba.position, (100 * 1.0 + 360 * 3.0) / 460) + self.assertAlmostEqual(mgba.lost, 20 + 36 - 11) + self.assertEqual(mgba.top, ("gba bios", "mgba bios", "gba bios download")) + self.assertAlmostEqual(pages[1].lost, -10) + + def test_the_table_shows_changes_against_the_period_before(self) -> None: + now = [insights.Query("mgba bios", PAGE, 10, 100, 2.0), + insights.Query("duckstation bios", self.OTHER, 3, 50, 4.0)] + before = [insights.Query("mgba bios", PAGE, 4, 80, 2.5)] + text = insights.report(readings(queries=now, previous=before)) + self.assertIn("| /emulators/mgba/ |", text) + self.assertIn("| 10 (+6) | 100 (+20) | 10.0% | 2.0 (-0.5) | mgba bios |", text) + self.assertIn("| 3 (new) | 50 (new) |", text) + self.assertIn("Against 2026-09-03 to 2026-09-30 (28 days): +9 clicks, +70 impressions.", text) + + def test_an_empty_period_before_is_said_and_adds_no_change(self) -> None: + text = insights.report(readings(queries=[insights.Query("mgba bios", PAGE, 10, 100, 2.0)], previous=[])) + self.assertIn("Search Console holds nothing for the period before, 2026-09-03 to 2026-09-30", text) + self.assertIn("| 10 | 100 | 10.0% | 2.0 | mgba bios |", text) + + +class FileNamesTable(unittest.TestCase): + def test_only_names_not_held_are_listed(self) -> None: + queries = [insights.Query("gba_bios.bin", PAGE, 1, 300, 8.0), insights.Query("dsp1b.rom", PAGE, 0, 40, 9.0)] + text = insights.report(readings(queries=queries, held={"gba_bios.bin"}, declared={"dsp1b.rom"})) + self.assertIn("1 of 2 searched file names are held. Not held (1):", text) + self.assertIn("| `dsp1b.rom` | 40 | declared, not held |", text) + self.assertNotIn("| `gba_bios.bin` |", text) + + def test_all_held_is_one_line(self) -> None: + text = insights.report(readings(queries=[insights.Query("gba_bios.bin", PAGE, 1, 300, 8.0)], + held={"gba_bios.bin"})) + self.assertIn("All 1 searched file names are held.", text) + self.assertNotIn("| File |", text) + + +def github(downloads: list[tuple[str, str, int]]) -> dict: + return {"views": {"count": 5, "uniques": 2, "views": [{"timestamp": "2026-11-05T00:00:00Z"}, + {"timestamp": "2026-11-18T00:00:00Z"}]}, + "clones": {"count": 1}, "referrers": [], "paths": [], "downloads": downloads} + + +class Downloads(unittest.TestCase): + DOWNLOADS = [("v1", "A.zip", 120), ("v1", "B.zip", 40), ("v2", "C.zip", 7)] + + def test_without_snapshot_the_totals_are_labelled_all_time(self) -> None: + text = insights.report(readings(github=github(self.DOWNLOADS))) + self.assertIn("No earlier snapshot", text) + self.assertIn("| Release | File | Downloads, all time |", text) + self.assertIn("| v1 | A.zip | 120 |", text) + self.assertIn("14 days (2026-11-05 to 2026-11-18)", text) + + def test_with_snapshot_the_change_comes_first(self) -> None: + snapshot = {"taken": "2026-11-12 08:00 UTC", "counts": {"v1/A.zip": 118, "v1/B.zip": 30}} + text = insights.report(readings(github=github(self.DOWNLOADS), snapshot=snapshot)) + self.assertIn("| Release | File | Since 2026-11-12 08:00 UTC | All time |", text) + table = text[text.index("| Release |"):] + self.assertLess(table.index("B.zip"), table.index("C.zip")) + self.assertIn("| v1 | B.zip | +10 | 40 |", text) + self.assertIn("| v2 | C.zip | +7 (new) | 7 |", text) + self.assertIn("| v1 | A.zip | +2 | 120 |", text) + + def test_the_snapshot_round_trips(self) -> None: + with tempfile.TemporaryDirectory() as scratch: + path = Path(scratch) / "insights" / "downloads.json" + self.assertIsNone(insights.load_snapshot(path)) + taken = dt.datetime(2026, 11, 19, 10, 30, tzinfo=dt.timezone.utc) + insights.save_snapshot(path, insights.downloads_snapshot(self.DOWNLOADS, taken)) + snapshot = insights.load_snapshot(path) + self.assertEqual(snapshot, {"taken": "2026-11-19 10:30 UTC", + "counts": {"v1/A.zip": 120, "v1/B.zip": 40, "v2/C.zip": 7}}) + path.write_text("{", encoding="utf-8") + with self.assertRaisesRegex(SystemExit, "not a download snapshot"): + insights.load_snapshot(path) + class SiteActions(unittest.TestCase): def test_events_are_grouped_by_kind_and_pages_apart(self) -> None: @@ -49,16 +190,27 @@ class SiteActions(unittest.TestCase): self.assertEqual(actions["helpful"], [("no", 2)]) +def readings(**fields: object) -> insights.Readings: + base: dict = {"start": dt.date(2026, 10, 1), "end": dt.date(2026, 10, 28), + "now": dt.datetime(2026, 11, 19, 12, 0, tzinfo=dt.timezone.utc), + "held": set(), "declared": set()} + return insights.Readings(**{**base, **fields}) + + class TheReport(unittest.TestCase): def test_a_skipped_source_leaves_no_section(self) -> None: - text = insights.report(dt.date(2026, 10, 1), dt.date(2026, 10, 28), - [insights.Query("gba_bios.bin", PAGE, 1, 300, 8.0)], None, None, - held={"gba_bios.bin"}, declared=set()) + text = insights.report(readings(queries=[insights.Query("gba_bios.bin", PAGE, 1, 300, 8.0)], + held={"gba_bios.bin"})) self.assertIn("## Google searches", text) - self.assertIn("| gba_bios.bin | /emulators/mgba/ | 300 | 0.3% | 8.0 |", text) + self.assertIn("2026-10-01 to 2026-10-28 (28 days): 1 clicks", text) self.assertNotIn("## On the site", text) self.assertNotIn("## GitHub", text) + def test_the_site_section_states_its_period(self) -> None: + goat = {"hits": [("/emulators/mgba/", 4)], "referrers": [], "visits": 4, "actions": 0} + text = insights.report(readings(goat=goat, goat_end=dt.date(2026, 11, 19))) + self.assertIn("2026-10-01 to 2026-11-19 (50 days), UTC days: 4 page views", text) + def test_names_come_from_profiles_and_the_collection(self) -> None: db = {"indexes": {"by_name": {"SCPH5501.BIN": ["x"]}}} profiles = {"p": {"files": [{"name": "bios/dsp1b.rom", "aliases": ["DSP1B.bin"]}, "str"]}} diff --git a/wiki/tools.md b/wiki/tools.md index 564092423..e01bf27d0 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -1388,7 +1388,7 @@ before a release (wiki/release-process.md). Its lines stay in | `generate_site.py` | Generate the site (this documentation) into the Starlight project in `website/` | | `sitesources.py` | Record which cited source paths each pinned upstream tree holds, for the site's source links (`--fetch` reads a tree no cache holds) | | `site_markdown.py` | Write each built page as Markdown beside its HTML (`/index.md`, named in every page's head) and `llms-full.txt`, the guides and every setup's page in one file, for the assistants that read the site. The Astro build runs it once the pages are written | -| `site_insights.py` | What readers look for and do not find, from totals only: searches that show the site but are rarely clicked, file names searched and whether the collection holds them, site searches that found nothing, broken addresses, "Did this page help?" answers, GitHub traffic and release downloads (`--days`, `--skip gsc,goatcounter,github`, `--output`). Reads Search Console, GoatCounter and GitHub with credentials kept outside the repository. [What the site counts](privacy.md) | +| `site_insights.py` | What readers look for and do not find, from totals only, each section with its period: Google searches by page against the period of the same length before (anchors merged into their page), ranked by the clicks lost against the site's own click rate at each position, searches clicked less than half that rate, searched file names the collection does not hold, site searches that found nothing, broken addresses, "Did this page help?" answers, GitHub traffic (14 days) and release downloads since the previous run (`--days`, `--skip gsc,goatcounter,github`, `--output`, `--downloads-snapshot`, default `.cache/insights/downloads.json`). Reads Search Console, GoatCounter and GitHub with credentials kept outside the repository. [What the site counts](privacy.md) | | `make_demo.py` | Record the installer demos of the README and the site into `docs_assets/demo/`. An ArkOS card with six games is built under `tmp/demo/` in a mount namespace of the user, this checkout is served on loopback, and VHS runs one tape per variant: `default` (`install.tape`, the one-line command in a terminal, the card at `/media/EASYROMS`, needs `unshare`) and `handheld` (`install-handheld.tape`, the full-screen interface at 640x480 on an ArkOS root made with `bwrap`, as its Tools menu starts it, driven by the keys gptokeyb sends for the buttons). `--variant NAME` records one (repeatable), every variant by default, the others kept. Each needs `vhs`, `ttyd` and `ffmpeg`. The default gets the README's GIF, each gets a WebM, an MP4 and a poster, held to their size targets, and an entry in `demo.json` with what it shows and its alt text. No Windows variant: under pwsh on Linux the installer's summary gives `--dest /mnt/e/bios` back. Never run by the build | | `validate_site.py` | Validate rendered metadata, heading order, image alternatives, JSON-LD, local resources, links and fragments, and the page size and search index budgets | | `indexnow.py` | List the pages a deploy changes, read against the `digests.json` the live site serves, as the IndexNow request the deploy posts once the new site is live. `--dist` names the built site, `--output` appends the request to a step output |