4ff31557a8
Trainer: `parking-trainer serve` — a stdlib HTTP job API on the compose network (never
published): /health, /readiness, /versions, /versions/<v>/report, /jobs. One job at a
time; each job runs the CLI as a subprocess with its output captured, state + log
persisted under /out/jobs/ so a restart keeps history. `publish` takes its URL from
TRAINER_PUBLISH_URL. Dockerfile: CMD serve, EXPOSE 8091, healthcheck.
Collector: COLLECTOR_TRAINER_URL + /api/training/{status,jobs,jobs/:id,versions/:v/report}
— a reviewer-gated proxy that forwards a fixed set of paths and whitelisted knobs and
passes the trainer's status codes through (409 while a job runs; 503 unconfigured, 502
unreachable). /review gains the Training section: labels per class vs the minimum with
Train disabled until two classes clear it, mode / backbone / floor, the running job's
live log, the versions with Report / Evaluate / Publish (publish confirms), and the
reminder that pinning stays a git commit. Fixed on the way: an apostrophe in the page's
inline script broke the whole page — a test now parses the script.
Compose: `trainer` is a service (restart: unless-stopped, read-only data volume, its own
trainer-out volume), the `train` profile and TRAINER_OUT are gone; the Docker-socket
route was rejected (root on the host for a service booths upload to). Verified with both
images running together: a Train started through the proxy finished, version and report
came back, the page rendered.
Wiki: bodytype-classifier-training (loop, running it, operating notes superseded),
vision-review-outbox, fleet-deployment-komodo, log.
Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
235 lines
15 KiB
TypeScript
235 lines
15 KiB
TypeScript
import { VEHICLE_CLASSES } from "@parking/shared";
|
||
|
||
// The reviewer's screen: one pending crop at a time, the operator's pick and the camera's
|
||
// pick beside it, one button per vocabulary class + "unusable". Served by the collector
|
||
// itself (no build step, no framework) — this is deliberately the whole UI.
|
||
|
||
export function reviewPage(): string {
|
||
const classes = JSON.stringify(VEHICLE_CLASSES);
|
||
return `<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>Wash review</title>
|
||
<style>
|
||
:root { --bg:#111; --panel:#1b1b1b; --text:#e8e8e8; --muted:#9a9a9a; --amber:#e0a030; --green:#4caf50; --red:#e05050; }
|
||
body { margin:0; background:var(--bg); color:var(--text); font:14px/1.4 system-ui, sans-serif; }
|
||
header { display:flex; justify-content:space-between; align-items:center; padding:.6rem 1rem; border-bottom:1px solid #333; }
|
||
header b { letter-spacing:.08em; text-transform:uppercase; color:var(--amber); font-size:.75rem; }
|
||
main { max-width:960px; margin:0 auto; padding:1rem; display:grid; gap:1rem; }
|
||
.card { background:var(--panel); border:1px solid #333; border-radius:6px; padding:1rem; }
|
||
img { max-width:100%; max-height:60vh; display:block; margin:0 auto; background:#000; border-radius:4px; }
|
||
dl { display:grid; grid-template-columns:max-content 1fr; gap:.2rem .8rem; margin:0; font-variant-numeric:tabular-nums; }
|
||
dt { color:var(--muted); }
|
||
.buttons { display:flex; flex-wrap:wrap; gap:.4rem; }
|
||
button { background:#2a2a2a; color:var(--text); border:1px solid #444; border-radius:4px; padding:.5rem .8rem; font:inherit; cursor:pointer; }
|
||
button:hover { border-color:var(--amber); }
|
||
button.mono { font-family:ui-monospace, monospace; }
|
||
button.hint { border-color:var(--amber); }
|
||
button.unusable { color:var(--red); }
|
||
button.skip { color:var(--muted); }
|
||
.muted { color:var(--muted); }
|
||
.warn { color:var(--amber); }
|
||
table { border-collapse:collapse; width:100%; font-variant-numeric:tabular-nums; }
|
||
td, th { text-align:left; padding:.2rem .5rem; border-bottom:1px solid #2a2a2a; }
|
||
th { color:var(--muted); font-weight:normal; font-size:.75rem; text-transform:uppercase; letter-spacing:.06em; }
|
||
kbd { background:#2a2a2a; border:1px solid #444; border-radius:3px; padding:0 .3rem; font-size:.75rem; }
|
||
h2 { font-size:.8rem; letter-spacing:.08em; text-transform:uppercase; color:var(--amber); margin:0 0 .6rem; }
|
||
.row { display:flex; flex-wrap:wrap; gap:.6rem; align-items:center; }
|
||
select, input { background:#2a2a2a; color:var(--text); border:1px solid #444; border-radius:4px; padding:.4rem .5rem; font:inherit; }
|
||
input[type=number] { width:5rem; }
|
||
label { color:var(--muted); font-size:.8rem; }
|
||
pre { background:#0d0d0d; border:1px solid #2a2a2a; border-radius:4px; padding:.6rem; max-height:22rem; overflow:auto; font-size:.75rem; white-space:pre-wrap; margin:.6rem 0 0; }
|
||
.ok { color:var(--green); }
|
||
.bad { color:var(--red); }
|
||
button:disabled { opacity:.45; cursor:not-allowed; }
|
||
button.small { padding:.25rem .5rem; font-size:.75rem; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header><b>Wash review</b><span id="counts" class="muted"></span></header>
|
||
<main>
|
||
<section class="card" id="item">
|
||
<p class="muted">Loading…</p>
|
||
</section>
|
||
<section class="card">
|
||
<table id="stats"><thead><tr><th>booth</th><th>operator</th><th>reviewed</th><th>agree</th><th>disagree</th><th>unusable</th></tr></thead><tbody></tbody></table>
|
||
</section>
|
||
<section class="card" id="training" hidden>
|
||
<h2>Training</h2>
|
||
<div id="tr-body"></div>
|
||
</section>
|
||
<p class="muted">Keys: <kbd>1</kbd>–<kbd>9</kbd>, <kbd>0</kbd> pick a class in order · <kbd>u</kbd> unusable · <kbd>s</kbd> skip. Skipped items come back after a reload. Your verdict is the training label; the operator's pick is only compared against it.</p>
|
||
</main>
|
||
<script>
|
||
const CLASSES = ${classes};
|
||
const skipped = new Set();
|
||
let current = null;
|
||
|
||
async function api(path, init) {
|
||
const r = await fetch(path, init);
|
||
if (!r.ok) throw new Error(path + ' → HTTP ' + r.status);
|
||
return r.json();
|
||
}
|
||
|
||
function esc(s) { return String(s).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); }
|
||
|
||
async function loadStats() {
|
||
const s = await api('/api/stats');
|
||
const pending = s.booths.reduce((n, b) => n + b.pending, 0);
|
||
const reviewed = s.booths.reduce((n, b) => n + b.reviewed, 0);
|
||
document.getElementById('counts').textContent = pending + ' waiting · ' + reviewed + ' reviewed';
|
||
const tb = document.querySelector('#stats tbody');
|
||
tb.innerHTML = s.operators.map(o => '<tr><td>' + esc(o.booth) + '</td><td class="mono">' + esc(o.operatorRef) + '</td><td>' + o.reviewed + '</td><td>' + o.agree + '</td><td' + (o.disagree ? ' class="warn"' : '') + '>' + o.disagree + '</td><td>' + o.unusable + '</td></tr>').join('') || '<tr><td colspan="6" class="muted">nothing reviewed yet</td></tr>';
|
||
}
|
||
|
||
async function next() {
|
||
const { items } = await api('/api/items?status=pending&limit=25');
|
||
current = items.find(i => !skipped.has(i.id)) || null;
|
||
const el = document.getElementById('item');
|
||
if (!current) { el.innerHTML = '<p class="muted">Nothing waiting for review.</p>'; return; }
|
||
const it = current;
|
||
const opClasses = JSON.parse(it.operatorClasses || '[]');
|
||
el.innerHTML =
|
||
'<img src="/api/items/' + encodeURIComponent(it.id) + '/image" alt="">' +
|
||
'<dl style="margin-top:.8rem">' +
|
||
(it.kind === 'entry'
|
||
? '<dt>sample</dt><dd><span class="muted">entry stream — no wash, no operator decision; label the vehicle</span></dd>'
|
||
: '<dt>operator chose</dt><dd><b>' + esc(it.operatorCategoryName) + '</b> <span class="muted">(' + esc(opClasses.join(', ') || 'no classes mapped') + ')</span></dd>') +
|
||
'<dt>camera saw</dt><dd class="mono">' + esc(it.visionClass) + ' <span class="muted">' + Math.round(it.visionConfidence * 100) + '%</span>' + (it.downgraded ? ' <span class="warn">flagged downgrade at the booth</span>' : '') + '</dd>' +
|
||
(it.kind === 'entry' ? '<dt>booth</dt><dd class="mono">' + esc(it.booth) + '</dd>' :
|
||
'<dt>service</dt><dd>' + esc(it.service) + '</dd>' +
|
||
'<dt>booth · operator</dt><dd class="mono">' + esc(it.booth) + ' · ' + esc(it.operatorRef) + '</dd>') +
|
||
'<dt>at</dt><dd>' + esc(it.at) + '</dd>' +
|
||
'</dl>' +
|
||
'<div class="buttons" style="margin-top:.8rem">' +
|
||
CLASSES.map((c, i) => '<button class="mono' + (c === it.visionClass ? ' hint' : '') + '" data-label="' + c + '" title="key ' + ((i + 1) % 10) + '">' + c + '</button>').join('') +
|
||
'<button class="unusable" data-label="unusable">unusable</button>' +
|
||
'<button class="skip" data-skip="1">skip</button>' +
|
||
'</div>';
|
||
el.querySelectorAll('button[data-label]').forEach(b => b.addEventListener('click', () => verdict(b.dataset.label)));
|
||
el.querySelector('button[data-skip]').addEventListener('click', skip);
|
||
}
|
||
|
||
async function verdict(label) {
|
||
if (!current) return;
|
||
await api('/api/items/' + encodeURIComponent(current.id) + '/review', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label }) });
|
||
await Promise.all([next(), loadStats()]);
|
||
}
|
||
function skip() { if (current) { skipped.add(current.id); next(); } }
|
||
|
||
document.addEventListener('keydown', e => {
|
||
if (e.target.tagName === 'INPUT') return;
|
||
if (e.key === 'u') verdict('unusable');
|
||
else if (e.key === 's') skip();
|
||
else if (/^[0-9]$/.test(e.key)) { const i = e.key === '0' ? 9 : Number(e.key) - 1; if (CLASSES[i]) verdict(CLASSES[i]); }
|
||
});
|
||
|
||
next().catch(e => { document.getElementById('item').innerHTML = '<p class="warn">' + esc(e.message) + '</p>'; });
|
||
loadStats().catch(() => {});
|
||
|
||
// ---- Training: the trainer's job API, proxied by the collector -------------------------
|
||
// Readiness (labels per class vs the minimum), one job at a time with a live log, the
|
||
// versions a run produced (written or refused) with Report / Evaluate / Publish. Pinning a
|
||
// published version into the vision image stays a git commit — that is the deploy control.
|
||
let trPoll = null;
|
||
let trShownReport = null;
|
||
const trDefaults = { mode: 'features', backbone: 'resnet18', minAccuracy: 0.85 };
|
||
|
||
function pct(x) { return x == null ? '—' : Math.round(x * 100) + ' %'; }
|
||
|
||
async function training() {
|
||
const box = document.getElementById('training');
|
||
const el = document.getElementById('tr-body');
|
||
let s;
|
||
try { s = await api('/api/training/status'); } catch (e) { box.hidden = false; el.innerHTML = '<p class="warn">' + esc(e.message) + '</p>'; return; }
|
||
if (!s.configured) { box.hidden = true; return; }
|
||
box.hidden = false;
|
||
if (!s.reachable) { el.innerHTML = '<p class="warn">trainer not reachable: ' + esc(s.error || '') + '</p>'; schedule(true); return; }
|
||
const r = s.readiness, run = r.run || {}, minPer = run.minPerClass || 20;
|
||
const byClass = (r.labelled && r.labelled.byClass) || {};
|
||
const classes = Object.keys(byClass);
|
||
const cur = s.current;
|
||
const readyLine = r.ready
|
||
? '<span class="ok">enough labels to train</span> — classes this run: ' + esc((run.classes || []).join(', '))
|
||
: '<span class="warn">not enough labels yet</span> — a class needs ' + minPer + ' reviewed crops; two classes must clear it';
|
||
let html = '<p>' + readyLine + ' <span class="muted">(' + (r.labelled ? r.labelled.total : 0) + ' labelled, ' + (r.missingCrops || 0) + ' missing crop files)</span></p>';
|
||
html += '<table><thead><tr><th>class</th><th>reviewed</th><th>train</th><th>val</th><th></th></tr></thead><tbody>' +
|
||
(classes.map(c => '<tr><td class="mono">' + esc(c) + '</td><td>' + byClass[c] + '</td><td>' + ((run.train || {})[c] ?? '—') + '</td><td>' + ((run.val || {})[c] ?? '—') + '</td><td class="muted">' + (byClass[c] < minPer ? 'below ' + minPer + ' — dropped' : '') + '</td></tr>').join('') || '<tr><td colspan="5" class="muted">no labels yet — review crops above</td></tr>') +
|
||
'</tbody></table>';
|
||
const d = Object.assign({}, trDefaults, r.defaults || {});
|
||
html += '<div class="row" style="margin-top:.8rem">' +
|
||
'<label>mode <select id="tr-mode">' + (r.modes || ['features', 'finetune']).map(m => '<option' + (m === d.mode ? ' selected' : '') + '>' + m + '</option>').join('') + '</select></label>' +
|
||
'<label>backbone <select id="tr-backbone">' + (r.backbones || ['resnet18']).map(b => '<option' + (b === d.backbone ? ' selected' : '') + '>' + b + '</option>').join('') + '</select></label>' +
|
||
'<label>floor <input id="tr-floor" type="number" min="0" max="1" step="0.01" value="' + d.minAccuracy + '"></label>' +
|
||
'<button id="tr-train"' + (r.ready && !cur ? '' : ' disabled') + '>Train</button>' +
|
||
(cur ? '<span class="warn">running: ' + esc(cur.kind) + ' ' + esc(cur.id) + '</span>' : '') +
|
||
'</div>';
|
||
const last = cur || (s.jobs && s.jobs[0]);
|
||
if (last) {
|
||
const cls = last.status === 'done' ? 'ok' : last.status === 'running' ? 'warn' : 'bad';
|
||
html += '<p style="margin:.8rem 0 0"><span class="' + cls + '">' + esc(last.status) + '</span> <span class="mono">' + esc(last.kind) + ' ' + esc(last.id) + '</span> <span class="muted">' + esc(last.startedAt || '') + (last.exitCode != null ? ' · exit ' + last.exitCode : '') + '</span> <button class="small" data-job="' + esc(last.id) + '">log</button></p>' +
|
||
'<pre id="tr-log" hidden></pre>';
|
||
}
|
||
const vs = s.versions || [];
|
||
html += '<h2 style="margin-top:1rem">Versions</h2>';
|
||
html += vs.length
|
||
? '<table><thead><tr><th>version</th><th>model</th><th>accuracy</th><th>classes</th><th>mode</th><th></th></tr></thead><tbody>' +
|
||
vs.map(v => '<tr><td class="mono">' + esc(v.version) + '</td><td>' + (v.written ? '<span class="ok">written</span>' : '<span class="bad">refused</span>') + '</td><td>' + pct(v.accuracy) + (v.floor != null ? ' <span class="muted">/ floor ' + pct(v.floor) + '</span>' : '') + '</td><td class="muted">' + esc((v.classes || []).join(', ')) + '</td><td class="muted">' + esc(v.mode || '') + '</td><td>' +
|
||
'<button class="small" data-report="' + esc(v.version) + '">report</button> ' +
|
||
(v.written ? '<button class="small" data-eval="' + esc(v.version) + '"' + (cur ? ' disabled' : '') + '>evaluate</button> <button class="small" data-publish="' + esc(v.version) + '"' + (cur ? ' disabled' : '') + '>publish</button>' : '') +
|
||
'</td></tr>').join('') + '</tbody></table>'
|
||
: '<p class="muted">no runs yet</p>';
|
||
html += '<pre id="tr-report" hidden></pre>';
|
||
html += '<p class="muted" style="margin:.8rem 0 0">A written model is only a file here. To put it on a booth: publish, then pin the version in <span class="mono">apps/vision/models/bodytype.version</span>, commit, and bump the TAG of the booth.</p>';
|
||
el.innerHTML = html;
|
||
|
||
const trainBtn = document.getElementById('tr-train');
|
||
if (trainBtn) trainBtn.addEventListener('click', () => startJob({ kind: 'train', mode: document.getElementById('tr-mode').value, backbone: document.getElementById('tr-backbone').value, minAccuracy: Number(document.getElementById('tr-floor').value) }));
|
||
el.querySelectorAll('button[data-eval]').forEach(b => b.addEventListener('click', () => startJob({ kind: 'evaluate', version: b.dataset.eval })));
|
||
el.querySelectorAll('button[data-publish]').forEach(b => b.addEventListener('click', () => { if (confirm('Publish ' + b.dataset.publish + ' to the package registry?')) startJob({ kind: 'publish', version: b.dataset.publish }); }));
|
||
el.querySelectorAll('button[data-job]').forEach(b => b.addEventListener('click', () => showLog(b.dataset.job)));
|
||
el.querySelectorAll('button[data-report]').forEach(b => b.addEventListener('click', () => showReport(b.dataset.report)));
|
||
if (cur) showLog(cur.id).catch(() => {});
|
||
if (trShownReport) showReport(trShownReport).catch(() => {});
|
||
schedule(!!cur);
|
||
}
|
||
|
||
function schedule(soon) {
|
||
if (trPoll) clearTimeout(trPoll);
|
||
trPoll = setTimeout(() => training().catch(() => {}), soon ? 4000 : 60000);
|
||
}
|
||
|
||
async function startJob(body) {
|
||
try {
|
||
const r = await fetch('/api/training/jobs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||
if (!r.ok) { const e = await r.json().catch(() => ({})); alert('trainer: ' + (e.error || ('HTTP ' + r.status))); }
|
||
} catch (e) { alert(e.message); }
|
||
training().catch(() => {});
|
||
}
|
||
|
||
async function showLog(id) {
|
||
const j = await api('/api/training/jobs/' + encodeURIComponent(id));
|
||
const pre = document.getElementById('tr-log');
|
||
if (!pre) return;
|
||
pre.hidden = false;
|
||
pre.textContent = j.log || '(no output yet)';
|
||
pre.scrollTop = pre.scrollHeight;
|
||
}
|
||
|
||
async function showReport(v) {
|
||
const r = await fetch('/api/training/versions/' + encodeURIComponent(v) + '/report');
|
||
const pre = document.getElementById('tr-report');
|
||
if (!pre) return;
|
||
trShownReport = v;
|
||
pre.hidden = false;
|
||
pre.textContent = r.ok ? await r.text() : 'no report for ' + v + ' (HTTP ' + r.status + ')';
|
||
}
|
||
|
||
training().catch(() => {});
|
||
</script>
|
||
</body>
|
||
</html>`;
|
||
}
|