Playground site: airplay serve (ranking, artist history and forecast, what-if on chart situation, backtest summary) at idiotmaxxing.com/airplay via a Traefik file route; daily collection refreshes the forecasts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 02:21:41 +00:00
co-authored by Claude Opus 5.5
parent eededc7571
commit 387502ebfa
9 changed files with 806 additions and 2 deletions
+384
View File
@@ -0,0 +1,384 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Airplay Predictor</title>
<style>
:root {
--bg: #f7f6f2; --panel: #ffffff; --ink: #1d1d1b; --muted: #6b6a64; --line: #e4e2da;
--accent: #c2410c; --accent-soft: #fde7d9; --good: #15803d; --bad: #b91c1c;
--p3: #2563eb; --p4: #c2410c; --p5: #7c3aed; --p6: #0f766e; --p8: #a16207;
--shadow: 0 1px 2px rgba(0,0,0,.05), 0 8px 24px rgba(0,0,0,.06);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #141412; --panel: #1d1d1a; --ink: #ecebe6; --muted: #9b9a92; --line: #2f2e2a;
--accent: #fb923c; --accent-soft: #3a2316; --good: #4ade80; --bad: #f87171;
--p3: #60a5fa; --p4: #fb923c; --p5: #a78bfa; --p6: #2dd4bf; --p8: #facc15;
--shadow: 0 1px 2px rgba(0,0,0,.3), 0 8px 24px rgba(0,0,0,.3);
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
header { padding: 28px 24px 8px; max-width: 1240px; margin: 0 auto; }
h1 { margin: 0; font-size: 26px; letter-spacing: -.02em; }
h1 span { color: var(--accent); }
.sub { color: var(--muted); margin-top: 4px; font-size: 14px; }
nav { display: flex; gap: 4px; margin-top: 18px; border-bottom: 1px solid var(--line); }
nav button { background: none; border: 0; padding: 10px 14px; font: inherit; color: var(--muted); cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; }
nav button.on { color: var(--ink); border-color: var(--accent); font-weight: 600; }
main { max-width: 1240px; margin: 0 auto; padding: 16px 24px 60px; }
.controls { display: flex; flex-wrap: wrap; gap: 14px 22px; align-items: end; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; box-shadow: var(--shadow); }
.ctl { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.ctl b { color: var(--ink); text-transform: none; letter-spacing: 0; font-size: 14px; }
input[type=range] { width: 220px; accent-color: var(--accent); }
input[type=search], select { font: inherit; padding: 7px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); min-width: 160px; }
label.chk { display: flex; gap: 6px; align-items: center; text-transform: none; letter-spacing: 0; font-size: 14px; color: var(--ink); }
.tablewrap { margin-top: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow-x: auto; box-shadow: var(--shadow); }
table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
th, td { padding: 9px 12px; text-align: right; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { font-size: 12px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; cursor: pointer; user-select: none; position: sticky; top: 0; background: var(--panel); }
th.l, td.l { text-align: left; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: var(--accent-soft); }
td.name { font-weight: 600; }
td.name small { color: var(--muted); font-weight: 400; margin-left: 6px; }
.bar { display: inline-flex; align-items: center; gap: 8px; }
.bar i { display: inline-block; height: 8px; border-radius: 4px; background: var(--accent); }
.cell { display: inline-block; min-width: 44px; padding: 2px 6px; border-radius: 6px; text-align: center; font-size: 13px; }
.more { display: block; margin: 12px auto; font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--ink); cursor: pointer; }
.empty { padding: 40px; text-align: center; color: var(--muted); }
/* drawer */
#shade { position: fixed; inset: 0; background: rgba(0,0,0,.35); opacity: 0; pointer-events: none; transition: opacity .2s; }
#shade.on { opacity: 1; pointer-events: auto; }
#drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(760px, 100vw); background: var(--panel); transform: translateX(100%); transition: transform .25s ease; overflow-y: auto; box-shadow: -10px 0 40px rgba(0,0,0,.2); }
#drawer.on { transform: none; }
.dhead { display: flex; gap: 16px; align-items: center; padding: 20px 22px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); z-index: 1; }
.dhead img { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; background: var(--line); }
.dhead h2 { margin: 0; font-size: 22px; }
.dhead .x { margin-left: auto; font-size: 22px; background: none; border: 0; color: var(--muted); cursor: pointer; }
.sec { padding: 16px 22px; border-bottom: 1px solid var(--line); }
.sec h3 { margin: 0 0 10px; font-size: 13px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
.kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; }
.kpi { background: var(--bg); border-radius: 10px; padding: 10px 12px; }
.kpi div { font-size: 12px; color: var(--muted); }
.kpi b { font-size: 22px; }
.kpi .d { font-size: 13px; margin-left: 6px; }
.up { color: var(--good); } .down { color: var(--bad); }
.legend { display: flex; flex-wrap: wrap; gap: 12px; font-size: 12px; color: var(--muted); margin-top: 6px; }
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 4px; vertical-align: -1px; }
svg text { fill: var(--muted); font-size: 11px; }
.wi { display: grid; grid-template-columns: 1fr; gap: 12px; }
.wi .row { display: grid; grid-template-columns: 210px 1fr 60px; align-items: center; gap: 10px; font-size: 14px; }
.wi input[type=range] { width: 100%; }
.wtable td, .wtable th { padding: 6px 8px; }
.note { color: var(--muted); font-size: 13px; }
.tracks { columns: 2; font-size: 14px; } .tracks div { break-inside: avoid; padding: 2px 0; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { background: var(--bg); border-radius: 999px; padding: 3px 10px; font-size: 13px; }
/* model tab */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px; box-shadow: var(--shadow); }
.card h3 { margin-top: 0; }
.card p { color: var(--muted); }
.prose { max-width: 760px; }
.prose li { margin: 6px 0; }
@media (max-width: 640px) {
header, main { padding-left: 16px; padding-right: 16px; }
input[type=range] { width: 100%; }
.ctl { width: 100%; }
.wi .row { grid-template-columns: 1fr 60px; } .wi .row label { grid-column: 1 / -1; }
.tracks { columns: 1; }
.hide-sm { display: none; }
}
</style>
</head>
<body>
<header>
<h1>Airplay <span>Predictor</span></h1>
<div class="sub" id="sub">Loading…</div>
<nav>
<button class="on" data-tab="rank">Ranking</button>
<button data-tab="model">How good is it?</button>
</nav>
</header>
<main>
<section id="tab-rank">
<div class="controls">
<div class="ctl">Week <b id="hlabel">—</b><input type="range" id="h" min="1" max="12" value="4"></div>
<div class="ctl">Station
<select id="ch">
<option value="any">Any DR station</option>
<option value="p3">P3</option>
<option value="p4">P4 (best region)</option>
<option value="p5">P5</option>
<option value="p6beat">P6 Beat</option>
<option value="p8jazz">P8 Jazz</option>
</select>
</div>
<div class="ctl">Sort by
<select id="sort">
<option value="p">Chance of rotation</option>
<option value="plays">Expected plays</option>
<option value="up">Biggest climbers</option>
</select>
</div>
<div class="ctl">Artist <input type="search" id="q" placeholder="Search…"></div>
<div class="ctl"><label class="chk"><input type="checkbox" id="dk"> Danish acts only</label></div>
</div>
<div class="tablewrap">
<table>
<thead><tr>
<th class="l">#</th><th class="l">Artist</th><th>Chance</th>
<th class="hide-sm">P3</th><th class="hide-sm">P4</th><th class="hide-sm">P5</th><th class="hide-sm">P6</th><th class="hide-sm">P8</th>
<th>Plays / wk (80%)</th>
</tr></thead>
<tbody id="rows"><tr><td colspan="9" class="empty">Loading…</td></tr></tbody>
</table>
</div>
<button class="more" id="more" hidden>Show more</button>
<p class="note">Chance = probability the artist is in rotation (plays at or above the station's weekly threshold) in the chosen week. "Biggest climbers" ranks by expected plays in that week versus the latest week. Click an artist for history and a what-if.</p>
</section>
<section id="tab-model" hidden>
<div class="prose">
<h2>What the model does</h2>
<p>For every artist DR has played, it forecasts each DR music station's weekly plays 1–12 weeks ahead, and the chance that the artist is "in rotation" (at or above the station's weekly play threshold). It learns from 51 weeks of DR's per-artist weekly play counts plus the artist's IFPI chart history (Track Top-40, Airplay Top-20).</p>
<p id="taus" class="note"></p>
</div>
<h2>Backtest</h2>
<p class="note prose">Walk-forward: for each week from week 27, the models are fitted only on what was known at the time and forecast 1, 4 and 8 weeks ahead. "Adds" are rows where the artist was not in rotation at the time of the forecast, which is the hard and interesting part. Skill above 0 means better than the baseline.</p>
<div class="cards" id="cards"></div>
<div class="prose">
<h2>Known limits</h2>
<ul>
<li><b>The artist pool is selected.</b> It holds only artists DR played in mid-November 2026, so every artist had airplay at the end of the window. Scores for the last weeks are flattered.</li>
<li><b>Not yet "if they release a song on date X".</b> The ranking is expected airplay given current form and chart situation. Conditioning on a release needs release dates (being collected).</li>
<li><b>Rotation thresholds are estimates</b> until DR's weekly rotation lists are parsed.</li>
<li><b>Christmas</b> is only seen once, as history. Forecasts for weeks 48–52 don't know about Christmas songs yet.</li>
</ul>
</div>
</section>
</main>
<div id="shade"></div>
<aside id="drawer" aria-hidden="true"></aside>
<script>
const BASE = location.pathname.replace(/\/(index\.html)?$/, '');
const API = p => fetch(BASE + '/api/' + p).then(r => r.json());
const GROUPS = [['p3', 'P3'], ['p4', 'P4'], ['p5', 'P5'], ['p6beat', 'P6'], ['p8jazz', 'P8']];
const P4S = ['p4kbh','p4sjaelland','p4fyn','p4syd','p4trekanten','p4vest','p4aarhus','p4nord','p4bornholm','p4esbjerg'];
const COLORS = { p3: 'var(--p3)', p4: 'var(--p4)', p5: 'var(--p5)', p6beat: 'var(--p6)', p8jazz: 'var(--p8)' };
let meta = null, data = { 1: null }, shown = 100, current = [];
const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const pct = p => p == null ? '—' : (p >= 0.995 ? '>99' : p < 0.005 ? '<1' : Math.round(p * 100)) + '%';
const fmtDate = s => new Date(s + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });
function chanP(r, g) {
if (g === 'any') return r.p_any;
if (g === 'p4') return Math.max(...P4S.map(c => r.p[c] ?? 0));
return r.p[g];
}
function chanPlays(r, g) {
if (g === 'any') return r.mean;
if (g === 'p4') return P4S.reduce((s, c) => s + (r.plays[c] ?? 0), 0) / P4S.length;
return r.plays[g];
}
function heat(p) {
if (p == null) return '';
const a = Math.min(1, Math.max(0, p));
return `background: color-mix(in srgb, var(--accent) ${Math.round(a * 85)}%, transparent); color: ${a > .55 ? '#fff' : 'inherit'}`;
}
async function loadMeta() {
meta = await API('meta');
if (!meta.ready) { $('sub').textContent = 'No forecasts yet: run `airplay model rank`.'; return; }
$('h').max = meta.horizons.length;
$('sub').textContent = `DR plays through the week of ${fmtDate(meta.origin_week)} · forecasts made ${meta.made_at.slice(0, 10)} · model ${meta.model}`;
if (meta.tau) $('taus').textContent = 'Rotation thresholds (plays per week): ' + meta.channels.map((c, i) => `${c} ${meta.tau[i]}`).join(', ') + '.';
renderModel();
}
async function loadRank() {
const h = +$('h').value;
const hz = meta.horizons.find(x => x.h === h);
$('hlabel').textContent = hz ? `${fmtDate(hz.week)} (+${h} wk)` : `+${h} wk`;
if (!data[h]) data[h] = (await API('rank?h=' + h)).rows;
if (!data[1]) data[1] = (await API('rank?h=1')).rows;
render();
}
function render() {
const h = +$('h').value, g = $('ch').value, sort = $('sort').value, q = $('q').value.trim().toLowerCase(), dk = $('dk').checked;
const now = Object.fromEntries((data[1] || []).map(r => [r.id, r]));
let rows = data[h].filter(r => (!q || r.name.toLowerCase().includes(q)) && (!dk || r.danish));
const key = sort === 'p' ? r => [chanP(r, g) ?? 0, chanPlays(r, g) ?? 0]
: sort === 'plays' ? r => [chanPlays(r, g) ?? 0, 0]
: r => [(chanPlays(r, g) ?? 0) - (chanPlays(now[r.id] || r, g) ?? 0), 0];
rows = rows.map(r => [key(r), r]).sort((a, b) => b[0][0] - a[0][0] || b[0][1] - a[0][1]).map(x => x[1]);
current = rows;
const body = rows.slice(0, shown).map((r, i) => {
const p = chanP(r, g), pl = chanPlays(r, g);
const range = g === 'any' ? ` <small class="note">(${Math.round(r.lo)}–${Math.round(r.hi)})</small>` : '';
return `<tr data-id="${esc(r.id)}">
<td class="l">${i + 1}</td>
<td class="l name">${esc(r.name)}${r.danish ? '<small>DK</small>' : ''}</td>
<td><span class="bar"><i style="width:${Math.round((p ?? 0) * 70)}px"></i>${pct(p)}</span></td>
${GROUPS.map(([c]) => `<td class="hide-sm"><span class="cell" style="${heat(chanP(r, c))}">${pct(chanP(r, c))}</span></td>`).join('')}
<td>${pl == null ? '—' : pl.toFixed(pl < 10 ? 1 : 0)}${range}</td>
</tr>`;
}).join('');
$('rows').innerHTML = body || '<tr><td colspan="9" class="empty">No artists match.</td></tr>';
$('more').hidden = rows.length <= shown;
}
// ---------- artist drawer ----------
function openDrawer(html) { $('drawer').innerHTML = html; $('drawer').classList.add('on'); $('shade').classList.add('on'); $('drawer').setAttribute('aria-hidden', 'false'); }
function closeDrawer() { $('drawer').classList.remove('on'); $('shade').classList.remove('on'); $('drawer').setAttribute('aria-hidden', 'true'); }
function historyChart(a) {
// Weekly plays: P3, P4 (mean of regions), P5, P6, P8 as lines, then the forecast of total plays as a band.
const W = 700, H = 220, L = 34, R = 10, T = 10, B = 26;
const n = a.weeks.length, f = a.forecasts.length;
const series = GROUPS.map(([g]) => g === 'p4'
? a.weeks.map((_, i) => P4S.reduce((s, c) => s + (a.plays[c]?.[i] ?? 0), 0) / P4S.length)
: (a.plays[g] || []).slice());
const total = a.weeks.map((_, i) => Object.values(a.plays).reduce((s, v) => s + (v[i] ?? 0), 0));
const maxY = Math.max(5, ...series.flat(), ...a.forecasts.map(x => (x.hi ?? 0) / 4), ...total.map(t => t / 4));
const X = i => L + (W - L - R) * i / (n + f - 1);
const Y = v => T + (H - T - B) * (1 - v / maxY);
let s = `<svg viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="Weekly plays per station">`;
for (let k = 0; k <= 4; k++) {
const v = maxY * k / 4;
s += `<line x1="${L}" x2="${W - R}" y1="${Y(v)}" y2="${Y(v)}" stroke="var(--line)"/><text x="${L - 6}" y="${Y(v) + 4}" text-anchor="end">${Math.round(v)}</text>`;
}
s += `<rect x="${X(n - 0.5)}" y="${T}" width="${X(n + f - 1) - X(n - 0.5)}" height="${H - T - B}" fill="var(--accent-soft)" opacity=".6"/>`;
s += `<text x="${X(n - 0.3)}" y="${T + 12}">forecast</text>`;
// forecast band of total plays scaled to "per station" (÷ 4 so it shares the axis), labelled
if (f) {
const up = a.forecasts.map((x, i) => `${X(n + i)},${Y((x.hi ?? 0) / 4)}`).join(' ');
const dn = a.forecasts.map((x, i) => `${X(n + i)},${Y((x.lo ?? 0) / 4)}`).reverse().join(' ');
s += `<polygon points="${up} ${dn}" fill="var(--muted)" opacity=".18"/>`;
s += `<polyline points="${X(n - 1)},${Y(total[n - 1] / 4)} ${a.forecasts.map((x, i) => `${X(n + i)},${Y((x.mean ?? 0) / 4)}`).join(' ')}" fill="none" stroke="var(--muted)" stroke-width="2" stroke-dasharray="4 3"/>`;
s += `<polyline points="${total.map((t, i) => `${X(i)},${Y(t / 4)}`).join(' ')}" fill="none" stroke="var(--muted)" stroke-width="1.5" opacity=".6"/>`;
}
GROUPS.forEach(([g], k) => {
const v = series[k];
if (!v.some(x => x > 0)) return;
s += `<polyline points="${v.map((y, i) => `${X(i)},${Y(y)}`).join(' ')}" fill="none" stroke="${COLORS[g]}" stroke-width="2"/>`;
});
[0, Math.floor(n / 2), n - 1].forEach(i => s += `<text x="${X(i)}" y="${H - 8}" text-anchor="middle">${fmtDate(a.weeks[i])}</text>`);
if (f) s += `<text x="${X(n + f - 1)}" y="${H - 8}" text-anchor="end">${fmtDate(a.forecasts[f - 1].week)}</text>`;
s += '</svg>';
s += `<div class="legend">${GROUPS.map(([g, l]) => `<span><i style="background:${COLORS[g]}"></i>${l}${g === 'p4' ? ' (avg region)' : ''}</span>`).join('')}<span><i style="background:var(--muted)"></i>All DR ÷ 4, forecast with 80% band</span></div>`;
return s;
}
async function showArtist(id) {
openDrawer('<div class="sec">Loading…</div>');
const a = await API('artist?id=' + encodeURIComponent(id));
if (a.error) { openDrawer(`<div class="sec">${esc(a.error)}</div>`); return; }
const h = +$('h').value;
const fc = a.forecasts.find(x => x.h === h) || a.forecasts[0] || {};
const facts = [a.country, a.description, a.debut ? `active since ${a.debut}` : null].filter(Boolean).map(esc).join(' · ');
const runs = {};
a.charts.forEach(c => { const k = c.chart + '|' + c.title; (runs[k] ??= { ...c, weeks: 0, best: 99, first: c }); runs[k].weeks++; runs[k].best = Math.min(runs[k].best, c.position); runs[k].first = c; });
const runList = Object.values(runs).slice(0, 12);
openDrawer(`
<div class="dhead">
${a.image ? `<img src="${esc(a.image)}" alt="">` : '<img alt="">'}
<div><h2>${esc(a.name)}</h2><div class="note">${facts}</div></div>
<button class="x" aria-label="Close" onclick="closeDrawer()">×</button>
</div>
<div class="sec">
<h3>Week of ${fc.week ? fmtDate(fc.week) : '—'} (+${fc.h ?? h} weeks)</h3>
<div class="kpis">
<div class="kpi"><div>Any DR station</div><b>${pct(fc.p_any)}</b></div>
${GROUPS.map(([g, l]) => `<div class="kpi"><div>${l}</div><b>${pct(chanP(fc, g))}</b></div>`).join('')}
<div class="kpi"><div>Plays that week</div><b>${Math.round(fc.mean ?? 0)}</b> <span class="note">${Math.round(fc.lo ?? 0)}–${Math.round(fc.hi ?? 0)}</span></div>
</div>
</div>
<div class="sec"><h3>Weekly plays, last 51 weeks and next 12</h3>${historyChart(a)}</div>
<div class="sec"><h3>What if…</h3><div id="wi" class="note">Loading the model…</div></div>
${a.top_tracks.length ? `<div class="sec"><h3>Most played on DR (all time)</h3><div class="tracks">${a.top_tracks.map(t => `<div>${esc(t.title)} <span class="note">${t.total}</span></div>`).join('')}</div></div>` : ''}
${runList.length ? `<div class="sec"><h3>Chart runs (IFPI)</h3><div class="chips">${runList.map(r => `<span class="chip">${r.chart === 't40' ? 'Track Top-40' : 'Airplay Top-20'}: ${esc(r.title)}, peak #${r.best}, ${r.weeks} wk, ${r.first.year}</span>`).join('')}</div></div>` : ''}
`);
whatIfUI(a, h);
}
function whatIfUI(a, h) {
const box = $('wi');
box.innerHTML = `<div class="wi">
<div class="row"><label for="wi-h">Weeks ahead</label><input type="range" id="wi-h" min="1" max="${meta.horizons.length}" value="${h}"><b id="wi-hv"></b></div>
<div class="row"><label for="wi-e">New chart entry, weeks ago</label><input type="range" id="wi-e" min="-1" max="26" value="-1"><b id="wi-ev"></b></div>
<div class="row"><label for="wi-t">Track Top-40 position now</label><input type="range" id="wi-t" min="0" max="40" value="0"><b id="wi-tv"></b></div>
<div class="row"><label for="wi-a">Airplay Top-20 position now</label><input type="range" id="wi-a" min="0" max="20" value="0"><b id="wi-av"></b></div>
<div id="wi-out"></div>
<p class="note">Change the artist's chart situation (as if it were true this week) and see how the model's forecast moves. "New chart entry" stands in for a release that charted, until release dates are in the model.</p>
</div>`;
let init = false, timer = null;
const label = () => {
$('wi-hv').textContent = '+' + $('wi-h').value;
$('wi-ev').textContent = $('wi-e').value < 0 ? 'none' : $('wi-e').value;
$('wi-tv').textContent = +$('wi-t').value ? '#' + $('wi-t').value : 'off';
$('wi-av').textContent = +$('wi-a').value ? '#' + $('wi-a').value : 'off';
};
const run = async () => {
label();
let qs = `id=${encodeURIComponent(a.id)}&h=${$('wi-h').value}`;
if (init) qs += `&entry=${$('wi-e').value < 0 ? 'none' : $('wi-e').value}&t40=${$('wi-t').value}&air=${$('wi-a').value}`;
const r = await fetch(BASE + '/api/whatif?' + qs);
if (r.status === 503) { $('wi-out').innerHTML = '<p class="note">The model is still loading on the server; try again in a minute.</p>'; return; }
const w = await r.json();
if (w.error) { $('wi-out').innerHTML = `<p class="note">${esc(w.error)}</p>`; return; }
if (!init) {
init = true;
$('wi-e').value = w.current.entry == null ? -1 : Math.min(26, w.current.entry);
$('wi-t').value = w.current.t40; $('wi-a').value = w.current.air;
label();
}
const d = (x, y, f) => { const v = y - x; if (Math.abs(v) < 0.005 * (f === 'p' ? 1 : 100)) return ''; return `<span class="d ${v > 0 ? 'up' : 'down'}">${v > 0 ? '+' : ''}${f === 'p' ? Math.round(v * 100) + ' pts' : Math.round(v)}</span>`; };
const rows = [['Any DR station', w.base.p_any, w.scenario.p_any]].concat(GROUPS.map(([g, l]) => [l, chanP(w.base, g), chanP(w.scenario, g)]));
$('wi-out').innerHTML = `<p class="note">Week of ${fmtDate(w.week)}. Now: ${w.current.t40 ? 'Track Top-40 #' + w.current.t40 : 'not on the Track Top-40'}, ${w.current.air ? 'Airplay Top-20 #' + w.current.air : 'not on the Airplay Top-20'}, ${w.current.entry == null ? 'no chart entry on record' : 'latest new chart entry ' + w.current.entry + ' weeks ago'}.</p>
<div class="kpis">${rows.map(([l, b, s]) => `<div class="kpi"><div>${l}</div><b>${pct(s)}</b>${d(b, s, 'p')}<div>was ${pct(b)}</div></div>`).join('')}
<div class="kpi"><div>Plays that week</div><b>${Math.round(w.scenario.mean)}</b>${d(w.base.mean, w.scenario.mean, 'n')}<div>was ${Math.round(w.base.mean)}</div></div></div>`;
};
['wi-h', 'wi-e', 'wi-t', 'wi-a'].forEach(id => $(id).addEventListener('input', () => { label(); clearTimeout(timer); timer = setTimeout(run, 120); }));
run();
}
// ---------- model tab ----------
function renderModel() {
const sc = meta.backtest || [];
const get = (m, h, k) => sc.find(x => x.model === m && x.h === h && x.metric === k)?.value;
const hs = [...new Set(sc.map(x => x.h))].sort((a, b) => a - b);
const names = { persistence: 'Same as now', popularity: 'Last 12 weeks', kalman: 'Kalman form', nb: 'Play-count model', logit: 'Rotation model' };
$('cards').innerHTML = hs.map(h => {
const ms = ['persistence', 'popularity', 'kalman', 'nb', 'logit'];
return `<div class="card"><h3>${h} week${h > 1 ? 's' : ''} ahead</h3>
<table class="wtable"><thead><tr><th class="l">Model</th><th>Skill on adds<br>vs last 12 wks</th><th>Ranking<br>NDCG@50</th></tr></thead><tbody>
${ms.map(m => { const s = get(m, h, 'skill_add_vs_popularity'); return `<tr><td class="l">${names[m]}</td><td class="${s > 0 ? 'up' : s < 0 ? 'down' : ''}">${s == null ? 'baseline' : (s > 0 ? '+' : '') + s.toFixed(3)}</td><td>${(get(m, h, 'ndcg50') ?? 0).toFixed(3)}</td></tr>`; }).join('')}
</tbody></table></div>`;
}).join('') || '<p class="note">No backtest stored yet (`airplay model backtest`).</p>';
}
// ---------- wiring ----------
document.querySelectorAll('nav button').forEach(b => b.addEventListener('click', () => {
document.querySelectorAll('nav button').forEach(x => x.classList.toggle('on', x === b));
$('tab-rank').hidden = b.dataset.tab !== 'rank'; $('tab-model').hidden = b.dataset.tab !== 'model';
}));
$('h').addEventListener('input', () => { shown = 100; loadRank(); });
['ch', 'sort', 'dk'].forEach(id => $(id).addEventListener('change', () => { shown = 100; render(); }));
$('q').addEventListener('input', () => { shown = 100; render(); });
$('more').addEventListener('click', () => { shown += 100; render(); });
$('rows').addEventListener('click', e => { const tr = e.target.closest('tr[data-id]'); if (tr) showArtist(tr.dataset.id); });
$('shade').addEventListener('click', closeDrawer);
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeDrawer(); });
loadMeta().then(() => meta.ready && loadRank());
</script>
</body>
</html>