Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

feat(stats): solo-maintainer GitHub-data dashboard (script + dashboard)

mrbizarro151d0d248d54
diff --git a/docs/stats-data.jsonl b/docs/stats-data.jsonl
new file mode 100644
index 0000000..2efa53b
--- /dev/null
+++ b/docs/stats-data.jsonl
@@ -0,0 +1 @@
+{"date": "2026-05-22", "fetched_at": "2026-05-22T06:28:43Z", "stars": 57, "forks": 5, "open_issues": 8, "watchers": 57, "subscribers": 1, "open_prs": 1, "clones": {"count": 257, "uniques": 148}, "views": {"count": 72, "uniques": 29}, "referrers": [{"referrer": "Google", "count": 177, "uniques": 101}, {"referrer": "github.com", "count": 93, "uniques": 24}, {"referrer": "huggingface.co", "count": 69, "uniques": 42}, {"referrer": "t.co", "count": 60, "uniques": 33}, {"referrer": "reddit.com", "count": 40, "uniques": 20}, {"referrer": "DuckDuckGo", "count": 23, "uniques": 5}, {"referrer": "search.brave.com", "count": 16, "uniques": 7}, {"referrer": "chatgpt.com", "count": 12, "uniques": 3}, {"referrer": "Bing", "count": 4, "uniques": 4}, {"referrer": "mjjcommunity.com", "count": 4, "uniques": 1}], "paths": [{"path": "/mrbizarro/phosphene", "title": "Overview", "count": 869, "uniques": 504}, {"path": "/mrbizarro/phosphene/issues", "title": "/issues", "count": 136, "uniques": 67}, {"path": "/mrbizarro/phosphene/blob/main/assets/screenshot_panel_full.jpg", "title": "/blob/main/assets/screenshot_panel_full.jpg", "count": 46, "uniques": 42}, {"path": "/mrbizarro/phosphene/pulls", "title": "/pulls", "count": 38, "uniques": 27}, {"path": "/mrbizarro/phosphene/issues/8", "title": "/issues/8", "count": 37, "uniques": 18}, {"path": "/mrbizarro/phosphene/issues/4", "title": "/issues/4", "count": 25, "uniques": 16}, {"path": "/mrbizarro/phosphene/tree/dev", "title": "/tree/dev", "count": 25, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/2", "title": "/issues/2", "count": 20, "uniques": 14}, {"path": "/mrbizarro/phosphene/tree/main", "title": "/tree/main", "count": 19, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/3", "title": "/issues/3", "count": 18, "uniques": 14}], "releases": {"total": 0, "by_release": {}}}
diff --git a/docs/stats.html b/docs/stats.html
new file mode 100644
index 0000000..145c259
--- /dev/null
+++ b/docs/stats.html
@@ -0,0 +1,397 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Phosphene · stats</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="robots" content="noindex,nofollow">
+ <!--
+ Phosphene repo-stats dashboard.
+
+ Reads docs/stats-data.jsonl (appended daily by .github/workflows/
+ repo-stats.yml) and shows simple cards + sparkline charts. Pure
+ vanilla — single file, no build, no framework. Chart.js from CDN
+ is the only outside dep. View at:
+ https://mrbizarro.github.io/phosphene/stats.html
+ (Enable in repo Settings → Pages → "Deploy from a branch → main /docs"
+ on first setup.)
+
+ No login, no telemetry, no analytics-ception. The data file is
+ public because it's committed to the public repo — that's by
+ design (open dashboards build trust).
+ -->
+ <style>
+ :root {
+ --bg: #0d1117;
+ --bg-card: #161b22;
+ --bg-card-2: #1f2630;
+ --border: #30363d;
+ --text: #c9d1d9;
+ --text-dim: #8b949e;
+ --text-faint:#6e7681;
+ --accent: #58a6ff;
+ --good: #3fb950;
+ --warn: #d29922;
+ --bad: #f85149;
+ }
+ * { box-sizing: border-box; }
+ html, body {
+ margin: 0; padding: 0;
+ background: var(--bg); color: var(--text);
+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text",
+ "Segoe UI", system-ui, sans-serif;
+ min-height: 100vh;
+ }
+ a { color: var(--accent); text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ .wrap { max-width: 1100px; margin: 0 auto; padding: 28px 24px 80px; }
+ header {
+ display: flex; align-items: baseline; justify-content: space-between;
+ flex-wrap: wrap; gap: 12px; margin-bottom: 24px;
+ }
+ h1 {
+ font-size: 22px; font-weight: 600; margin: 0;
+ }
+ h1 .subtitle {
+ color: var(--text-dim); font-weight: 400; font-size: 14px;
+ margin-left: 10px;
+ }
+ .meta {
+ color: var(--text-dim); font-size: 13px;
+ }
+ .meta strong { color: var(--text); font-weight: 500; }
+ section {
+ background: var(--bg-card);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 18px;
+ }
+ h2 {
+ font-size: 13px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.05em; color: var(--text-dim); margin: 0 0 14px;
+ }
+ /* Cards row */
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: 12px;
+ }
+ .card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ }
+ .card .label {
+ color: var(--text-dim);
+ font-size: 11px; text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+ .card .value {
+ font-size: 28px; font-weight: 600; line-height: 1.1;
+ margin-top: 6px;
+ }
+ .card .delta {
+ font-size: 12px; color: var(--text-faint); margin-top: 4px;
+ }
+ .card .delta.up { color: var(--good); }
+ .card .delta.down { color: var(--bad); }
+ /* Chart blocks */
+ .chart-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ }
+ @media (max-width: 720px) {
+ .chart-row { grid-template-columns: 1fr; }
+ }
+ .chart-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ }
+ .chart-card h3 {
+ font-size: 12px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.05em; color: var(--text-dim);
+ margin: 0 0 8px;
+ }
+ .chart-card .chart-wrap {
+ position: relative; height: 180px;
+ }
+ /* Tables */
+ table {
+ width: 100%; border-collapse: collapse; font-size: 13px;
+ }
+ th, td {
+ text-align: left; padding: 7px 8px;
+ border-bottom: 1px solid var(--border);
+ }
+ th {
+ font-weight: 500; color: var(--text-dim);
+ text-transform: uppercase; font-size: 11px; letter-spacing: 0.05em;
+ }
+ td.num { text-align: right; font-variant-numeric: tabular-nums; }
+ .two-col {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
+ }
+ @media (max-width: 720px) {
+ .two-col { grid-template-columns: 1fr; }
+ }
+ .empty {
+ color: var(--text-faint); font-style: italic; padding: 20px 0;
+ text-align: center;
+ }
+ code {
+ background: var(--bg-card-2); padding: 1px 5px; border-radius: 3px;
+ font-size: 12px; font-family: ui-monospace, SFMono-Regular, monospace;
+ }
+ footer {
+ color: var(--text-faint); font-size: 12px; text-align: center;
+ margin-top: 30px;
+ }
+ </style>
+</head>
+<body>
+ <div class="wrap">
+ <header>
+ <h1>Phosphene · stats <span class="subtitle">solo-maintainer dashboard</span></h1>
+ <div class="meta" id="meta">loading…</div>
+ </header>
+
+ <!-- Big number cards: state TODAY (last snapshot) -->
+ <section>
+ <h2>Right now</h2>
+ <div class="cards" id="cards"></div>
+ </section>
+
+ <!-- Time-series charts: cumulative + daily counts -->
+ <section>
+ <h2>Over time</h2>
+ <div class="chart-row">
+ <div class="chart-card">
+ <h3>Stars · cumulative</h3>
+ <div class="chart-wrap"><canvas id="chart-stars"></canvas></div>
+ </div>
+ <div class="chart-card">
+ <h3>Forks · cumulative</h3>
+ <div class="chart-wrap"><canvas id="chart-forks"></canvas></div>
+ </div>
+ </div>
+ <div class="chart-row" style="margin-top:14px">
+ <div class="chart-card">
+ <h3>Clones per day</h3>
+ <div class="chart-wrap"><canvas id="chart-clones"></canvas></div>
+ </div>
+ <div class="chart-card">
+ <h3>Repo page views per day</h3>
+ <div class="chart-wrap"><canvas id="chart-views"></canvas></div>
+ </div>
+ </div>
+ </section>
+
+ <!-- 14-day rolling snapshots from latest fetch -->
+ <section>
+ <h2>Where traffic comes from (last 14 days)</h2>
+ <div class="two-col">
+ <div>
+ <h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top referrers</h3>
+ <table id="referrers-table"><thead><tr>
+ <th>Source</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody></tbody></table>
+ </div>
+ <div>
+ <h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top paths</h3>
+ <table id="paths-table"><thead><tr>
+ <th>Path</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody></tbody></table>
+ </div>
+ </div>
+ </section>
+
+ <footer>
+ Data lives at <code>docs/stats-data.jsonl</code>, refreshed daily by
+ <code>.github/workflows/repo-stats.yml</code>.
+ <br>
+ The GitHub Traffic API only retains 14 days; this file is how we keep
+ the history.
+ </footer>
+ </div>
+
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
+ <script>
+ // ---- load + parse the JSONL ----------------------------------------
+ async function loadRows() {
+ const r = await fetch('stats-data.jsonl', {cache: 'no-store'});
+ if (!r.ok) throw new Error('HTTP ' + r.status + ' on stats-data.jsonl');
+ const text = await r.text();
+ return text.split(/\n+/).filter(Boolean).map(l => JSON.parse(l));
+ }
+
+ // ---- small helpers --------------------------------------------------
+ const fmt = n => (n == null ? '—' : n.toLocaleString());
+ const dayAgo = (iso) => {
+ const t = new Date(iso).getTime();
+ const ms = Date.now() - t;
+ const d = Math.floor(ms / 86400000);
+ if (d === 0) return 'today';
+ if (d === 1) return 'yesterday';
+ if (d < 7) return d + 'd ago';
+ return Math.floor(d / 7) + 'w ago';
+ };
+
+ function deltaSpan(today, yesterday) {
+ if (today == null || yesterday == null) return '';
+ const d = today - yesterday;
+ if (d === 0) return '<span class="delta">no change</span>';
+ const sign = d > 0 ? '+' : '';
+ const cls = d > 0 ? 'up' : 'down';
+ return `<span class="delta ${cls}">${sign}${d.toLocaleString()} vs yday</span>`;
+ }
+
+ function renderCards(rows) {
+ const last = rows[rows.length - 1];
+ const prev = rows.length > 1 ? rows[rows.length - 2] : {};
+ const cards = [
+ {label: "Stars", value: last.stars, yday: prev.stars},
+ {label: "Forks", value: last.forks, yday: prev.forks},
+ {label: "Watchers", value: last.subscribers, yday: prev.subscribers},
+ {label: "Clones · today",value: last.clones?.count, yday: prev.clones?.count},
+ {label: "Views · today", value: last.views?.count, yday: prev.views?.count},
+ {label: "Open issues", value: last.open_issues, yday: prev.open_issues},
+ {label: "Open PRs", value: last.open_prs, yday: prev.open_prs},
+ ];
+ const total_dl = last.releases?.total ?? null;
+ if (total_dl != null && total_dl > 0) {
+ cards.push({label: "Release downloads", value: total_dl, yday: prev.releases?.total});
+ }
+ document.getElementById('cards').innerHTML = cards.map(c => `
+ <div class="card">
+ <div class="label">${c.label}</div>
+ <div class="value">${fmt(c.value)}</div>
+ ${deltaSpan(c.value, c.yday)}
+ </div>
+ `).join('');
+ }
+
+ // ---- charts ---------------------------------------------------------
+ Chart.defaults.color = '#8b949e';
+ Chart.defaults.borderColor = '#30363d';
+ Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, system-ui, sans-serif';
+ Chart.defaults.font.size = 11;
+ Chart.defaults.plugins.legend.display = false;
+
+ const COMMON_OPTS = {
+ responsive: true, maintainAspectRatio: false,
+ scales: {
+ x: { grid: { color: '#21262d' }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8 } },
+ y: { grid: { color: '#21262d' }, beginAtZero: true, ticks: { precision: 0 } },
+ },
+ plugins: { tooltip: { intersect: false, mode: 'index' } },
+ };
+
+ function lineChart(canvasId, labels, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ new Chart(el.getContext('2d'), {
+ type: 'line',
+ data: {
+ labels,
+ datasets: [{
+ data,
+ borderColor: color,
+ backgroundColor: color + '33',
+ fill: true, tension: 0.25, pointRadius: 2,
+ pointHoverRadius: 4, borderWidth: 2,
+ }]
+ },
+ options: COMMON_OPTS,
+ });
+ }
+
+ function barChart(canvasId, labels, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ new Chart(el.getContext('2d'), {
+ type: 'bar',
+ data: {
+ labels,
+ datasets: [{ data, backgroundColor: color, borderWidth: 0 }]
+ },
+ options: COMMON_OPTS,
+ });
+ }
+
+ function renderCharts(rows) {
+ // X-axis labels in MM-DD so they fit on mobile.
+ const labels = rows.map(r => r.date?.slice(5) || '');
+ lineChart('chart-stars', labels, rows.map(r => r.stars ?? null), '#58a6ff');
+ lineChart('chart-forks', labels, rows.map(r => r.forks ?? null), '#8957e5');
+ barChart ('chart-clones', labels, rows.map(r => r.clones?.count ?? 0), '#3fb950');
+ barChart ('chart-views', labels, rows.map(r => r.views?.count ?? 0), '#d29922');
+ }
+
+ function renderTables(rows) {
+ const last = rows[rows.length - 1] || {};
+ const refs = last.referrers || [];
+ const paths = last.paths || [];
+ const refBody = document.querySelector('#referrers-table tbody');
+ const pathBody = document.querySelector('#paths-table tbody');
+ if (refs.length === 0) {
+ refBody.innerHTML = '<tr><td colspan="3" class="empty">no referrer data yet</td></tr>';
+ } else {
+ refBody.innerHTML = refs.map(r => `
+ <tr><td>${escapeHtml(r.referrer)}</td>
+ <td class="num">${fmt(r.count)}</td>
+ <td class="num">${fmt(r.uniques)}</td></tr>
+ `).join('');
+ }
+ if (paths.length === 0) {
+ pathBody.innerHTML = '<tr><td colspan="3" class="empty">no path data yet</td></tr>';
+ } else {
+ pathBody.innerHTML = paths.map(p => `
+ <tr><td><a href="https://github.com/mrbizarro/phosphene${escapeAttr(p.path)}"
+ target="_blank" rel="noopener">${escapeHtml(p.path)}</a></td>
+ <td class="num">${fmt(p.count)}</td>
+ <td class="num">${fmt(p.uniques)}</td></tr>
+ `).join('');
+ }
+ }
+
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, c =>
+ ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])
+ );
+ }
+ function escapeAttr(s) { return escapeHtml(s); }
+
+ function renderMeta(rows) {
+ const last = rows[rows.length - 1];
+ const meta = document.getElementById('meta');
+ if (!last) { meta.textContent = 'no data yet — first snapshot due 03:17 UTC'; return; }
+ meta.innerHTML = `
+ <strong>${rows.length}</strong> daily snapshots ·
+ last refresh <strong>${escapeHtml(dayAgo(last.fetched_at))}</strong>
+ (${escapeHtml(last.fetched_at)}) ·
+ <a href="https://github.com/mrbizarro/phosphene" target="_blank" rel="noopener">repo ↗</a>
+ `;
+ }
+
+ (async function main() {
+ try {
+ const rows = await loadRows();
+ rows.sort((a, b) => (a.date || '') < (b.date || '') ? -1 : 1);
+ renderMeta(rows);
+ if (!rows.length) return;
+ renderCards(rows);
+ renderCharts(rows);
+ renderTables(rows);
+ } catch (e) {
+ document.getElementById('meta').innerHTML =
+ `<span style="color:var(--bad)">could not load stats-data.jsonl: ${escapeHtml(e.message)}</span>`;
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/scripts/fetch_repo_stats.py b/scripts/fetch_repo_stats.py
new file mode 100644
index 0000000..ca8682c
--- /dev/null
+++ b/scripts/fetch_repo_stats.py
@@ -0,0 +1,284 @@
+#!/usr/bin/env python3
+"""Fetch GitHub repo stats and append a daily snapshot to docs/stats-data.jsonl.
+
+Runs from .github/workflows/repo-stats.yml on a 24h cron. The GitHub Action
+default token has push access to the repo it runs in, which is exactly what
+the Traffic API (/repos/:owner/:repo/traffic/*) requires.
+
+Why a custom script (not the off-the-shelf `github-repo-stats` Action):
+- Mr Bizarro asked for "stable, has historic data, basic stuff" — keep the
+ surface tiny and readable top-to-bottom.
+- No build step, no node, no docker. Just stdlib urllib.
+- Schema lives next to us; we can add fields later without renegotiating
+ with an upstream marketplace action.
+
+Output schema (one JSON object per UTC day, newline-delimited):
+
+ {
+ "date": "2026-05-22", # UTC YYYY-MM-DD (the day fetched)
+ "fetched_at": "...Z", # full ISO timestamp
+ "clones": {"count": N, "uniques": N}, # daily-window slice
+ "views": {"count": N, "uniques": N},
+ "stars": N, # total today
+ "forks": N,
+ "open_issues": N,
+ "open_prs": N,
+ "watchers": N,
+ "subscribers": N, # actual GitHub watch
+ "referrers": [{"referrer": "...", "count": N, "uniques": N}, ...],
+ "paths": [{"path": "...", "count": N, "uniques": N, "title": "..."}, ...]
+ }
+
+The clones/views counts here are the SUM of the latest 24 hours of the
+Traffic API's 15-day day-array. The full 15-day curve from the API rotates
+out by tomorrow, so the only way to retain it is to snapshot daily and
+append. The dashboard reads the JSONL append-only.
+
+Idempotent: if today's date already has an entry, the new fetch REPLACES
+it (so re-runs in the same UTC day don't duplicate rows).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+from datetime import datetime, timezone
+from pathlib import Path
+
+# ---- config --------------------------------------------------------------
+
+REPO = os.environ.get("PHOSPHENE_REPO", "mrbizarro/phosphene")
+TOKEN = (
+ os.environ.get("GH_STATS_TOKEN") # explicit override
+ or os.environ.get("GITHUB_TOKEN") # default in GH Actions
+ or ""
+).strip()
+OUTPUT = Path(__file__).resolve().parent.parent / "docs" / "stats-data.jsonl"
+
+API = "https://api.github.com"
+UA = "phosphene-repo-stats/1"
+
+if not TOKEN:
+ sys.stderr.write(
+ "ERROR: no GitHub token. Set GH_STATS_TOKEN or run inside GitHub "
+ "Actions (which injects GITHUB_TOKEN automatically).\n"
+ )
+ sys.exit(1)
+
+# ---- http helpers --------------------------------------------------------
+
+
+def _get(path: str, accept: str = "application/vnd.github+json") -> dict | list:
+ """GET an API path. Raises on non-2xx so the Action surfaces failures."""
+ url = path if path.startswith("http") else f"{API}{path}"
+ req = urllib.request.Request(
+ url,
+ headers={
+ "Authorization": f"Bearer {TOKEN}",
+ "Accept": accept,
+ "User-Agent": UA,
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=20) as resp:
+ return json.loads(resp.read())
+ except urllib.error.HTTPError as exc:
+ body = exc.read().decode("utf-8", errors="replace")
+ sys.stderr.write(f"HTTP {exc.code} on {url}: {body[:300]}\n")
+ raise
+
+
+def _get_paginated(path: str, accept: str = "application/vnd.github+json") -> list:
+ """Drain ?per_page=100 pages. Used for stargazers timeline."""
+ out: list = []
+ page = 1
+ sep = "&" if "?" in path else "?"
+ while True:
+ chunk = _get(f"{path}{sep}per_page=100&page={page}", accept=accept)
+ if not chunk:
+ break
+ out.extend(chunk)
+ if len(chunk) < 100:
+ break
+ page += 1
+ if page > 200: # safety — 20k stars is enough
+ break
+ return out
+
+
+# ---- metric fetchers -----------------------------------------------------
+
+
+def fetch_repo() -> dict:
+ """The repo object — covers stars/forks/issues/watchers."""
+ r = _get(f"/repos/{REPO}")
+ return {
+ "stars": int(r.get("stargazers_count", 0)),
+ "forks": int(r.get("forks_count", 0)),
+ "open_issues": int(r.get("open_issues_count", 0)), # includes PRs
+ "watchers": int(r.get("watchers_count", 0)), # alias for stars
+ "subscribers": int(r.get("subscribers_count", 0)), # actual "watch"
+ }
+
+
+def fetch_open_prs() -> int:
+ """The repo's open_issues_count includes PRs. Disambiguate so the
+ dashboard can show issues and PRs separately."""
+ # /search counts are cheap and don't paginate full result lists.
+ q = f"repo:{REPO}+is:pr+is:open"
+ r = _get(f"/search/issues?q={q}")
+ return int(r.get("total_count", 0))
+
+
+def fetch_clones() -> tuple[int, int]:
+ """Last 24 hours of clones (the most recent entry in the 15-day array).
+ Returns (count, uniques) for the most-recent day so we can graph day-
+ over-day. Older entries get permanently archived in previous JSONL
+ rows."""
+ r = _get(f"/repos/{REPO}/traffic/clones")
+ days = r.get("clones") or []
+ if not days:
+ return 0, 0
+ today = days[-1]
+ return int(today.get("count", 0)), int(today.get("uniques", 0))
+
+
+def fetch_views() -> tuple[int, int]:
+ """Last 24h of repo page views — same shape as clones."""
+ r = _get(f"/repos/{REPO}/traffic/views")
+ days = r.get("views") or []
+ if not days:
+ return 0, 0
+ today = days[-1]
+ return int(today.get("count", 0)), int(today.get("uniques", 0))
+
+
+def fetch_referrers() -> list[dict]:
+ """Top 10 referring domains over the rolling 14-day window. We snapshot
+ the 14d aggregate every day rather than try to derive a per-day
+ breakdown (the API doesn't give one)."""
+ r = _get(f"/repos/{REPO}/traffic/popular/referrers")
+ if not isinstance(r, list):
+ return []
+ return [
+ {
+ "referrer": x.get("referrer", "?"),
+ "count": int(x.get("count", 0)),
+ "uniques": int(x.get("uniques", 0)),
+ }
+ for x in r[:10]
+ ]
+
+
+def fetch_paths() -> list[dict]:
+ """Top 10 paths viewed over the rolling 14d. Tells us which docs are
+ actually getting read (README vs STATE vs ROADMAP, etc)."""
+ r = _get(f"/repos/{REPO}/traffic/popular/paths")
+ if not isinstance(r, list):
+ return []
+ return [
+ {
+ "path": x.get("path", "?"),
+ "title": (x.get("title", "") or "")[:120],
+ "count": int(x.get("count", 0)),
+ "uniques": int(x.get("uniques", 0)),
+ }
+ for x in r[:10]
+ ]
+
+
+def fetch_release_downloads() -> dict:
+ """Cumulative downloads per release asset. GitHub provides no time
+ series here, so we just take a snapshot — the dashboard can derive
+ deltas across snapshots itself. Empty when the repo has no releases
+ (Phosphene currently ships via Pinokio clone, not release binaries)."""
+ try:
+ rs = _get(f"/repos/{REPO}/releases?per_page=100")
+ if not isinstance(rs, list):
+ return {}
+ except urllib.error.HTTPError:
+ return {}
+ total = 0
+ per_release: dict = {}
+ for rel in rs:
+ tag = rel.get("tag_name", "?")
+ rel_total = 0
+ for a in rel.get("assets") or []:
+ n = int(a.get("download_count", 0))
+ rel_total += n
+ total += n
+ per_release[tag] = rel_total
+ return {"total": total, "by_release": per_release}
+
+
+# ---- main ----------------------------------------------------------------
+
+
+def main() -> int:
+ now = datetime.now(timezone.utc)
+ today = now.strftime("%Y-%m-%d")
+ iso_now = now.strftime("%Y-%m-%dT%H:%M:%SZ")
+ print(f"[{iso_now}] fetching stats for {REPO}", flush=True)
+
+ repo = fetch_repo()
+ print(f" repo: {repo}", flush=True)
+ open_prs = fetch_open_prs()
+ repo["open_prs"] = open_prs
+ # open_issues from the repo API includes PRs — subtract to disambiguate.
+ repo["open_issues"] = max(0, repo["open_issues"] - open_prs)
+ print(f" prs: {open_prs} (open_issues adjusted to {repo['open_issues']})", flush=True)
+
+ clones_count, clones_uniques = fetch_clones()
+ views_count, views_uniques = fetch_views()
+ print(f" clones today: {clones_count} ({clones_uniques} unique)", flush=True)
+ print(f" views today: {views_count} ({views_uniques} unique)", flush=True)
+
+ referrers = fetch_referrers()
+ paths = fetch_paths()
+ releases = fetch_release_downloads()
+ print(f" referrers: {len(referrers)} paths: {len(paths)} "
+ f"release downloads total: {releases.get('total', 0)}", flush=True)
+
+ row = {
+ "date": today,
+ "fetched_at": iso_now,
+ **repo,
+ "clones": {"count": clones_count, "uniques": clones_uniques},
+ "views": {"count": views_count, "uniques": views_uniques},
+ "referrers": referrers,
+ "paths": paths,
+ "releases": releases,
+ }
+
+ # Idempotent append: replace today's row if it already exists.
+ OUTPUT.parent.mkdir(parents=True, exist_ok=True)
+ existing: list[dict] = []
+ if OUTPUT.exists():
+ for line in OUTPUT.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ if obj.get("date") == today:
+ continue # drop today's prior row
+ existing.append(obj)
+ except json.JSONDecodeError:
+ continue
+ existing.append(row)
+ OUTPUT.write_text(
+ "\n".join(json.dumps(r, ensure_ascii=False) for r in existing) + "\n",
+ encoding="utf-8",
+ )
+ print(f" wrote {len(existing)} rows → {OUTPUT.relative_to(OUTPUT.parent.parent)}",
+ flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())