/* AIMScribe annotation workspace -- the shared engine behind both pages.
*
* sd.html and asr.html are separate tools for separate workforces, but they are the same
* audio, the same turn model and the same submit path, so they run one engine and differ in
* layout and in which controls are wired. The page announces itself through the body class
* (track-sd / track-asr); everything below reads PAGE_TRACK rather than guessing.
*
* No external libraries: the waveform, the region editor and the playback clock are all
* built on Canvas2D and the Web Audio API. That keeps the tool usable inside a hospital
* network with no CDN access, and means nothing about patient audio depends on a third
* party being reachable.
*
* Two views over the same audio. #mini shows the whole chunk and never moves; #wave shows a
* zoomable window. Eight minutes across 1400px is 0.34 s per pixel, which is far too coarse
* to place a boundary on -- at the default 30 s window it is about 20 ms, which is the
* precision this dataset exists to capture.
*/
'use strict';
// Which tool this is. Drives layout, which controls exist, and where a mismatched account
// gets redirected.
const PAGE_TRACK = document.body.classList.contains('track-asr')
? 'transcription' : 'diarization';
const SPEAKERS = [
{ key: 'DOCTOR', color: '#4da3ff' },
{ key: 'PATIENT', color: '#f5a15c' },
{ key: 'ATTENDANT', color: '#3ecf8e' },
{ key: 'OTHER', color: '#9aa5b1' },
];
const colourOf = k => (SPEAKERS.find(s => s.key === k) || SPEAKERS[3]).color;
const EDGE_PX = 6; // grab zone for resizing, in pixels
const MIN_TURN = 0.05; // shorter than this is a slip of the mouse, not a turn
const AUTOSAVE_MS = 20000;
const $ = id => document.getElementById(id);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const fmt = t => t.toFixed(2);
const S = {
user: null,
task: null,
buffer: null,
peaks: null, // coarse peaks for the mini view
turns: [], // {start, end, speaker}
sel: -1,
view: { start: 0, dur: 30 },
cursor: 0,
playing: false,
ctx: null, src: null, playStartedAt: 0, playFrom: 0,
listen: 0, // seconds of audio actually played
openedAt: 0, // wall clock, for active_seconds
drag: null,
dirty: false,
};
/* ─────────────────────────── net ─────────────────────────── */
async function api(path, opts = {}) {
const r = await fetch(path, {
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
...opts,
});
if (r.status === 401) { showLogin(); throw new Error('signed out'); }
const body = r.headers.get('content-type')?.includes('json') ? await r.json() : null;
if (!r.ok) throw new Error(body?.detail || r.statusText);
return body;
}
function toast(msg, ms = 2600) {
const t = $('toast');
t.textContent = msg;
t.style.display = 'block';
clearTimeout(toast._t);
toast._t = setTimeout(() => { t.style.display = 'none'; }, ms);
}
/* ─────────────────────────── auth ─────────────────────────── */
// Sign-in lives on index.html; a workspace that loses its session goes back there rather
// than growing a second login form.
function showLogin() { location.href = '/static/index.html'; }
function showWork() { /* the workspace is the page */ }
async function boot() {
S.user = await api('/api/me');
// An account belongs to one workforce. Landing on the other tool -- by a stale bookmark
// or a shared link -- silently shows the wrong job, so bounce rather than adapt.
if (S.user.role === 'annotator' && S.user.track !== 'both'
&& S.user.track !== PAGE_TRACK) {
location.replace(S.user.page || '/static/index.html');
return;
}
$('who').textContent = `${S.user.full_name || S.user.username} · ${S.user.completed} done`
+ (S.user.qualified ? '' : ' · calibration');
$('adminLink').hidden = !['reviewer', 'admin'].includes(S.user.role);
showWork();
buildPalette();
await loadNext();
}
/* ─────────────────────────── task ─────────────────────────── */
async function loadNext() {
const t = await api('/api/next');
if (t.empty) {
// Hide the whole working area. A waveform with no audio in it looks like a broken
// page, and the annotator has no way to tell that from an empty queue.
stop();
S.task = null;
S.turns = [];
S.buffer = null;
$('taskLabel').textContent = '';
if ($('modePill')) $('modePill').hidden = true;
if ($('workarea')) $('workarea').hidden = true;
$('calib').hidden = false;
$('calib').innerHTML = `Nothing to annotate right now.
${t.detail || ''}
This is not an error — there is simply no
work waiting for you. Leave the page open and press
`;
const again = $('retry');
if (again) again.onclick = () => loadNext().catch(e => toast(e.message));
renderTable();
return;
}
$('calib').hidden = true;
if ($('workarea')) $('workarea').hidden = false;
S.task = t;
S.turns = (t.turns || []).map(x => ({ start: x.start, end: x.end, speaker: x.speaker,
text: x.text || '' }));
normalise();
S.sel = -1;
S.cursor = 0;
S.listen = 0;
S.openedAt = Date.now();
S.dirty = false;
S.view = { start: 0, dur: Math.min(30, t.duration_s) };
$('taskLabel').textContent = `${t.recording} · chunk ${t.chunk + 1} · ${fmt(t.duration_s)}s`;
applyMode(t.mode || 'diarization');
await loadAudio(t.audio_url);
fitCanvas();
draw();
renderTable();
describeDraft();
}
/* Empty transcript boxes have two very different causes and the annotator cannot tell them
* apart: either the model produced no text for this chunk, or it did and they are looking at
* a genuine gap. Saying which one it is costs a line and saves a support question. */
function describeDraft() {
const el = $('draftNotice');
if (!el) return;
if (!wantsText() || !S.task) { el.hidden = true; return; }
const withText = S.turns.filter(t => (t.text || '').trim()).length;
el.hidden = false;
if (withText === 0) {
el.className = 'notice warn';
el.innerHTML = 'No machine transcript for this chunk. '
+ 'The boxes below are empty because the draft carried no text — type each turn from '
+ 'scratch. The speaker labels and timings are already correct.';
} else if (withText < S.turns.length) {
el.className = 'notice info';
el.textContent = `Machine transcript filled ${withText} of ${S.turns.length} turns. `
+ 'Correct what is there and fill in the rest.';
} else {
el.className = 'notice info';
el.textContent = 'Every turn carries a machine transcript. Correct it against what you '
+ 'hear — it is a draft, not a reference.';
}
}
async function loadAudio(url) {
S.ctx = S.ctx || new (window.AudioContext || window.webkitAudioContext)();
const bytes = await (await fetch(url, { credentials: 'same-origin' })).arrayBuffer();
S.buffer = await S.ctx.decodeAudioData(bytes);
// One coarse pass for the overview strip; the detail view recomputes from raw samples
// for whatever window is on screen, so zooming never looks blocky.
const data = S.buffer.getChannelData(0);
const N = 2000, step = Math.max(1, Math.floor(data.length / N));
const peaks = new Float32Array(N * 2);
for (let i = 0; i < N; i++) {
let lo = 0, hi = 0;
for (let j = i * step; j < Math.min((i + 1) * step, data.length); j++) {
const v = data[j];
if (v < lo) lo = v;
if (v > hi) hi = v;
}
peaks[i * 2] = lo; peaks[i * 2 + 1] = hi;
}
S.peaks = peaks;
}
/* Modes decide what the annotator is asked for. Transcription tasks arrive with boundaries
* the model already placed, so the waveform becomes a reference rather than the work surface
* and the transcript boxes take the focus. */
// What this page asks for. The task mode and the page agree by construction -- the queue
// only serves modes the account's track covers -- but the page has the final say, so the
// transcript column can never appear in the speaker-turn tool.
const wantsText = () => PAGE_TRACK === 'transcription'
|| (PAGE_TRACK === 'diarization' ? false
: Boolean(S.task && (S.task.mode === 'transcription' || S.task.mode === 'both')));
const wantsTurns = () => PAGE_TRACK === 'diarization'
|| Boolean(S.task && S.task.mode === 'both');
function applyMode(mode) {
const label = { diarization: 'speaker turns', transcription: 'transcript',
both: 'turns + transcript' }[mode] || mode;
const pill = $('modePill');
if (pill) {
pill.hidden = false;
pill.textContent = label;
pill.className = 'pill ' + (mode === 'transcription' ? 'warn' : 'ok');
}
document.body.classList.toggle('with-text', wantsText());
// Boundary tools only exist on the speaker-turn page; guard so asr.html can omit them.
if ($('splitBtn')) $('splitBtn').disabled = !wantsTurns();
if ($('delBtn')) $('delBtn').disabled = !wantsTurns();
}
/* ───────────────────────── turns ───────────────────────── */
function normalise() {
S.turns.forEach(t => {
t.start = Math.max(0, Math.min(t.start, t.end));
t.end = Math.min(S.task ? S.task.duration_s : t.end, Math.max(t.start, t.end));
});
S.turns = S.turns.filter(t => t.end - t.start >= MIN_TURN);
S.turns.sort((a, b) => a.start - b.start || a.end - b.end);
}
function renderTable() {
const body = $('turnBody');
body.innerHTML = '';
S.turns.forEach((t, i) => {
const tr = document.createElement('tr');
if (i === S.sel) tr.className = 'sel';
const spkCell = wantsTurns()
? ``
: `${t.speaker}`;
tr.innerHTML =
`
${i + 1}
` +
`
` +
`
${fmt(t.start)}
` +
`
${fmt(t.end)}
` +
`
${fmt(t.end - t.start)}
` +
`
${spkCell}
` +
`
` +
`
`;
tr.onclick = ev => {
if (ev.target.dataset.del !== undefined || ev.target.dataset.play !== undefined) return;
S.sel = i; centreOn((t.start + t.end) / 2); draw(); highlightRow();
};
body.appendChild(tr);
});
body.querySelectorAll('[data-del]').forEach(b => {
b.onclick = ev => { ev.stopPropagation(); removeTurn(+b.dataset.del); };
});
body.querySelectorAll('[data-play]').forEach(b => {
b.onclick = ev => { ev.stopPropagation(); playTurn(+b.dataset.play); };
});
body.querySelectorAll('[data-spk]').forEach(sel => {
sel.onchange = () => {
S.turns[+sel.dataset.spk].speaker = sel.value;
S.dirty = true; draw();
};
});
body.querySelectorAll('[data-text]').forEach(box => {
autoGrow(box);
box.oninput = () => {
S.turns[+box.dataset.text].text = box.value;
S.dirty = true; autoGrow(box); updateSummary(); renderFullText();
};
box.onfocus = () => {
// Selecting the row a box belongs to keeps the waveform on what is being typed.
S.sel = +box.dataset.text;
centreOn((S.turns[S.sel].start + S.turns[S.sel].end) / 2);
draw(); highlightRow();
};
box.onkeydown = ev => {
if (ev.key === 'Enter' && !ev.shiftKey && !ev.ctrlKey) {
ev.preventDefault();
const n = +box.dataset.text + 1;
if (n < S.turns.length) {
playTurn(n);
body.querySelector(`[data-text="${n}"]`)?.focus();
}
}
};
});
updateSummary();
highlightRow();
renderFullText();
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
function autoGrow(el) {
el.style.height = 'auto';
el.style.height = Math.min(160, el.scrollHeight) + 'px';
}
function highlightRow() {
document.querySelectorAll('#turnBody tr').forEach((tr, i) =>
tr.classList.toggle('sel', i === S.sel));
}
// Called on every keystroke, so it must not touch the DOM the caret lives in.
function updateSummary() {
const speech = S.turns.reduce((a, t) => a + (t.end - t.start), 0);
const spk = new Set(S.turns.map(t => t.speaker)).size;
let txt = `${S.turns.length} turns · ${spk} speakers · ${fmt(speech)}s speech`;
if (wantsText()) {
const done = S.turns.filter(t => (t.text || '').trim()).length;
const chars = S.turns.reduce((a, t) => a + (t.text || '').length, 0);
txt += ` · ${done}/${S.turns.length} transcribed · ${chars} chars`;
}
$('turnSummary').textContent = txt;
}
/* The assembled view. Derived on every keystroke rather than stored, so it can never drift
* from the boxes it came from -- the same reason the exported full transcript is joined from
* the segments instead of being annotated separately. */
function renderFullText() {
const el = $('fullText');
if (!el) return;
const withSpeakers = ($('fullSpeakers') || {}).checked !== false;
const rows = [...S.turns].sort((a, b) => a.start - b.start || a.end - b.end);
let out = '', last = null, chars = 0;
for (const t of rows) {
const text = (t.text || '').trim();
if (!text) continue;
chars += text.length;
if (withSpeakers) {
// Consecutive turns by one speaker read as a paragraph; repeating the label every
// line turns a conversation into a list.
out += (t.speaker !== last ? `${escapeHtml(t.speaker)}: ` : ' ')
+ escapeHtml(text) + (t.speaker !== last ? '' : '');
out += ' ';
last = t.speaker;
} else {
out += escapeHtml(text) + ' ';
}
}
el.innerHTML = out || 'Nothing transcribed yet.';
el.dataset.chars = chars;
}
function playTurn(i) {
const t = S.turns[i];
if (!t) return;
S.cursor = t.start;
centreOn((t.start + t.end) / 2);
play(t.start, t.end);
draw();
}
function removeTurn(i) {
S.turns.splice(i, 1);
if (S.sel >= S.turns.length) S.sel = S.turns.length - 1;
S.dirty = true;
draw(); renderTable();
}
function setSpeaker(idx) {
if (S.sel < 0 || !SPEAKERS[idx]) return;
S.turns[S.sel].speaker = SPEAKERS[idx].key;
S.dirty = true;
draw(); renderTable();
}
function splitAtCursor() {
const i = S.turns.findIndex(t => t.start < S.cursor && S.cursor < t.end);
if (i < 0) { toast('Cursor is not inside a turn'); return; }
const t = S.turns[i];
if (S.cursor - t.start < MIN_TURN || t.end - S.cursor < MIN_TURN) return;
// A split divides audio, not a sentence: text stays with the first half for the
// annotator to cut by hand rather than being silently duplicated into both.
S.turns.splice(i + 1, 0, { start: S.cursor, end: t.end, speaker: t.speaker, text: '' });
t.end = S.cursor;
S.sel = i + 1;
S.dirty = true;
draw(); renderTable();
}
function buildPalette() {
if (!$('palette') || !wantsTurns()) return;
$('palette').innerHTML = SPEAKERS.map((s, i) =>
``).join(' ');
$('palette').querySelectorAll('[data-spk]').forEach(b => {
b.onclick = () => setSpeaker(+b.dataset.spk);
});
}
/* ─────────────────────────── drawing ─────────────────────────── */
function fitCanvas() {
for (const id of ['wave', 'mini']) {
const c = $(id), r = c.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
c.width = Math.max(1, Math.floor(r.width * dpr));
c.height = Math.max(1, Math.floor(r.height * dpr));
}
}
const t2x = (t, c) => ((t - S.view.start) / S.view.dur) * c.width;
const x2t = (x, c) => S.view.start + (x / c.width) * S.view.dur;
function drawWave() {
const c = $('wave'), g = c.getContext('2d');
g.clearRect(0, 0, c.width, c.height);
g.fillStyle = '#0b0e12'; g.fillRect(0, 0, c.width, c.height);
if (!S.buffer) return;
const data = S.buffer.getChannelData(0), sr = S.buffer.sampleRate;
const mid = c.height / 2, amp = c.height / 2 - 6;
g.strokeStyle = '#39424e';
g.beginPath(); g.moveTo(0, mid); g.lineTo(c.width, mid); g.stroke();
g.strokeStyle = '#5c6b7c';
g.beginPath();
for (let x = 0; x < c.width; x++) {
const a = Math.floor(x2t(x, c) * sr), b = Math.floor(x2t(x + 1, c) * sr);
let lo = 0, hi = 0;
for (let j = Math.max(0, a); j < Math.min(b, data.length); j++) {
const v = data[j];
if (v < lo) lo = v;
if (v > hi) hi = v;
}
g.moveTo(x + 0.5, mid - hi * amp);
g.lineTo(x + 0.5, mid - lo * amp);
}
g.stroke();
// regions
S.turns.forEach((t, i) => {
const x0 = t2x(t.start, c), x1 = t2x(t.end, c);
if (x1 < 0 || x0 > c.width) return;
const col = colourOf(t.speaker);
g.fillStyle = col + (i === S.sel ? '4d' : '26');
g.fillRect(x0, 0, x1 - x0, c.height);
g.strokeStyle = col; g.lineWidth = i === S.sel ? 2 : 1;
g.strokeRect(x0 + 0.5, 0.5, x1 - x0 - 1, c.height - 1);
if (x1 - x0 > 46) {
g.fillStyle = col;
g.font = `${11 * (window.devicePixelRatio || 1)}px system-ui`;
g.fillText(t.speaker, x0 + 5, 14 * (window.devicePixelRatio || 1));
}
});
// cursor
const cx = t2x(S.cursor, c);
g.strokeStyle = '#fff'; g.lineWidth = 1;
g.beginPath(); g.moveTo(cx + 0.5, 0); g.lineTo(cx + 0.5, c.height); g.stroke();
}
function drawMini() {
const c = $('mini'), g = c.getContext('2d');
g.clearRect(0, 0, c.width, c.height);
g.fillStyle = '#0b0e12'; g.fillRect(0, 0, c.width, c.height);
if (!S.peaks || !S.task) return;
const mid = c.height / 2, amp = c.height / 2 - 2, N = S.peaks.length / 2;
g.strokeStyle = '#4a5563'; g.beginPath();
for (let x = 0; x < c.width; x++) {
const i = Math.floor((x / c.width) * N);
g.moveTo(x + 0.5, mid - S.peaks[i * 2 + 1] * amp);
g.lineTo(x + 0.5, mid - S.peaks[i * 2] * amp);
}
g.stroke();
const D = S.task.duration_s;
S.turns.forEach(t => {
g.fillStyle = colourOf(t.speaker) + '66';
g.fillRect((t.start / D) * c.width, 0, ((t.end - t.start) / D) * c.width, c.height);
});
// viewport
const vx = (S.view.start / D) * c.width, vw = (S.view.dur / D) * c.width;
g.strokeStyle = '#fff'; g.lineWidth = 2;
g.strokeRect(vx + 1, 1, Math.max(2, vw - 2), c.height - 2);
}
function draw() { drawWave(); drawMini(); updateClock(); }
function updateClock() {
if (!S.task) return;
$('clock').textContent = `${fmt(S.cursor)} / ${fmt(S.task.duration_s)} s`;
const r = S.task.duration_s ? S.listen / S.task.duration_s : 0;
const cls = r >= 0.9 ? 'ok' : r >= 0.5 ? 'warn' : 'bad';
$('listenPill').innerHTML =
`listened ${Math.round(r * 100)}%`;
}
function centreOn(t) {
S.view.start = clamp(t - S.view.dur / 2, 0, Math.max(0, S.task.duration_s - S.view.dur));
}
function zoom(factor, anchor) {
const D = S.task.duration_s;
const a = anchor ?? S.cursor;
const nd = clamp(S.view.dur * factor, 0.5, D);
S.view.start = clamp(a - (a - S.view.start) * (nd / S.view.dur), 0, Math.max(0, D - nd));
S.view.dur = nd;
draw();
}
/* ─────────────────────────── mouse ─────────────────────────── */
function hit(c, x, t) {
for (let i = S.turns.length - 1; i >= 0; i--) {
const r = S.turns[i], x0 = t2x(r.start, c), x1 = t2x(r.end, c);
if (x >= x0 - EDGE_PX && x <= x1 + EDGE_PX) {
if (Math.abs(x - x0) <= EDGE_PX) return { i, mode: 'start' };
if (Math.abs(x - x1) <= EDGE_PX) return { i, mode: 'end' };
if (t >= r.start && t <= r.end) return { i, mode: 'move' };
}
}
return null;
}
function wireCanvas() {
const c = $('wave');
const px = ev => (ev.clientX - c.getBoundingClientRect().left)
* (window.devicePixelRatio || 1);
c.addEventListener('mousedown', ev => {
const x = px(ev), t = x2t(x, c), h = hit(c, x, t);
if (h) {
S.sel = h.i;
S.drag = { ...h, grabT: t, orig: { ...S.turns[h.i] } };
} else {
// Dragging empty space creates a turn; a click without movement just seeks.
S.drag = { mode: 'create', from: t, i: -1 };
S.cursor = t;
}
draw(); renderTable();
});
c.addEventListener('mousemove', ev => {
const x = px(ev), t = clamp(x2t(x, c), 0, S.task ? S.task.duration_s : 0);
if (!S.drag) {
const h = S.task && hit(c, x, t);
c.style.cursor = h ? (h.mode === 'move' ? 'grab' : 'ew-resize') : 'crosshair';
const hint = $('hint');
hint.style.display = 'block';
hint.textContent = fmt(t) + ' s';
hint.style.left = (ev.clientX - c.getBoundingClientRect().left + 12) + 'px';
hint.style.top = '6px';
return;
}
const d = S.drag;
if (d.mode === 'create') {
d.to = t;
} else {
const r = S.turns[d.i];
if (d.mode === 'start') r.start = Math.min(t, r.end - MIN_TURN);
else if (d.mode === 'end') r.end = Math.max(t, r.start + MIN_TURN);
else {
const shift = t - d.grabT, len = d.orig.end - d.orig.start;
r.start = clamp(d.orig.start + shift, 0, S.task.duration_s - len);
r.end = r.start + len;
}
S.dirty = true;
}
draw();
});
window.addEventListener('mouseup', () => {
const d = S.drag;
S.drag = null;
if (!d) return;
if (d.mode === 'create' && d.to !== undefined) {
const a = Math.min(d.from, d.to), b = Math.max(d.from, d.to);
if (b - a >= MIN_TURN) {
const spk = S.sel >= 0 ? S.turns[S.sel].speaker : SPEAKERS[0].key;
S.turns.push({ start: a, end: b, speaker: spk, text: '' });
S.dirty = true;
}
}
normalise();
if (d.mode === 'create' && d.to !== undefined) {
S.sel = S.turns.findIndex(t => Math.abs(t.start - Math.min(d.from, d.to)) < 1e-6);
}
draw(); renderTable();
});
c.addEventListener('mouseleave', () => { $('hint').style.display = 'none'; });
c.addEventListener('wheel', ev => {
if (!S.task) return;
ev.preventDefault();
zoom(ev.deltaY > 0 ? 1.25 : 0.8, x2t(px(ev), c));
}, { passive: false });
// The overview strip is a scrub bar for the detail view.
const m = $('mini');
const jump = ev => {
if (!S.task) return;
const r = m.getBoundingClientRect();
centreOn(((ev.clientX - r.left) / r.width) * S.task.duration_s);
draw();
};
m.addEventListener('mousedown', ev => { jump(ev); m._down = true; });
m.addEventListener('mousemove', ev => { if (m._down) jump(ev); });
window.addEventListener('mouseup', () => { m._down = false; });
}
/* ─────────────────────────── playback ─────────────────────────── */
function play(from, until) {
if (!S.buffer) return;
stop();
const src = S.ctx.createBufferSource();
src.buffer = S.buffer;
src.connect(S.ctx.destination);
if (until && until > from) src.start(0, from, until - from);
else src.start(0, from);
S.src = src;
S.playing = true;
S.playFrom = from;
S.playStartedAt = S.ctx.currentTime;
$('play').textContent = '❚❚ Pause';
src.onended = () => { if (S.playing) stop(); };
requestAnimationFrame(tick);
}
function stop() {
if (S.src) {
// Only time the audio was genuinely audible counts toward listen_seconds.
S.listen += Math.max(0, S.ctx.currentTime - S.playStartedAt);
try { S.src.stop(); } catch (e) { /* already ended */ }
S.src.disconnect();
S.src = null;
}
S.playing = false;
$('play').textContent = '▶ Play';
updateClock();
}
function toggle() {
if (S.playing) { S.cursor = playhead(); stop(); }
else play(S.cursor >= (S.task?.duration_s ?? 0) - 0.05 ? 0 : S.cursor);
draw();
}
const playhead = () =>
S.playing ? Math.min(S.playFrom + (S.ctx.currentTime - S.playStartedAt),
S.task.duration_s) : S.cursor;
function tick() {
if (!S.playing) return;
S.cursor = playhead();
// Follow the playhead once it leaves the visible window.
if (S.cursor > S.view.start + S.view.dur * 0.9 || S.cursor < S.view.start) {
S.view.start = clamp(S.cursor - S.view.dur * 0.2, 0,
Math.max(0, S.task.duration_s - S.view.dur));
}
draw();
requestAnimationFrame(tick);
}
/* ─────────────────────────── submit ─────────────────────────── */
function payload(final) {
return JSON.stringify({
task_id: S.task.task_id,
turns: S.turns.map(t => ({ start: +t.start.toFixed(3), end: +t.end.toFixed(3),
speaker: t.speaker, text: t.text || '' })),
listen_seconds: S.listen + (S.playing ? S.ctx.currentTime - S.playStartedAt : 0),
active_seconds: (Date.now() - S.openedAt) / 1000,
final,
});
}
async function autosave() {
if (!S.task || !S.dirty) return;
try {
await api('/api/submit', { method: 'POST', body: payload(false) });
S.dirty = false;
} catch (e) { /* transient; the next tick retries */ }
}
async function submit() {
if (!S.task) return;
if (!S.turns.length && !confirm('Submit with no speaker turns at all?')) return;
if (wantsText()) {
const missing = S.turns.filter(t => !(t.text || '').trim()).length;
if (missing && !confirm(missing + ' of ' + S.turns.length +
' turns have no transcript.\nSubmit anyway?')) return;
}
const ratio = S.listen / S.task.duration_s;
if (ratio < 0.5 &&
!confirm(`You have played only ${Math.round(ratio * 100)}% of this chunk.\n` +
'Submit anyway? Playback is recorded and reviewed.')) return;
$('submitBtn').disabled = true;
try {
const r = await api('/api/submit', { method: 'POST', body: payload(true) });
if (r.calibration && !r.calibration.qualified) {
toast(`Calibration ${r.calibration.done}/${r.calibration.needed}` +
(r.calibration.mean_der !== undefined
? ` · mean DER ${r.calibration.mean_der} (need ≤ ${r.calibration.threshold})`
: ''), 6000);
} else if (r.calibration?.qualified) {
toast('Calibration passed — you now receive production tasks.', 6000);
} else {
toast(`Submitted: ${r.stats.turns} turns`);
}
stop();
S.user = await api('/api/me');
$('who').textContent = `${S.user.full_name || S.user.username} · ${S.user.completed} done`
+ (S.user.qualified ? '' : ' · calibration');
await loadNext();
} catch (e) { toast('Submit failed: ' + e.message, 5000); }
$('submitBtn').disabled = false;
}
async function skip() {
if (!S.task || !confirm('Skip this chunk? It goes back into the queue.')) return;
try {
await api(`/api/skip/${S.task.task_id}`, { method: 'POST' });
stop();
await loadNext();
} catch (e) { toast(e.message); }
}
/* ─────────────────────────── keys ─────────────────────────── */
function wireKeys() {
window.addEventListener('keydown', ev => {
const typing = ['INPUT', 'TEXTAREA', 'SELECT'].includes(ev.target.tagName);
if (ev.ctrlKey && ev.key === 'Enter') { ev.preventDefault(); return submit(); }
// Every other shortcut is a bare character, so it has to stand down inside a text box
// or typing "1" would relabel a speaker instead of entering a digit.
if (typing) return;
if (!S.task) return;
const step = ev.shiftKey ? 1.0 : 0.05;
switch (ev.key) {
case ' ': ev.preventDefault(); toggle(); break;
case '1': case '2': case '3': case '4': setSpeaker(+ev.key - 1); break;
case 's': case 'S': splitAtCursor(); break;
case 'Delete': case 'Backspace':
if (S.sel >= 0) { ev.preventDefault(); removeTurn(S.sel); } break;
case 'Tab':
ev.preventDefault();
if (S.turns.length) {
S.sel = (S.sel + (ev.shiftKey ? -1 : 1) + S.turns.length) % S.turns.length;
centreOn((S.turns[S.sel].start + S.turns[S.sel].end) / 2);
draw(); renderTable();
}
break;
case 'ArrowLeft':
ev.preventDefault(); S.cursor = clamp(S.cursor - step, 0, S.task.duration_s); draw(); break;
case 'ArrowRight':
ev.preventDefault(); S.cursor = clamp(S.cursor + step, 0, S.task.duration_s); draw(); break;
}
});
}
/* ─────────────────────────── init ─────────────────────────── */
function init() {
const on = (id, ev, fn) => { const el = $(id); if (el) el[ev] = fn; };
on('logout', 'onclick', async () => {
await api('/api/logout', { method: 'POST' }).catch(() => {});
location.href = '/static/index.html';
});
on('play', 'onclick', toggle);
on('zoomIn', 'onclick', () => zoom(0.6));
on('zoomOut', 'onclick', () => zoom(1.6));
on('fit', 'onclick', () => { S.view = { start: 0, dur: S.task.duration_s }; draw(); });
on('splitBtn', 'onclick', splitAtCursor);
on('delBtn', 'onclick', () => { if (S.sel >= 0) removeTurn(S.sel); });
on('submitBtn', 'onclick', submit);
on('skipBtn', 'onclick', skip);
on('fullSpeakers', 'onchange', renderFullText);
on('copyFull', 'onclick', () => {
const el = $('fullText');
if (!el) return;
navigator.clipboard.writeText(el.innerText.trim())
.then(() => toast('Full transcript copied'))
.catch(() => toast('Copy failed — select the text manually'));
});
wireCanvas();
wireKeys();
window.addEventListener('resize', () => { fitCanvas(); draw(); });
setInterval(autosave, AUTOSAVE_MS);
window.addEventListener('beforeunload', ev => {
if (S.dirty) { ev.preventDefault(); ev.returnValue = ''; }
});
boot().catch(() => showLogin());
}
document.addEventListener('DOMContentLoaded', init);