Spaces:
Running

openajaj / static /stats.html
Jindrich3's picture
hynek med
Super-squash branch 'main' using huggingface_hub
78acc67
Raw History Blame Contribute Delete
33.1 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAjaj — Visitors</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root { --human: #4caf7a; --unverified: #d9a441; --bot: #7a7a96; --internal: #6fa8dc; --broken: #dc5a5a;
--bg: #0f0f1a; --text: #d0d0e8; --muted: #8a8aa8; --panel: #181828; --line: #2a2a40; }
:root.light { --bg: #fdf7ee; --text: #2a1e08; --muted: #7a6040; --panel: #f5edd8; --line: #d4b870; }
:root.pink { --bg: #fff0f5; --text: #4a0e2a; --muted: #9e4b6e; --panel: #ffe4ec; --line: #f5c2d4; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: var(--bg); color: var(--text); min-height: 100vh; padding: 20px 16px;
max-width: 960px; margin: 0 auto;
}
h1 { font-size: 20px; margin-bottom: 4px; }
h2 { font-size: 14px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 28px 0 10px;
overflow-wrap: anywhere; }
.sub { color: var(--muted); font-size: 13px; }
.tabs { margin: 16px 0; display: flex; flex-wrap: wrap; gap: 8px; }
.tabs button { background: var(--panel); color: inherit; border: 1px solid var(--line); border-radius: 6px;
padding: 6px 14px; font: inherit; cursor: pointer; }
.tabs button.on { border-color: var(--human); color: var(--text); }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(130px, 100%), 1fr)); gap: 10px; }
.tile { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px; }
.tile b { display: block; font-size: 26px; font-variant-numeric: tabular-nums; }
.tile span { font-size: 12px; color: var(--muted); }
.legend { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 12px; color: var(--muted); margin-bottom: 8px; }
.legend summary { cursor: pointer; }
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 5px; vertical-align: -1px; }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px; }
svg text { fill: var(--muted); font-size: 10px; }
svg text.in { fill: var(--text); font-weight: 600; }
svg .jump { cursor: pointer; }
.theme { float: right; background: var(--panel); color: var(--muted); border: 1px solid var(--line); border-radius: 6px;
padding: 4px 10px; font: inherit; font-size: 12px; cursor: pointer; }
.row { display: grid; grid-template-columns: 150px 1fr 40px; gap: 8px; align-items: center; font-size: 13px; margin: 4px 0; }
.row .n { text-align: right; font-variant-numeric: tabular-nums; }
.bar { display: flex; height: 14px; border-radius: 3px; overflow: hidden; background: var(--line); }
.bar > * { height: 100%; }
.bar.big { height: 20px; margin-bottom: 8px; }
.bar.thin { height: 6px; margin-top: 6px; }
/* Quality tab: label and value on one line, the bar under them, so a row is never wider than the panel */
.qrow { display: grid; grid-template-columns: 1fr auto; gap: 3px 8px; font-size: 13px; margin: 8px 0; }
.qrow > span:first-child { min-width: 0; overflow-wrap: anywhere; }
.qrow .n { font-variant-numeric: tabular-nums; white-space: nowrap; }
/* One verdict per cell: as many columns as fit, one on a phone */
.legend.verdicts { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); }
.legend > * { min-width: 0; overflow-wrap: anywhere; }
.qrow .bar { grid-column: 1 / -1; height: 10px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
td { padding: 5px 6px; border-top: 1px solid var(--line); word-break: break-all; }
td:last-child { text-align: right; white-space: nowrap; }
.group { border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; margin: 6px 0; }
.group summary { cursor: pointer; font-size: 13px; }
summary.row { cursor: pointer; list-style: none; }
summary.row > span:first-child::before { content: '▸ '; color: var(--muted); }
details[open] > summary.row > span:first-child::before { content: '▾ '; }
.who { font-size: 12px; color: var(--muted); margin: 4px 0 10px 12px; border-left: 2px solid var(--line); padding-left: 10px; }
.who p { padding: 5px 0; }
.who p + p { border-top: 1px solid var(--line); }
.who summary { cursor: pointer; padding: 4px 0; color: var(--text); }
.who details .who { margin-bottom: 4px; }
.versions { margin: 2px 0 8px 12px; border-left: 2px solid var(--line); padding-left: 10px; }
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr)); gap: 0 12px; }
.grid2 > * { min-width: 0; }
.toggle { font-size: 13px; color: var(--muted); cursor: pointer; }
a { color: inherit; }
.empty { color: var(--muted); font-size: 13px; }
@media (max-width: 520px) {
.row { grid-template-columns: 100px 1fr 32px; }
.tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
.tile { padding: 8px; }
.tile b { font-size: 20px; }
}
</style>
<script>
// Same saved theme as the main page (same origin, so same host and port):
// dark / light / pink / auto (system). The button here cycles and saves it too.
const THEMES = ['dark', 'light', 'pink', 'auto'];
function applyTheme() {
const theme = localStorage.getItem('theme') || 'auto';
const shown = theme === 'auto' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme;
document.documentElement.className = shown === 'dark' ? '' : shown;
const button = document.getElementById('theme');
if (button) button.textContent = `Theme: ${theme}`;
}
function cycleTheme() {
const theme = localStorage.getItem('theme') || 'auto';
localStorage.setItem('theme', THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length]);
applyTheme();
}
applyTheme(); // before paint; again once the button exists
addEventListener('DOMContentLoaded', applyTheme);
addEventListener('storage', applyTheme);
</script>
</head>
<body>
<h1>Visitors<!--SERVER--> <button id="theme" class="theme" onclick="cycleTheme()"></button></h1>
<p class="sub">Data goes back to <span id="since">the first logged visit</span>. Counts are unique visitors unless noted. Human = this browser solved the captcha, now or earlier; striped = a human who never chatted (on /t: never started a transcription) · Unverified (dotted) = browser that never did · Bot (finer dots) = crawler/tool user agent · Internal test = our own checks (admin token).</p>
<div class="tabs"><button data-site="main">openajaj.cz</button><button data-site="t">/t transcribe</button><button data-site="quality">Transcription quality</button></div>
<div class="tabs"><button data-days="1">Today</button><button data-days="7">7 days</button><button data-days="30">30 days</button><button data-days="0">All</button></div>
<label class="toggle"><input type="checkbox" id="all" autocomplete="off"> Show bots, unverified &amp; internal tests</label>
<div id="out"></div>
<p class="sub" style="margin-top:24px">IP geolocation by <a href="https://db-ip.com">DB-IP</a> (CC BY 4.0).</p>
<script>
// 'idle' = human who never used the site: drawn striped in the human colour. Unverified: dotted, fainter. Bot: smaller dots, fainter still.
const HUMANS = ['human', 'idle'], ALL = [...HUMANS, 'unverified', 'bot', 'internal'];
let CLASSES = HUMANS, showAll = false;
const PATTERN = {idle: 'hatch', unverified: 'dots', bot: 'dots2'};
const LABEL = {human: 'Human', idle: 'Human, idle', unverified: 'Unverified', bot: 'Bot', internal: 'Internal test'};
const ACTION = {main: ['chat', 'Chats', 'never chatted', 'question'], t: ['stt', 'STT sessions', 'never transcribed', 'transcription']};
const plural = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
const regionName = new Intl.DisplayNames(['en'], {type: 'region'});
// The tab lives in the URL (#main, #t, #quality), so the browser's Back returns to the previous tab.
const SITES = ['main', 't', 'quality'];
const siteFromUrl = () => SITES.includes(location.hash.slice(1)) ? location.hash.slice(1) : 'quality';
let data = null, site = siteFromUrl(), days = '7';
history.scrollRestoration = 'manual'; // a tab is redrawn on Back: put its scroll back by hand
function go(next) {
if (next === site) return;
history.replaceState({y: scrollY}, '');
history.pushState(null, '', `#${next}`);
site = next;
render();
}
addEventListener('popstate', e => {
site = siteFromUrl();
if (!data) return;
render();
scrollTo(0, e.state?.y || 0);
});
let jumpUnit = null; // the /t charts' bucket unit while their use counts link to the quality tab
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[c]));
// Totals count only the classes on show.
const sum = o => CLASSES.reduce((a, c) => a + (o?.[c] || 0), 0);
const color = c => `var(--${c === 'idle' ? 'human' : c})`;
const paint = (fill, pattern) => ({
hatch: `repeating-linear-gradient(135deg, transparent 0 3px, var(--panel) 3px 5px), ${fill}`,
dots: `radial-gradient(circle, transparent 1.2px, var(--panel) 1.3px) 0 0 / 4px 4px, ${fill}`,
dots2: `radial-gradient(circle, transparent 0.8px, var(--panel) 0.9px) 0 0 / 4px 4px, ${fill}`,
}[pattern] || fill);
// Overlays in the panel colour: stripes, or a dot grid (the colour shows only through the holes).
const DEFS = `<defs><pattern id="hatch" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="2" height="5" style="fill:var(--panel)"/></pattern>
<pattern id="dots" width="4" height="4" patternUnits="userSpaceOnUse"><path fill-rule="evenodd" style="fill:var(--panel)"
d="M0 0h4v4H0z M3.2 2a1.2 1.2 0 1 0-2.4 0a1.2 1.2 0 1 0 2.4 0z"/></pattern>
<pattern id="dots2" width="4" height="4" patternUnits="userSpaceOnUse"><path fill-rule="evenodd" style="fill:var(--panel)"
d="M0 0h4v4H0z M2.8 2a0.8 0.8 0 1 0-1.6 0a0.8 0.8 0 1 0 1.6 0z"/></pattern></defs>`;
// Golden-angle hues by order of first appearance in the whole log: a person keeps their colour in every period.
const hue = i => `hsl(${(i * 137.508) % 360}deg 70% 62%)`;
const classSeries = () => CLASSES.map(c => [c, LABEL[c], color(c), PATTERN[c] || '']);
// A person's entry opens to their details (place, device, …).
const legend = series => !series.length ? '' : `<div class="legend">${series.map(([, name, fill, pattern, detail]) => {
const key = `<i style="background:${paint(fill, pattern)}"></i>${esc(name)}`;
return detail ? `<details><summary>${key}</summary>${esc(detail)}</details>` : `<span>${key}</span>`;
}).join('')}</div>`;
function country(code) {
if (!/^[A-Z]{2}$/.test(code)) return 'Unknown';
const flag = String.fromCodePoint(...[...code].map(ch => 0x1F1A5 + ch.charCodeAt(0)));
try { return `${flag} ${regionName.of(code)}`; } catch { return code; }
}
// "🇨🇿 Czechia · Dlouhá Loučka, Pardubice Region · T-Mobile CZ · Android 14 Firefox 158.0 · 112 transcriptions (60 CS, 40 EN) · captcha solved 23.10.2026"
const dmy = day => `${+day.slice(8)}.${+day.slice(5, 7)}.${day.slice(0, 4)}`;
const useCount = h => Object.values(h.uses.hours).reduce((a, n) => a + n, 0);
// " (20 EN, 15 CS)", most first; transcriptions from before languages were logged aren't in it.
const langSplit = c => {
const e = Object.entries(c || {}).sort((a, b) => b[1] - a[1]);
return e.length ? ` (${e.map(([l, n]) => `${n} ${l.toUpperCase()}`).join(', ')})` : '';
};
const withVersion = (name, version) => version ? `${name} ${version}` : name;
const who = (h, uses = '') => [country(h.country), h.dbip, h.isp,
`${withVersion(h.os, h.os_v)} ${withVersion(h.browser, h.browser_v)}`, uses,
h.solved && `captcha solved ${dmy(h.solved)}`].filter(Boolean).join(' · ');
function stackBar(counts, total) {
return `<div class="bar">${CLASSES.filter(c => counts[c]).map(c =>
`<div style="width:${100 * counts[c] / total}%;background:${paint(color(c), PATTERN[c] || '')}" title="${LABEL[c]}: ${counts[c]}"></div>`
).join('')}</div>`;
}
// series: [[key in each entry's counts, name, color, pattern]], stacked bottom up.
// entries: [[tick, counts, uses?]]; a use count is drawn inside its bar when it fits.
function columns(entries, aria, series, noun) {
const total = d => series.reduce((a, [k]) => a + (d[k] || 0), 0);
if (!entries.some(([, d]) => total(d))) return '<p class="empty">No data.</p>';
// Drawn at the panel's real width (minus its padding and border), so text keeps its size on a phone.
const W = Math.max(200, document.getElementById('out').clientWidth - 26), H = 180, pad = 22;
const max = Math.max(...entries.map(([, d]) => total(d)));
const step = (W - pad) / entries.length, bw = Math.max(2, step * 0.7);
const label = Math.ceil(entries.length / Math.floor(W / 75));
const cols = entries.map(([tickText, d, uses, key], i) => {
let y = H - pad, x = pad + i * step;
const rects = series.filter(([k]) => d[k]).map(([k, name, fill, pattern]) => {
const h = (H - 2 * pad) * d[k] / max, box = `x="${x}" y="${y -= h}" width="${bw}" height="${h}"`;
// Use count in a square of the page background, 80% of the bar's short side, so it reads on any bar colour.
// Font fits the square: digits are ~0.6em wide, so wider numbers get smaller text.
const n = uses?.[k] || 0, side = 0.8 * Math.min(h, bw), fs = side * Math.min(0.7, 1.5 / String(n).length);
const cx = x + bw / 2, cy = y + h / 2;
return `<g><title>${tickText} · ${esc(name)}: ${d[k]}${n ? ` · ${plural(n, noun)}` : ''}</title><rect ${box} fill="${fill}"/>${
pattern ? `<rect ${box} fill="url(#${pattern})"/>` : ''}${
n && side >= 12 ? `<g${jumpUnit ? ` class="jump" onclick="jump(${k}, '${key}')"` : ''}><rect x="${cx - side / 2}" y="${cy - side / 2}" width="${side}" height="${side}" rx="${side * 0.15}" style="fill:var(--bg)"/>
<text class="in" x="${cx}" y="${cy + fs * 0.35}" text-anchor="middle" style="font-size:${fs}px">${n}</text></g>` : ''}</g>`;
}).join('');
const tick = i % label ? '' : `<text x="${x + bw / 2}" y="${H - 6}" text-anchor="middle">${tickText}</text>`;
return rects + tick;
}).join('');
return `<svg viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="${aria}">${DEFS}
<text x="0" y="${pad}">${max}</text><line x1="${pad}" x2="${W}" y1="${H - pad}" y2="${H - pad}" style="stroke:var(--line)"/>${cols}</svg>`;
}
// list: [[name, counts, key]]; a row with humans in it opens to one line per human whose `field` is `key`.
// versions ({key: {version: counts}}): a row with a known version opens to one row per version
// instead, each opening to its humans (by `${field}_v`).
// Over MANY visitors (and not already one country): one opening group per country, biggest first.
const MANY = 5;
function visitorList(mine, field) {
const lines = list => `<div class="who">${list.map(([h, line]) => `<p>Visitor ${h.hn} · ${esc(line)}</p>`).join('')}</div>`;
if (mine.length <= MANY || field === 'country') return lines(mine);
const by = Object.groupBy(mine, ([h]) => h.country);
return `<div class="who">${Object.entries(by).sort((a, b) => b[1].length - a[1].length).map(([code, list]) =>
`<details><summary>${country(code)} · ${list.length}</summary>${lines(list)}</details>`).join('')}</div>`;
}
function rows(list, field, people = [], versions = {}) {
list = list.filter(([, c]) => sum(c));
const top = Math.max(...list.map(([, c]) => sum(c)), 1);
if (!list.length) return '<p class="empty">No data.</p>';
return list.map(([name, c, key]) => {
const row = `<span>${esc(name)}</span><div style="width:${100 * sum(c) / top}%">${stackBar(c, sum(c))}</div><span class="n">${sum(c)}</span>`;
const mine = people.filter(([h]) => h[field] === key);
const sub = Object.entries(versions[key] || {}).filter(([, vc]) => sum(vc)).sort((a, b) => sum(b[1]) - sum(a[1]));
if (sub.some(([version]) => version)) return `<details><summary class="row">${row}</summary><div class="versions">${
rows(sub.map(([version, vc]) => [version || 'Unknown', vc, version]), `${field}_v`, mine)}</div></details>`;
return mine.length ? `<details><summary class="row">${row}</summary>${visitorList(mine, field)}</details>`
: `<div class="row">${row}</div>`;
}).join('');
}
function render() {
document.querySelectorAll('.tabs button').forEach(b =>
b.classList.toggle('on', b.dataset.site === site || b.dataset.days === days));
if (site === 'quality') { document.getElementById('out').innerHTML = qualityPanel(quality); return; }
const s = data[site], v = s.visitors, [actionKey, actionLabel, never, noun] = ACTION[site];
LABEL.idle = `Human, ${never}`;
const ranked = (o, n = 20) => Object.entries(o).filter(([, c]) => sum(c)).sort((a, b) => sum(b[1]) - sum(a[1])).slice(0, n);
const countries = ranked(s.countries).map(([code, c]) => [country(code), c, code]);
const referrers = ranked(s.referrers, 15).map(([host, c]) => [host || '(none / typed URL)', c, host]);
const named = o => ranked(o).map(([name, c]) => [name || 'Unknown', c, name]);
const line = h => who(h, h.idle ? '' : plural(useCount(h), noun) + langSplit(h.langs));
const people = s.humans.map(h => [h, line(h)]);
// ~60 columns at most: days, else weeks (labelled by their Monday), else months.
const units = Object.keys(s.days).length <= 62 ? 'days' : Object.keys(s.weeks).length <= 60 ? 'weeks' : 'months';
// Days: "Monday 13.10." ("Mon 13.10." past a week of columns). Weeks: their Monday "13.10.". Months: "2026-10".
const unit = units.slice(0, -1), dm = key => `${+key.slice(8)}.${+key.slice(5, 7)}.`;
const weekday = key => new Date(`${key}T12:00`).toLocaleDateString('en',
{weekday: Object.keys(s.days).length > 7 ? 'short' : 'long'});
const tick = key => unit === 'month' ? key : unit === 'week' ? dm(key) : `${weekday(key)} ${dm(key)}`;
// Humans only: one color per person. Otherwise one color per class.
const series = showAll ? classSeries()
: people.map(([h, detail], i) => [i, `Visitor ${h.hn}`, hue(h.n), h.idle ? 'hatch' : '', detail]);
// visits: visits started in the bucket (a request 30+ min after the previous one); else who was there.
const counts = showAll ? (u, key, visits) => (visits ? s.visit_timeline : s)[u][key] || {}
: (u, key, visits) => s.humans.map(h => visits ? h[u][key] || 0 : +(key in h[u]));
const uses = showAll ? () => null : (u, key) => s.humans.map(h => h.uses[u][key] || 0);
// Today: its 24 hours. Longer: days, weeks or months.
const today = days === '1', per = today ? 'hour' : unit, bucketUnit = today ? 'hours' : units;
const buckets = today ? Array.from({length: 24}, (_, h) => String(h).padStart(2, '0')) : Object.keys(s[units]);
const timeline = visits => buckets.map(key =>
[today ? key : tick(key), counts(bucketUnit, key, visits), uses(bucketUnit, key), key]);
jumpUnit = site === 't' && !showAll ? bucketUnit : null;
const humans = (v.human || 0) + (v.idle || 0), engaged = s.engaged.human || 0;
const returning = (s.returning.human || 0) + (s.returning.idle || 0);
const pct = n => humans ? ` (${Math.round(100 * n / humans)}%)` : '';
const via = Object.entries(s.via).map(([k, n]) => [k === 'cloudflare' ? 'openajaj.cz (Cloudflare)' : 'Direct (hf.space)', n, k]);
document.getElementById('out').innerHTML = `
<div class="tiles">
${CLASSES.filter(c => c !== 'idle').map(c => `<div class="tile"><b style="color:${color(c)}">${c === 'human' ? humans : v[c] || 0}</b><span>${LABEL[c]} visitors</span></div>`).join('')}
<div class="tile"><b>${sum(s.visits)}</b><span>Visits</span></div>
<div class="tile"><b>${sum(s.events.page)}</b><span>Page loads</span></div>
<div class="tile"><b>${sum(s.events[actionKey])}</b><span>${actionLabel}</span></div>
<div class="tile"><b>${engaged}</b><span>Humans who used it${pct(engaged)}</span></div>
<div class="tile"><b>${returning}</b><span>Humans back on another day${pct(returning)}</span></div>
</div>
${site === 't' ? langPanel(s) : ''}
${today ? '' : `<h2>Unique visitors per ${unit}</h2><div class="panel">${legend(series)}${columns(timeline(false), `Unique visitors per ${unit}`, series, noun)}</div>`}
<h2>Visits per ${per}${today ? ' (Prague time)' : ''}</h2><div class="panel">${legend(series)}${columns(timeline(true), `Visits per ${per}`, series, noun)}</div>
<h2>Countries</h2><div class="panel">${legend(classSeries())}${rows(countries, 'country', people)}</div>
<div class="grid2">
<div><h2>Operating system</h2><div class="panel">${rows(named(s.os), 'os', people, s.os_versions)}</div></div>
<div><h2>Browser</h2><div class="panel">${rows(named(s.browsers), 'browser', people, s.browser_versions)}</div></div>
<div><h2>Entry point</h2><div class="panel">${rows(via, 'via', people)}</div></div>
<div><h2>Came from</h2><div class="panel">${rows(referrers, 'referrer', people)}</div></div>
<div><h2>Place</h2><div class="panel">${rows(named(s.places_dbip), 'dbip', people)}</div></div>
<div><h2>Network (ISP)</h2><div class="panel">${rows(named(s.isps), 'isp', people)}</div></div>
</div>
${CLASSES.includes('bot') ? `<h2>Top bot user agents (requests)</h2><div class="panel">${s.bot_agents.length
? `<table>${s.bot_agents.map(([ua, n]) => `<tr><td>${esc(ua || '(none)')}</td><td>${n}</td></tr>`).join('')}</table>`
: '<p class="empty">None.</p>'}</div>` : ''}`;
}
// /t: which languages the shown visitors transcribed in, as shares of one bar.
function langPanel(s) {
const inShown = c => CLASSES.reduce((a, k) => a + (c?.[k] || 0), 0);
const counts = Object.entries(s.langs || {}).map(([l, c]) => [l.toUpperCase(), inShown(c)])
.filter(([, n]) => n).sort((a, b) => b[1] - a[1]);
const total = counts.reduce((a, [, n]) => a + n, 0), before = inShown(s.events.stt) - total;
if (!total) return '';
const part = ([l, n], i) => `style="width:${100 * n / total}%;background:${hue(i)}" title="${esc(l)}: ${n}"`;
return `<h2>Transcription languages</h2><div class="panel">
<div class="bar big">${counts.map((e, i) => `<div ${part(e, i)}></div>`).join('')}</div>
<div class="legend">${counts.map(([l, n], i) =>
`<span><i style="background:${hue(i)}"></i>${esc(l)} ${Math.round(100 * n / total)}% (${n})</span>`).join('')}</div>
${before > 0 ? `<p class="sub">${plural(before, 'transcription')} from before languages were logged not counted.</p>` : ''}</div>`;
}
// Its own tab: /t visits, judged by stt_quality.py from the page's own reports (all visitors, not only humans)
const VERDICT = {ok: 'OK', degraded: 'Degraded: late or unsure text', broken: 'Broken: not transcribing or losing speech',
failed: 'Never started', too_short: 'Too short to judge'};
const PROBLEM = {ok: 'No problem shown', connect: 'Connecting (normal start)', off: 'Not transcribing', mic: 'Mic not hearing',
stuck: 'Very slow internet (audio stuck)', slow: 'Slow internet (text over 5 s late)',
noise: 'Noisy', far: 'Speaker far away', lang: 'Unclear speech', music: 'Only music/noise (info)'};
let quality = null;
const MIN_ACTIVE_S = 15; // stt_quality.MIN_ACTIVE_S: shorter visits without a problem are not judged
const mins = s => s < 60 ? `${s} s` : `${Math.round(s / 60)} min`;
const JUDGED = ['ok', 'degraded', 'broken', 'failed'];
const VERDICT_COLOR = {ok: 'var(--human)', degraded: 'var(--unverified)', broken: 'var(--broken)', failed: 'var(--bot)'};
// Problems by how bad they are: blue = info, amber = worse text, red = no text.
const SEVERITY = {ok: 'var(--human)', connect: 'var(--internal)', music: 'var(--internal)', noise: 'var(--unverified)',
far: 'var(--unverified)', lang: 'var(--unverified)', slow: 'var(--unverified)',
off: 'var(--broken)', mic: 'var(--broken)', stuck: 'var(--broken)'};
const severity = k => SEVERITY[k] || 'var(--muted)';
// Green for the best bin, through amber, to red for the worst.
const ramp = (i, n) => `hsl(${140 - 140 * i / Math.max(1, n - 1)}deg 55% 52%)`;
// entries: [[label, n, value text, fill]], each bar scaled to the largest
function bars(entries) {
if (!entries.some(([, n]) => n)) return '<p class="empty">None.</p>';
const top = Math.max(...entries.map(([, n]) => n));
return entries.map(([label, n, text, fill]) => `<div class="qrow"><span>${esc(label)}</span><span class="n">${text}</span>
<div class="bar"><div style="width:${100 * n / top}%;background:${fill}"></div></div></div>`).join('');
}
// bins over edges, the last one open: "≤ 0.5 s", …, "> 10 s"; worstFirst flips the colours
function bins(counts, edges, fmt, worstFirst = false) {
const total = counts.reduce((a, n) => a + n, 0);
return counts.map((n, i) => [i < edges.length ? `≤ ${fmt(edges[i])}` : `> ${fmt(edges[edges.length - 1])}`,
n, `${n}${total ? ` (${Math.round(100 * n / total)}%)` : ''}`, ramp(worstFirst ? counts.length - 1 - i : i, counts.length)]);
}
// Judged visits side by side, one colour per verdict; spans, so it may sit in a <summary>.
function verdictBar(v, size) {
const judged = JUDGED.reduce((a, k) => a + (v[k] || 0), 0);
return judged ? `<span class="bar ${size}">${JUDGED.filter(k => v[k]).map(k =>
`<span style="width:${100 * v[k] / judged}%;background:${VERDICT_COLOR[k]}" title="${VERDICT[k]}: ${v[k]}"></span>`).join('')}</span>` : '';
}
function qualityPanel(q) {
if (q?.error) return `<h2>Transcription quality</h2><div class="panel"><p class="empty">Could not load (${esc(q.error)}).</p></div>`;
if (!q?.visits) return '<h2>Transcription quality</h2><div class="panel"><p class="empty">No visit reports yet.</p></div>';
return `<h2>By visitor (anyone with a visit long enough to judge)</h2>${q.by_visitor.map(g => qualityGroup(g, `${g.name} · ${g.device}`, sessionList(g.sessions), ` data-who="${esc(g.name)}"`)).join('')}
<h2>Transcription quality – All</h2>${qualityGroup(q, 'All visits')}
<h2>By operating system</h2>${q.by_os.map(g => qualityGroup(g, g.name)).join('')}`;
}
// Closed: verdict counts, then each problem's share of the group's /t time. Open: the group's full numbers.
const shortVerdict = k => VERDICT[k]?.split(':')[0] || k;
const shareLine = g => Object.entries(g.problem_secs).map(([c, s]) =>
`${c} ${g.total_s ? Math.round(100 * s / g.total_s) : 0}%`).join(' · ') || 'no problem shown';
function qualityGroup(g, name, more = '', attr = '') {
const short = g.verdicts.too_short || 0, judged = `${g.visits - short} judged, ${short} under ${MIN_ACTIVE_S} s`;
const verdicts = Object.entries(g.verdicts).filter(([k]) => k !== 'too_short')
.map(([k, n]) => ` · ${shortVerdict(k)} ${n}`).join('');
return `<details class="group"${attr}><summary><b>${esc(name)}</b> · ${plural(g.visits, 'visit')} (${judged})${verdicts}
<br><span class="sub">${shareLine(g)}</span>${verdictBar(g.verdicts, 'thin')}</summary>${more}${qualityBody(g)}</details>`;
}
// A visit's clock time in Prague, as much of the date as the period needs:
// "9:20–9:30" today, "Tue 9:20–9:30" over 7 days, "Tue 27.10. 9:20–9:30" beyond.
const PRAGUE = new Intl.DateTimeFormat('en-GB', {timeZone: 'Europe/Prague', weekday: 'short',
day: 'numeric', month: 'numeric', hour: 'numeric', minute: '2-digit', hourCycle: 'h23'});
function span(s) {
if (!s.start) return 'Time unknown';
const at = iso => Object.fromEntries(PRAGUE.formatToParts(new Date(iso)).map(p => [p.type, p.value]));
const a = at(s.start), b = at(s.end || s.start), hm = p => `${+p.hour}:${p.minute}`;
const day = days === '1' ? '' : `${a.weekday} ${days === '7' ? '' : `${+a.day}.${+a.month}. `}`;
return `${day}${hm(a)}–${hm(b)}`;
}
// First thing in an open visitor, right under its summary line.
const sessionList = list => list?.length ? `<h2 style="margin-top:12px">Sessions, newest first</h2>${list.map(sessionGroup).join('')}
<h2>All sessions of this visitor</h2>` : '';
// One visit: when, its verdict, transcriptions and on-screen time, the visitor as they were then. Open: its own numbers.
function sessionGroup(s) {
const [k] = Object.keys(s.verdicts);
const count = s.country ? `${plural(s.transcriptions, 'transcription')}${langSplit(s.langs)}, ` : '';
return `<details class="group" data-start="${esc(s.start || s.end || '')}"><summary><b>${span(s)}</b> · <b style="color:${VERDICT_COLOR[k] || 'var(--muted)'}">${
esc(shortVerdict(k))}</b> · ${count}${mins(s.total_s)}${s.country ? `<br><span class="sub">${esc(who(s))}</span>` : ''}
<br><span class="sub">${shareLine(s)}</span></summary>${qualityBody(s, true)}</details>`;
}
// The /t charts' bucket a session started in, Prague time, keyed like visits._buckets.
const PRAGUE_PARTS = new Intl.DateTimeFormat('en-CA', {timeZone: 'Europe/Prague', year: 'numeric',
month: '2-digit', day: '2-digit', hour: '2-digit', hourCycle: 'h23'});
function bucketOf(iso, unit) {
const p = Object.fromEntries(PRAGUE_PARTS.formatToParts(new Date(iso)).map(x => [x.type, x.value]));
const day = `${p.year}-${p.month}-${p.day}`, noon = new Date(`${day}T12:00Z`);
noon.setUTCDate(noon.getUTCDate() - (noon.getUTCDay() + 6) % 7);
return {hours: p.hour, days: day, weeks: noon.toISOString().slice(0, 10), months: day.slice(0, 7)}[unit];
}
// A use count on the /t charts: open that visitor on the quality tab, and their sessions in that bucket.
function jump(i, key) {
const unit = jumpUnit, name = `Visitor ${data.t.humans[i].hn}`;
go('quality');
const person = [...document.querySelectorAll('details[data-who]')].find(d => d.dataset.who === name);
if (!person) return;
person.open = true;
const hits = [...person.querySelectorAll('details[data-start]')]
.filter(d => d.dataset.start && bucketOf(d.dataset.start, unit) === key);
hits.forEach(d => { d.open = true; });
(hits[0] || person).scrollIntoView({behavior: 'smooth', block: 'start'});
}
function qualityBody(q, single = false) {
const v = q.verdicts, judged = q.visits - (v.too_short || 0);
const pct = n => judged ? ` (${Math.round(100 * (n || 0) / judged)}%)` : '';
const share = s => mins(s) + (q.total_s ? ` (${Math.round(100 * s / q.total_s)}%)` : '');
const problems = (o, fmt) => Object.entries(o).map(([k, n]) => [PROBLEM[k] || k || '(none)', n, fmt(n), severity(k)]);
const charts = [
['Main reason', problems(q.reasons, n => n)],
['Time per problem', problems(q.problem_secs, share)],
['Why not transcribing', Object.entries(q.off_why).map(([k, s]) => [k || '(none)', s, mins(s), 'var(--broken)'])],
['Text delay', bins(q.lag_hist, q.lag_edges_ms, ms => `${ms / 1000} s`)],
['Word confidence', bins(q.conf_hist, q.conf_edges, c => `${Math.round(c * 100)} %`, true)],
];
// A chart with nothing in it is only named, on one line under the rest.
const empty = charts.filter(([, e]) => !e.some(([, n]) => n)).map(([title]) => title);
return `${single ? `<p class="sub">${mins(q.missed_s)} speech missed (drops, lost audio)</p>` : `<div class="panel">${verdictBar(v, 'big')}
<div class="legend verdicts">${JUDGED.map(k =>
`<span><i style="background:${VERDICT_COLOR[k]}"></i>${v[k] || 0} ${VERDICT[k]}${pct(v[k])}</span>`).join('')}</div>
<p class="sub">${v.too_short || 0} too short to judge · ${mins(q.missed_s)} speech missed (drops, lost audio)</p></div>`}
<div class="grid2">${charts.filter(([, e]) => e.some(([, n]) => n)).map(([title, e]) =>
`<div><h2>${title}</h2><div class="panel">${bars(e)}</div></div>`).join('')}</div>
${empty.length ? `<p class="sub" style="margin-top:12px">Nothing to show: ${empty.join(' · ')}.</p>` : ''}`;
}
async function load() {
let tok = localStorage.getItem('adminToken');
if (!tok) { tok = prompt('Admin token'); if (tok) localStorage.setItem('adminToken', tok); }
const headers = {
'X-Ajaj-Admin': tok || '',
'X-Ajaj-Session': new URLSearchParams(location.search).get('cs') || localStorage.getItem('ajaj_v') || '',
};
const resp = await fetch(`/api/visits?days=${days}`, {headers});
if (resp.status === 403) {
localStorage.removeItem('adminToken');
document.getElementById('out').innerHTML = '<p class="empty">Forbidden — reload to enter the token again.</p>';
return;
}
data = await resp.json();
const q = await fetch(`/api/stt/quality?days=${days}`, {headers}).catch(() => null);
quality = !q ? {error: 'network'} : q.ok ? await q.json().catch(() => ({error: 'bad reply'})) : {error: q.status};
if (data.since) document.getElementById('since').textContent = new Date(data.since).toLocaleString('cs-CZ',
{timeZone: 'Europe/Prague', day: 'numeric', month: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'});
render();
}
// charts are drawn at the panel's width; the quality tab has none, and redrawing would close its rows
addEventListener('resize', () => data && site !== 'quality' && render());
document.getElementById('all').onchange = e => { showAll = e.target.checked; CLASSES = showAll ? ALL : HUMANS; if (data) render(); };
document.querySelectorAll('[data-site]').forEach(b => b.onclick = () => go(b.dataset.site));
document.querySelectorAll('[data-days]').forEach(b => b.onclick = () => { days = b.dataset.days; load(); });
load();
</script>
</body>
</html>