/* CuratorBot viewer: renders any brief produced by curatorbot.pipeline.build_brief. */
"use strict";
let LIST = [];
let D = null, T = null, G = null, GAZ = {}, seg = {}, H = [], log = [];
let HEALTH = {live:false, asr:false, passcode:false};
const LIVE_ID = "__live__";
let liveBrief = null;
const $ = (s, r=document) => r.querySelector(s);
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
const t2s = t => { if(!t) return 0; const p = t.split(":").map(Number); while(p.length<3) p.unshift(0); return p[0]*3600+p[1]*60+p[2]; };
const timeOf = id => seg[id] && seg[id].start ? seg[id].start : (id || "");
const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
/* ---------- loading ---------- */
async function api(path, opts){ const r = await fetch(path, opts);
if(r.status === 401 && r.headers.get("X-Login-Required")){ location.href = "/login"; throw new Error("Sign in needed."); }
const body = await r.json().catch(()=>({}));
if(!r.ok) throw new Error(body.detail || `Request failed (${r.status})`); return body; }
async function boot(){
try{ HEALTH = await api("/api/health"); }catch(e){}
let list = [];
try{ list = await api("/api/interviews"); }catch(e){ $("#ttl").textContent = "Could not reach the server."; return; }
LIST = list;
const pick = $("#pick");
pick.innerHTML = list.map(i => `${esc(i.title)} `).join("");
pick.onchange = async () => { await open(pick.value); setMode("demo"); };
renderQueue();
const want = location.hash.slice(1);
const first = list.find(i => i.id === want) || list[0];
if(first){ pick.value = first.id; await open(first.id); } else { $("#ttl").textContent = "No interviews yet"; }
setMode(want === "live" ? "live" : (list.some(i => i.id === want) ? "demo" : "queue"));
setupLive();
}
async function open(id){
if(id === LIVE_ID && liveBrief){ load(liveBrief); return; }
$("#ttl").textContent = "Loading…";
try{ load(await api("/api/interviews/" + encodeURIComponent(id))); }
catch(e){ $("#ttl").textContent = e.message; }
}
function load(data){
D = data; T = D.testimony; G = D.agent || {}; GAZ = D.gazetteer || {};
seg = Object.fromEntries(T.segments.map(s => [s.segId, s]));
H = (G.headings || []).map((h,i) => ({...h, id:"h"+i, status:"Unreviewed", value:h.heading,
ok: h.grounded !== false && h.in_vocabulary !== false}));
log = [];
$("#tab-catalogue").hidden = !D.backtest;
if(currentTab === "catalogue" && !D.backtest) currentTab = "brief";
renderCatalogue();
renderHeader(); renderBrief(); renderTranscript(); renderPlaces(); renderHeadings(); renderDonor(); renderHood();
showTab(currentTab);
}
/* ---------- mode + tabs ---------- */
let currentTab = "brief";
function setMode(mode){ ["queue","demo","live"].forEach(m => { $("#"+m).hidden = m !== mode; $("#m-"+m).setAttribute("aria-pressed", String(m === mode)); });
window.scrollTo(0, 0); }
$("#m-queue").onclick = () => setMode("queue");
$("#m-demo").onclick = () => setMode("demo");
$("#m-live").onclick = () => setMode("live");
function showTab(name){ currentTab = name;
document.querySelectorAll(".tabs button").forEach(b => b.setAttribute("aria-selected", String(b.dataset.tab === name)));
["brief","transcript","places","headings","donor","catalogue","hood"].forEach(n => $("#p-"+n).hidden = n !== name); }
document.querySelectorAll(".tabs button").forEach(b => b.onclick = () => showTab(b.dataset.tab));
document.addEventListener("click", e => {
const b = e.target.closest("[data-seg]"); if(b && b.dataset.seg){ gotoSeg(b.dataset.seg, b.dataset.q || ""); return; }
const p = e.target.closest("[data-place]"); if(p){ showTab("places"); renderPlaces(p.dataset.place); }
});
function gotoSeg(id, q){
showTab("transcript"); renderTranscript(q ? {seg:id, q} : null);
const el = document.getElementById("t-"+id); if(!el) return;
el.classList.add("focus"); el.scrollIntoView({behavior: reduced() ? "auto" : "smooth", block:"center"});
setTimeout(() => el.classList.remove("focus"), 2400);
}
/* ---------- header ---------- */
function renderHeader(){
const note = T.note || "";
$("#notice").hidden = !note; $("#notice").innerHTML = note ? `About this interview. ${esc(note)}` : "";
const langs = (G.languages && G.languages.length) ? G.languages : [...new Set((G.media?.languages || []).map(l => l.lang))];
$("#acc").textContent = [T.id, T.parts ? `${T.parts} parts` : "", T.duration || "", langs.join(", ")].filter(Boolean).join(" · ");
$("#ttl").textContent = T.title;
const claims = G.claims || [], ms = D.mentions || [];
const bad = claims.filter(c => c.verdict === "contradicted" || c.verdict === "incomplete").length;
const fixed = ms.filter(m => ["relabelled","relinked","added","split"].includes(m.action)).length;
const rej = G.validation ? G.validation.rejected : 0;
$("#status").innerHTML = [
statusChip(T.status),
claims.length ? `${bad} donor discrepanc${bad===1?"y":"ies"} ` : "",
G.media?.flags?.length ? `${G.media.flags.length} listening flag${G.media.flags.length===1?"":"s"} ` : "",
G.gap ? `Collection gap: ${esc(G.gap.band)} ` : "",
`${H.filter(h=>h.ok).length} heading suggestions `,
`${ms.length} place mentions, ${fixed} corrected `,
rej ? `${rej} stopped by validators ` : ""].join("");
}
/* ---------- status, queue, catalogue ---------- */
const STATUS = {under_review:["flag","Under review: new submission"], released:["good","Released and catalogued"], synthetic:["","Synthetic demonstration"]};
function statusChip(s){ const [cls, label] = STATUS[s] || STATUS.under_review; return `${label} `; }
const pct = x => x == null ? "–" : `${Math.round(x * 100)}%`;
function renderQueue(){
const groups = [["under_review","New submissions under review"],["released","Released interviews, scored against the catalogue"],["synthetic","Synthetic demonstration"]];
// Catalogue scores only for released interviews: a new submission has no catalogue record yet.
const rel = LIST.filter(r => r.status === "released" && r.backtest && r.backtest.recall_head != null);
const mean = rel.length ? rel.reduce((a,r) => a + r.backtest.recall_head, 0) / rel.length : null;
$("#qstats").innerHTML = [`${LIST.length} interview${LIST.length===1?"":"s"} `,
`${LIST.filter(r=>r.status==="under_review").length} under review `,
`${LIST.filter(r=>r.status==="released").length} released `,
mean != null ? `Catalogue headings found: ${pct(mean)} on average ` : ""].join("");
$("#qlist").innerHTML = groups.map(([s, label]) => { const rows = LIST.filter(r => r.status === s); if(!rows.length) return "";
return `
${label} ${rows.map(r => `
${esc(r.title)}
${statusChip(r.status)}${r.duration?`${esc(r.duration)} `:""}${(r.languages||[]).length?`${esc(r.languages.join(", "))} `:""}
${r.gap?`Gap: ${esc(r.gap)} `:""}
${r.claims?`${r.discrepancies} donor discrepanc${r.discrepancies===1?"y":"ies"} `:""}
${r.flags?`${r.flags} listening flag${r.flags===1?"":"s"} `:""}
${r.headings} headings ${r.places} place mentions
${r.backtest && r.status === "released"?`${pct(r.backtest.recall_head)} of ${r.backtest.catalogued} catalogue headings found `:""}
${r.summary?`
${esc(r.summary)}${r.summary.length>=280?"…":""}
`:""}
Open brief
`).join("")}
`; }).join("")
|| 'No interviews prepared yet.
';
document.querySelectorAll("[data-open]").forEach(b => b.onclick = async () => { $("#pick").value = b.dataset.open; await open(b.dataset.open); setMode("demo"); });
}
function renderCatalogue(){
const b = D.backtest; if(!b){ $("#p-catalogue").innerHTML = ""; return; }
const outside = new Set(b.missed_outside_vocabulary || []);
const li = (h, chip, extra="") => `${esc(h)} ${chip}${extra} `;
const ev = h => { const e = (b.extra_evidence||{})[h]; return e && e.quote ? ` ${esc(timeOf(e.segId))} "${esc(e.quote)}" ` : ""; };
$("#p-catalogue").innerHTML = `
How CuratorBot compares with the catalogue
${pct(b.recall_head)} catalogue headings found, by main heading
${pct(b.recall_exact)} found exactly, with subdivisions
${pct(b.recall_within_vocabulary)} found, counting only headings in CuratorBot's vocabulary
${b.with_rules ? `
${pct(b.with_rules.recall_exact)} found exactly, adding the form headings proposed by rule
` : ""}
${b.catalogued} headings in the catalogue record; CuratorBot's top ${b.suggested} suggestions compared.${b.catalogue_url?` Open the catalogue record .`:""}
Catalogue headings
${(b.matched||[]).map(h => li(h, 'Found exactly ')).join("")}
${(b.matched_head_only||[]).map(h => li(h, 'Main heading found ')).join("")}
${(b.missed||[]).map(h => li(h, 'Missed ', outside.has(h) ? ' not in the vocabulary yet ' : "")).join("")}
Suggested but not in the catalogue
Not necessarily wrong: a curator decides whether each adds something the record lacks.
${(b.extra||[]).map(h => li(h, "", ev(h))).join("") || 'None. '}
"Missed" headings that are not in the vocabulary yet show a gap in the authority list, not an error by the model; loading the museum's full authority file closes it.
`;
}
/* ---------- brief ---------- */
function segAt(stamp){ return [...T.segments].reverse().find(x => t2s(x.start) <= t2s(stamp)) || T.segments[0]; }
function renderBrief(){
const chapters = (G.chapters || []).map(c => { const s = c.segId ? seg[c.segId] : T.segments.find(x => x.start === c.start);
return `${esc(c.start || (s&&s.start) || "")} ${esc(c.title)} `; }).join("");
const total = t2s(T.duration) || 1;
const L = G.media?.languages;
const langPanel = L && L.length ? `Languages
${L.map(l=>` `).join("")}
${[...new Map(L.map(l=>[l.lang,l])).values()].map(l=>` ${esc(l.lang)}${l.code!=="en"?`, ${l.from} to ${l.to}`:""} `).join("")}
`
: (G.languages && G.languages.length ? `Languages ${esc(G.languages.join(", "))}
` : "");
const gap = G.gap ? `Collection gap ${esc(G.gap.band)} priority
${G.gap.reasons.map(r=>`
${esc(r.text)} ${esc(r.level)}
`).join("")}
${esc(G.gap.note||"")}
`
: `Collection gap Needs the collection profile built from the catalogue export. Not available for this interview yet.
`;
const flags = G.media?.flags?.length ? `Needs human listening ${G.media.flags.map(f=>{const s=segAt(f.at);return `
${esc(f.at)} ${esc(f.text)}
`}).join("")}
` : "";
const parts = G.media?.parts?.length ? `Media${G.media.simulated?" (simulated)":""} Part Length Audio ${G.media.parts.map(p=>`${esc(p.part)} ${esc(p.duration)} ${esc(p.audio||p.audio_codec||"")} `).join("")}
` : "";
$("#p-brief").innerHTML = `
Summary ${esc(G.summary || "No summary: the agent step did not run for this interview.")}
${chapters ? `
` : ""}
${gap}${langPanel}${flags}${parts}
`;
}
/* ---------- transcript ---------- */
let tFilter = "all", tQuery = "";
function highlight(html, q){ const plain = esc(q); const k = html.indexOf(plain);
return k >= 0 ? html.slice(0,k) + "" + plain + " " + html.slice(k+plain.length) : `${html} `; }
function markText(id, text, quote){
const ann = seg[id].translation || seg[id].text;
if(text !== ann || quote) return quote ? highlight(esc(text), quote) : esc(text);
const ms = (D.mentions || []).filter(m => m.segId === id).sort((a,b) => a.start - b.start);
let out = "", i = 0;
for(const m of ms){ if(m.start < i) continue; out += esc(text.slice(i, m.start));
const g = GAZ[m.key] || {name:m.surface}; const fix = !["linked","confirmed"].includes(m.action);
out += `${esc(text.slice(m.start,m.end))} `; i = m.end; }
return out + esc(text.slice(i));
}
function renderTranscript(focus){
const turns = T.segments.filter(s => (tFilter==="all" || s.role==="A") && (!tQuery || (s.text+" "+(s.translation||"")).toLowerCase().includes(tQuery.toLowerCase())));
$("#p-transcript").innerHTML = `
${turns.map(s => {
const fq = focus && focus.seg === s.segId ? focus.q : "";
const foreign = s.lang && s.lang !== "en" && s.translation;
const main = foreign ? (fq && s.text.includes(fq) ? highlight(esc(s.text), fq) : esc(s.text)) : markText(s.segId, s.text, fq);
const tr = foreign ? `
Machine translation: ${markText(s.segId, s.translation, fq && s.translation.includes(fq) ? fq : "")}
` : "";
return `
${esc(s.start||"")} ${s.role==="Q"?"INT":"NAR"} ${main}${tr}
`; }).join("")
|| `
No turns match "${esc(tQuery)}".
`}
`;
const q = $("#tq"); q.oninput = () => { tQuery = q.value; const pos = q.selectionStart; renderTranscript(); const n = $("#tq"); n.focus(); n.setSelectionRange(pos,pos); };
document.querySelectorAll("#p-transcript .seg button").forEach(b => b.onclick = () => { tFilter = b.dataset.f; renderTranscript(); });
}
/* ---------- places + map ---------- */
function mapSVG(sel){
const journeys = (G.journeys || []).map((j,n) => ({...j, n: n+1})).filter(j => j.status !== "rejected");
const used = new Set(); journeys.forEach(j => { if(j.fromKey) used.add(j.fromKey); if(j.toKey) used.add(j.toKey); });
(D.mentions || []).forEach(m => used.add(m.key));
const pts = [...used].map(k => k && GAZ[k] && GAZ[k].lat != null ? {k, ...GAZ[k]} : null).filter(Boolean);
const approx = g => g.precision === "near" || g.precision === "country" || g.uncertain;
const tag = g => g.precision === "near" ? `${g.name} (near)` : g.precision === "country" ? `${g.name} (country only)` : g.uncertain ? `${g.name}?` : g.name;
const inEU = p => p.lon >= -12 && p.lon <= 45 && p.lat >= 34 && p.lat <= 62;
// Frame the journeys when there are any, so local places are not crowded by far-away mentions.
const jk = new Set(); journeys.forEach(j => [j.fromKey, j.toKey].forEach(k => k && GAZ[k] && GAZ[k].lat != null && inEU(GAZ[k]) && jk.add(k)));
const jp = pts.filter(p => jk.has(p.k));
const frame = jp.length >= 2 ? jp : pts.filter(inEU);
if(!frame.length) return "";
const fx0 = Math.min(...frame.map(p=>p.lon)) - 2, fx1 = Math.max(...frame.map(p=>p.lon)) + 2, fy0 = Math.min(...frame.map(p=>p.lat)) - 1.2, fy1 = Math.max(...frame.map(p=>p.lat)) + 1.2;
const inside = pts.filter(p => inEU(p) && p.lon >= fx0 && p.lon <= fx1 && p.lat >= fy0 && p.lat <= fy1);
const jAll = new Set(journeys.flatMap(j => [j.fromKey, j.toKey]).filter(Boolean));
const outside = pts.filter(p => !inside.includes(p) && !jAll.has(p.k)).map(p => p.name);
let lo0 = Math.min(...inside.map(p=>p.lon)) - 1.5, lo1 = Math.max(...inside.map(p=>p.lon)) + 1.5;
let la0 = Math.min(...inside.map(p=>p.lat)) - 1, la1 = Math.max(...inside.map(p=>p.lat)) + 1;
if(lo1 - lo0 < 8){ const c=(lo0+lo1)/2; lo0=c-4; lo1=c+4; } if(la1 - la0 < 4){ const c=(la0+la1)/2; la0=c-2; la1=c+2; }
const W = 760, Hh = 470, X = lon => 70 + (lon-lo0)/(lo1-lo0)*(W-110), Y = lat => 40 + (la1-lat)/(la1-la0)*(Hh-80);
// cluster points closer than 0.3 degrees so labels do not collide
const inJ = k => journeys.some(j => j.fromKey===k || j.toKey===k);
const clusters = [];
[...inside].sort((a,b) => (inJ(b.k)-inJ(a.k))).forEach(p => {
const c = clusters.find(c => Math.hypot(c.lon-p.lon, c.lat-p.lat) < 0.3);
if(c){ c.keys.push(p.k); c.names.push(tag(p)); c.exact = c.exact || !approx(p); } else clusters.push({lon:p.lon, lat:p.lat, keys:[p.k], names:[tag(p)], kind:p.kind, exact: !approx(p)});
});
const where = k => { const c = clusters.find(c => c.keys.includes(k)); return c ? [X(c.lon), Y(c.lat)] : null; };
let grid = "";
const step = (lo1-lo0) > 16 ? 4 : 2;
for(let lo = Math.ceil(lo0/step)*step; lo <= lo1; lo += step) grid += `${lo}°${lo<0?"W":"E"} `;
for(let la = Math.ceil(la0); la <= la1; la += 1) grid += `${la}°N `;
const badge = (x,y,n) => `${n} `;
let arcs = "", offmap = 0;
journeys.forEach((j,i) => {
const a = j.fromKey && where(j.fromKey), b = j.toKey && where(j.toKey), dash = j.status === "inferred" ? 'stroke-dasharray="5 5"' : "";
if(a && b){ if(Math.hypot(a[0]-b[0], a[1]-b[1]) < 6) return;
const bend = i % 2 ? -1 : 1, mx = (a[0]+b[0])/2 + bend*(b[1]-a[1])*.25, my = (a[1]+b[1])/2 - bend*(b[0]-a[0])*.25;
const rough = (GAZ[j.fromKey] && approx(GAZ[j.fromKey])) || (GAZ[j.toKey] && approx(GAZ[j.toKey])) ? 'stroke-dasharray="2 4"' : "";
arcs += ` ${badge((a[0]+2*mx+b[0])/4,(a[1]+2*my+b[1])/4,j.n)}`;
} else if(a && j.toKey && GAZ[j.toKey] && GAZ[j.toKey].lat != null){
// Destination outside the frame: point towards it and stop at the edge.
const g = GAZ[j.toKey], tx = X(g.lon), ty = Y(g.lat), x0 = 76, x1 = W-46, y0 = 46, y1 = Hh-46;
let t = 1; const dx = tx - a[0], dy = ty - a[1];
if(dx) t = Math.min(t, dx > 0 ? (x1 - a[0]) / dx : (x0 - a[0]) / dx);
if(dy) t = Math.min(t, dy > 0 ? (y1 - a[1]) / dy : (y0 - a[1]) / dy);
const ex = a[0] + dx * t, ey = a[1] + dy * t, right = ex > W / 2, below = ey > Hh / 2;
arcs += ` ${badge((a[0]+ex)/2,(a[1]+ey)/2,j.n)}
To ${esc(g.name)}${j.when ? ", " + esc(j.when) : ""} `;
}
});
// Labels: try four positions around each point and keep the first that does not overlap an earlier label.
const boxes = [], over = (a,b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
const dots = clusters.map(c => { const x = X(c.lon), y = Y(c.lat), on = c.keys.includes(sel), hollow = !c.keys.some(inJ);
const extra = c.names.slice(1), sub = extra.length ? (extra.length > 2 ? `${extra.slice(0,2).join(" · ")} +${extra.length-2}` : extra.join(" · ")) : hollow ? "mentioned" : "";
const w = Math.max(c.names[0].length * 7.6, sub.length * 6.4) + 6;
const opts = [[1,-1],[-1,-1],[1,1],[-1,1]].map(([sx,sy]) => { const x0 = sx > 0 ? x + 12 : x - 12 - w, ty = sy < 0 ? y - 10 : y + 20;
return {sx, ty, b: {x0, x1: x0 + w, y0: ty - 13, y1: ty + (sub ? 18 : 4)}}; });
const fits = o => o.b.x0 >= 2 && o.b.x1 <= W - 2 && o.b.y0 >= 2 && o.b.y1 <= Hh - 30 && !boxes.some(b => over(b, o.b));
const pick = opts.find(fits) || opts.find(o => o.b.x0 >= 2 && o.b.x1 <= W - 2) || opts[0];
boxes.push(pick.b);
const anc = pick.sx > 0 ? "start" : "end", lx = pick.sx > 0 ? x + 12 : x - 12;
const ring = c.exact ? "" : ` `;
return `${ring}
${esc(c.names[0])}
${sub ? `${esc(sub)} ` : ""} `; }).join("");
return `
${grid}${arcs}${dots}
Schematic, equirectangular. Coordinates approximate; dashed rings are places known only roughly.
${outside.length ? `Also mentioned, outside this view: ${esc(outside.join(", "))}.
` : ""}`;
}
function renderPlaces(sel){
const actChip = a => ({linked:"accent", confirmed:"good", relabelled:"flag", relinked:"bad", added:"flag", split:"flag", geocoded:"good", approximate:"flag", unplaced:"bad"}[a] || "");
const loc = (key, prec) => { const g = GAZ[key];
if(prec === "near") return `Approximate: near ${esc((GAZ[g && g.anchor] || {}).name || "")}
`;
if(prec === "country") return `Approximate: ${esc(g ? g.name : "")}, country only
`;
if(prec === "unnamed") return `Not named in the testimony
`;
if(prec === "uncertain" && g) return `${esc(g.name)}? Spelling uncertain: ${esc(g.note || "")}
`;
if(prec === "unplaced" || (key && !g)) return `Not found: needs a curator
`;
if(g && g.source === "geonames") return `${esc(g.name)}, GeoNames${g.ambiguous ? ", several towns share this name" : ""}
`;
return ""; };
const pc = D.placeCoverage;
const ms = D.mentions || [], js = G.journeys || [], rj = D.ruleJourneys || [];
const ev = j => j.quote ? `${esc(timeOf(j.segId))} "${esc(j.quote)}" ${j.grounded===false?' Rejected: quote not in transcript ':""}`
: `Inferred, no quote Needs review `;
$("#p-places").innerHTML = `
Journeys ${mapSVG(sel) || '
No mappable places.
'}
${pc ? `
${pc.journeys_drawn} of ${pc.journeys} journeys drawn (${pc.journeys_drawn_exact} with both ends placed exactly)${pc.journeys_not_drawn ? `; ${pc.journeys_not_drawn} not drawn, listed below${pc.journeys_not_drawn_unnamed != null ? ` (${pc.journeys_not_drawn_unnamed} because the testimony does not name the place, ${pc.journeys_not_drawn_not_found} because a named place was not found)` : ""}` : ""}. ${pc.mentions_placed} of ${pc.mentions} place mentions placed.
` : ""}
${js.length ? `
# From To When How Evidence
${js.map((j,i)=>`${i+1} ${esc(j.from)}${loc(j.fromKey, j.fromPrecision)} ${esc(j.to)}${loc(j.toKey, j.toPrecision)} ${esc(j.when)} ${esc(j.how)} ${ev(j)} `).join("")}
` : '
No journeys drafted.
'}
${rj.length ? `
Compare with the rule-based baseline (spatio-textual rule_dependency_v1, ${rj.length} candidates)
From To Transport Date Evidence
${rj.map(j=>`${esc(j.start_location||"–")} ${esc(j.end_location||"–")} ${esc(j.transport_mode||"–")} ${esc(j.date||"–")} ${esc(timeOf(j.segId))} ${esc(j.evidence_quote)} `).join("")}
` : ""}
Place mentions: spatio-textual output and review
${ms.length} mentions. The period gazetteer corrects historical names the NER model misses or mislabels, and records why; other places are placed with GeoNames, approximated, or marked for a curator.
Said At Resolved as Period name Raw model output Review
${ms.map(m=>{const g=GAZ[m.key]||{name:m.surface,kind:""}; return `${esc(m.surface)} ${esc(timeOf(m.segId))} ${esc(g.name)}${esc(g.kind)}
${esc(g.period||"–")}
${m.raw?esc(`${m.raw.text} · ${m.raw.label}${m.raw.resolution_status?" · "+m.raw.resolution_status:""}`):"not detected"}
${esc(m.action)} ${esc(m.reason)}
`}).join("")}
`;
}
/* ---------- headings review ---------- */
const stamp = () => new Date().toLocaleTimeString([], {hour:"2-digit", minute:"2-digit", second:"2-digit"});
function act(id, action, val){
const h = H.find(x => x.id === id); const before = h.value;
if(action === "edit"){ h.value = val; h.status = "Edited"; log.unshift(`${stamp()} · Edited "${before}" to "${val}"`); }
else { h.status = action === "accept" ? "Accepted" : "Rejected"; log.unshift(`${stamp()} · ${h.status} "${h.value}"`); }
renderHeadings();
}
function arfDraft(){
const ok = H.filter(h => h.status === "Accepted" || h.status === "Edited");
const disc = (G.claims || []).filter(c => c.verdict !== "supported");
return `# Acquisition Rationale Form: machine draft\n\nAccession: ${T.id}\nTitle: ${T.title}\nDuration: ${T.duration || "unknown"}\n\n## Summary\n${G.summary || ""}\n\n## Subject headings (curator-approved)\n${ok.map(h=>`- ${h.value} [${h.category}] evidence ${timeOf(h.segId)}: "${h.quote}"`).join("\n") || "- none approved yet"}\n\n## Donor-reported information: discrepancies\n${disc.map(c=>`- ${c.field}: donor "${c.donor}"; ${c.verdict}. ${c.note||""}`).join("\n") || "- none"}\n\n_Machine-drafted by CuratorBot. Fields are suggestions until a curator signs off._\n`;
}
function renderHeadings(){
const cats = ["Geographic","Chronological","Corporate","Topical","Form"];
const good = H.filter(h => h.ok), stopped = H.filter(h => !h.ok);
const n = s => good.filter(h => h.status === s).length;
const st = s => ({Accepted:"good",Edited:"accent",Rejected:"bad"}[s] || "");
const row = h => `${esc(h.value)}
${h.source === "rule" ? `Added by rule ${esc(h.rule || "")}` : ` confidence ${(h.confidence||0).toFixed(2)}`} · ${h.status}
${h.quote ? `
"${esc(h.quote)}" ${esc(timeOf(h.segId))}
` : ""}
Save Cancel
Accept Edit Reject
`;
$("#p-headings").innerHTML = `
${good.length ? cats.map(c => { const hs = good.filter(h => h.category === c); return hs.length ? `
${c} ${hs.map(row).join("")}
` : ""; }).join("") : '
No heading suggestions for this interview.
'}
${stopped.length ? `
Stopped by validators ${stopped.map(h=>`
${esc(h.heading)}
${h.in_vocabulary===false?"Not in the vocabulary. ":""}${h.grounded===false?"Quote not found in the transcript.":""}
"${esc(h.quote)}"
`).join("")}
` : ""}
Review progress
${n("Accepted")} accepted ${n("Edited")} edited ${n("Rejected")} rejected ${n("Unreviewed")} to review
Headings come only from a controlled vocabulary and each must quote the narrator. Form headings that cataloguers add by convention are proposed by rule and marked as such. Nothing reaches the catalogue until a curator accepts it.
Download ARF draft
Audit trail ${log.length?log.map(l=>`
${esc(l)}
`).join(""):'
Every decision is recorded here. Accept, edit or reject a heading to start.
'}
`;
document.querySelectorAll("[data-acc]").forEach(b => b.onclick = () => act(b.dataset.acc, "accept"));
document.querySelectorAll("[data-rej]").forEach(b => b.onclick = () => act(b.dataset.rej, "reject"));
document.querySelectorAll("[data-edit]").forEach(b => b.onclick = () => { $("#e-"+b.dataset.edit).hidden = false; $("#ei-"+b.dataset.edit).focus(); });
document.querySelectorAll("[data-cancel]").forEach(b => b.onclick = () => { $("#e-"+b.dataset.cancel).hidden = true; });
document.querySelectorAll("[data-save]").forEach(b => b.onclick = () => { const v = $("#ei-"+b.dataset.save).value.trim(); if(v) act(b.dataset.save, "edit", v); });
$("#arf").onclick = () => { const blob = new Blob([arfDraft()], {type:"text/markdown"}); const a = document.createElement("a");
a.href = URL.createObjectURL(blob); a.download = `ARF-draft-${T.id}.md`; document.body.appendChild(a); a.click(); a.remove(); };
}
/* ---------- donor check ---------- */
function renderDonor(){
const cl = G.claims || [];
const vc = v => ({supported:"good", contradicted:"bad", incomplete:"flag"}[v] || "");
const n = v => cl.filter(c => c.verdict === v).length;
$("#p-donor").innerHTML = cl.length ? `
${n("supported")} supported ${n("contradicted")} contradicted ${n("incomplete")} incomplete ${n("not_mentioned")} not mentioned
Each field the donor reported is treated as a claim and checked against the recording.
Field Donor says Verdict Evidence in the interview
${cl.map(c=>`${esc(c.field)} ${esc(c.donor)} ${esc(c.verdict.replace("_"," "))}
${c.quote?`${esc(timeOf(c.segId))} "${esc(c.quote)}" ${c.grounded===false?' Rejected: quote not in transcript ':""}`:""}${c.note?`${esc(c.note)}
`:""} `).join("")}
`
: `No donor-reported details were supplied for this interview.
`;
}
/* ---------- how it works ---------- */
function renderHood(){
const r = D.run || {}, lat = (D.annotations || []).reduce((a,x) => a + (x.latency_ms || 0), 0);
const L = r.llm, secs = L ? `${(L.latency_ms/1000).toFixed(1)} s` : "";
const llm = L ? (L.fallback_from ? `Fallback model, ${secs}` : secs) : "Precomputed or not run";
const llmDetail = L ? `Model: ${L.model} via ${L.provider}.${L.fallback_from ? ` ${L.fallback_from} failed, so the fallback model answered.` : ""} ${Number(L.input_tokens||0).toLocaleString()} tokens in, ${Number(L.output_tokens||0).toLocaleString()} out.` : "";
const steps = [
["Media preparation and language ID","Parts grouped and checked, audio extracted, languages detected per segment.", G.media?.simulated ? "Simulated" : (G.media ? "Run offline" : "Not run: transcript supplied"), G.media && !G.media.simulated ? "good" : "flag"],
["Transcription with speaker roles","faster-whisper; interviewer and narrator separated.", G.media && !G.media.simulated ? "Run offline" : "Transcript supplied", G.media && !G.media.simulated ? "good" : "flag"],
["Spatial annotation", `${r.library || "spatio-textual"} with ${r.ner || "spaCy"}.`, `${(D.annotations||[]).length} answers in ${lat.toFixed(0)} ms`, "good"],
["Journey baseline","spatio-textual rule_dependency_v1 with evidence spans.", `${(D.ruleJourneys||[]).length} candidates`, "good"],
["Places","Period gazetteer for historical names, then GeoNames for towns; the rest approximated or listed for review.", D.placeCoverage ? `${D.placeCoverage.journeys_drawn} of ${D.placeCoverage.journeys} journeys drawn` : `${(D.mentions||[]).length} mentions reviewed`, "accent",
D.placeCoverage ? `${D.placeCoverage.mentions_placed} of ${D.placeCoverage.mentions} place mentions placed.` : ""],
["Agent draft","Brief, chapters, headings, journeys, donor checks.", llm, L && L.fallback_from ? "flag" : "accent", llmDetail],
["Validators","Quotes must appear in the transcript; headings must be in the vocabulary.", G.validation ? `${G.validation.verified} verified, ${G.validation.rejected} stopped` : "All quotes checked when built", "good",
G.validation && G.validation.out_of_vocabulary !== undefined ? `Stopped: ${G.validation.quotes_rejected} ${G.validation.quotes_rejected===1?"quote":"quotes"} not found in the transcript, ${G.validation.out_of_vocabulary} ${G.validation.out_of_vocabulary===1?"heading":"headings"} outside the vocabulary.` : ""],
["Curator review","Accept, edit or reject with an audit trail; ARF draft from approved items.", "In this page", "good"]];
$("#p-hood").innerHTML = `Pipeline for this interview ${steps.map((s,i)=>`
${i+1} ${s[0]} ${esc(s[1])}
${s[4]?`
${esc(s[4])}
`:""}
${esc(s[2])} `).join("")}
Built ${esc(r.created || "")}${r.curatorbot?` with CuratorBot ${esc(r.curatorbot)}`:""}.
Principles
Curators decide. CuratorBot drafts and flags; it never accepts, declines or catalogues.
Evidence or nothing. Every claim links to a moment in the interview.
Closed vocabularies. Headings come from authority lists, never free text.
Language equity. Poor transcription raises a listening flag and never lowers priority.
`;
}
/* ---------- live analysis ---------- */
function setupLive(){
const info = $("#liveinfo");
if(!HEALTH.live){ $("#run").disabled = true; info.textContent = "Live analysis is switched off on this server. The interviews above are precomputed."; }
else info.textContent = `Model: ${HEALTH.model}. Limit ${Number(HEALTH.max_chars).toLocaleString()} characters. One analysis runs at a time.`;
$("#passWrap").hidden = !HEALTH.passcode;
$("#audioBtn").hidden = !HEALTH.asr;
}
$("#tx").oninput = () => { $("#txcount").textContent = `${$("#tx").value.length.toLocaleString()} characters`; };
$("#loadDemo").onclick = async () => {
try{ const b = await api("/api/interviews/DEMO-0001");
$("#tx").value = b.testimony.segments.map(s => `[${s.start}] ${s.role}: ${s.text}${s.translation?` (Translation: ${s.translation})`:""}`).join("\n");
const d = b.testimony.donor || {}; $("#d-birth").value = d.birth||""; $("#d-lang").value = d.languages||""; $("#d-war").value = d.wartime||""; $("#d-post").value = d.postwar||"";
$("#tx").oninput(); }catch(e){ $("#runstate").innerHTML = `${esc(e.message)} `; }
};
$("#audio").onchange = async e => {
const f = e.target.files[0]; if(!f) return; const st = $("#runstate");
st.innerHTML = ` Transcribing ${esc(f.name)}. Short clips take a minute or two on this server.`;
const fd = new FormData(); fd.append("file", f);
try{ const r = await api("/api/transcribe", {method:"POST", body:fd, headers:{"X-Demo-Passcode": $("#pass").value}});
$("#tx").value = r.text; $("#tx").oninput(); st.textContent = `Transcribed (${r.language}). Check speaker roles, then press Analyse.`; }
catch(err){ st.innerHTML = `${esc(err.message)} `; }
e.target.value = "";
};
$("#run").onclick = async () => {
const txt = $("#tx").value.trim(), st = $("#runstate");
if(!txt){ st.innerHTML = 'Paste a transcript or load the synthetic one first. '; return; }
const donor = {birth:$("#d-birth").value.trim(), languages:$("#d-lang").value.trim(), wartime:$("#d-war").value.trim(), postwar:$("#d-post").value.trim()};
const t0 = Date.now(); $("#run").disabled = true;
const tick = setInterval(() => { st.innerHTML = ` Analysing · ${Math.round((Date.now()-t0)/1000)} s`; }, 500);
try{
liveBrief = await api("/api/analyse", {method:"POST", headers:{"Content-Type":"application/json","X-Demo-Passcode":$("#pass").value},
body: JSON.stringify({transcript: txt, donor, title: "Live analysis"})});
const pick = $("#pick"); if(!pick.querySelector(`option[value="${LIVE_ID}"]`)) pick.insertAdjacentHTML("afterbegin", `Live analysis (not saved) `);
pick.value = LIVE_ID; currentTab = "brief"; load(liveBrief); setMode("demo"); st.textContent = "Done.";
}catch(e){ st.innerHTML = `${esc(e.message)} `; }
finally{ clearInterval(tick); $("#run").disabled = !HEALTH.live; }
};
boot();