Spaces:
Running
Running
Download app/static/app.js from ignatius/curatorbot: direct link, hf CLI and curl.
- Browser
- Download file 43.5 kB
-
https://huggingface.co/spaces/ignatius/curatorbot/resolve/main/app/static/app.js
- Command line
-
hf download hf://spaces/ignatius/curatorbot/app/static/app.js
-
curl -L -o app.js https://huggingface.co/spaces/ignatius/curatorbot/resolve/main/app/static/app.js
43.5 kB
| /* CuratorBot viewer: renders any brief produced by curatorbot.pipeline.build_brief. */ | |
| ; | |
| 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 => `<option value="${esc(i.id)}">${esc(i.title)}</option>`).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 ? `<b>About this interview.</b> ${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 ? `<span class="chip ${bad?"bad":"good"}">${bad} donor discrepanc${bad===1?"y":"ies"}</span>` : "", | |
| G.media?.flags?.length ? `<span class="chip flag">${G.media.flags.length} listening flag${G.media.flags.length===1?"":"s"}</span>` : "", | |
| G.gap ? `<span class="chip accent">Collection gap: ${esc(G.gap.band)}</span>` : "", | |
| `<span class="chip">${H.filter(h=>h.ok).length} heading suggestions</span>`, | |
| `<span class="chip">${ms.length} place mentions, ${fixed} corrected</span>`, | |
| rej ? `<span class="chip bad">${rej} stopped by validators</span>` : ""].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 `<span class="chip ${cls}">${label}</span>`; } | |
| 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 = [`<span class="chip">${LIST.length} interview${LIST.length===1?"":"s"}</span>`, | |
| `<span class="chip flag">${LIST.filter(r=>r.status==="under_review").length} under review</span>`, | |
| `<span class="chip good">${LIST.filter(r=>r.status==="released").length} released</span>`, | |
| mean != null ? `<span class="chip accent">Catalogue headings found: ${pct(mean)} on average</span>` : ""].join(""); | |
| $("#qlist").innerHTML = groups.map(([s, label]) => { const rows = LIST.filter(r => r.status === s); if(!rows.length) return ""; | |
| return `<div class="qgroup"><span class="label">${label}</span>${rows.map(r => `<div class="panel qrow"> | |
| <div style="min-width:0"><h2>${esc(r.title)}</h2> | |
| <div class="qmeta">${statusChip(r.status)}${r.duration?`<span class="chip">${esc(r.duration)}</span>`:""}${(r.languages||[]).length?`<span class="chip">${esc(r.languages.join(", "))}</span>`:""} | |
| ${r.gap?`<span class="chip accent">Gap: ${esc(r.gap)}</span>`:""} | |
| ${r.claims?`<span class="chip ${r.discrepancies?"bad":"good"}">${r.discrepancies} donor discrepanc${r.discrepancies===1?"y":"ies"}</span>`:""} | |
| ${r.flags?`<span class="chip flag">${r.flags} listening flag${r.flags===1?"":"s"}</span>`:""} | |
| <span class="chip">${r.headings} headings</span><span class="chip">${r.places} place mentions</span> | |
| ${r.backtest && r.status === "released"?`<span class="chip good">${pct(r.backtest.recall_head)} of ${r.backtest.catalogued} catalogue headings found</span>`:""}</div> | |
| ${r.summary?`<p class="qsum">${esc(r.summary)}${r.summary.length>=280?"…":""}</p>`:""}</div> | |
| <div class="btns"><button class="btn primary" data-open="${esc(r.id)}">Open brief</button></div></div>`).join("")}</div>`; }).join("") | |
| || '<div class="panel"><p class="muted">No interviews prepared yet.</p></div>'; | |
| 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="") => `<li><span>${esc(h)}</span>${chip}${extra}</li>`; | |
| const ev = h => { const e = (b.extra_evidence||{})[h]; return e && e.quote ? ` <button class="tlink" data-seg="${esc(e.segId)}" data-q="${esc(e.quote)}">${esc(timeOf(e.segId))}</button> <span class="quote" style="font-size:14px">"${esc(e.quote)}"</span>` : ""; }; | |
| $("#p-catalogue").innerHTML = `<div class="grid2"><div class="stack"> | |
| <div class="panel stack"><span class="label">How CuratorBot compares with the catalogue</span> | |
| <div class="figs"><div class="fig"><b>${pct(b.recall_head)}</b><span>catalogue headings found, by main heading</span></div> | |
| <div class="fig"><b>${pct(b.recall_exact)}</b><span>found exactly, with subdivisions</span></div> | |
| <div class="fig"><b>${pct(b.recall_within_vocabulary)}</b><span>found, counting only headings in CuratorBot's vocabulary</span></div> | |
| ${b.with_rules ? `<div class="fig"><b>${pct(b.with_rules.recall_exact)}</b><span>found exactly, adding the form headings proposed by rule</span></div>` : ""}</div> | |
| <p class="muted small">${b.catalogued} headings in the catalogue record; CuratorBot's top ${b.suggested} suggestions compared.${b.catalogue_url?` <a href="${esc(b.catalogue_url)}" target="_blank" rel="noopener">Open the catalogue record</a>.`:""}</p></div> | |
| <div class="panel"><span class="label">Catalogue headings</span><ul class="hlist"> | |
| ${(b.matched||[]).map(h => li(h, '<span class="chip good">Found exactly</span>')).join("")} | |
| ${(b.matched_head_only||[]).map(h => li(h, '<span class="chip accent">Main heading found</span>')).join("")} | |
| ${(b.missed||[]).map(h => li(h, '<span class="chip bad">Missed</span>', outside.has(h) ? ' <span class="muted small">not in the vocabulary yet</span>' : "")).join("")} | |
| </ul></div></div> | |
| <div class="stack"><div class="panel"><span class="label">Suggested but not in the catalogue</span> | |
| <p class="muted small" style="margin:6px 0">Not necessarily wrong: a curator decides whether each adds something the record lacks.</p> | |
| <ul class="hlist">${(b.extra||[]).map(h => li(h, "", ev(h))).join("") || '<li class="muted">None.</li>'}</ul></div> | |
| <div class="panel"><p class="muted small">"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.</p></div></div></div>`; | |
| } | |
| /* ---------- 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 `<li><button class="tlink" data-seg="${s?s.segId:""}">${esc(c.start || (s&&s.start) || "")}</button><span>${esc(c.title)}</span></li>`; }).join(""); | |
| const total = t2s(T.duration) || 1; | |
| const L = G.media?.languages; | |
| const langPanel = L && L.length ? `<div class="panel"><span class="label">Languages</span> | |
| <div class="langbar" role="img" aria-label="${esc(L.map(l=>`${l.lang} ${l.from} to ${l.to}`).join("; "))}">${L.map(l=>`<span style="width:${Math.max(.8,(t2s(l.to)-t2s(l.from))/total*100)}%;background:${l.code==="en"?"var(--accent)":"var(--flag)"}"></span>`).join("")}</div> | |
| <div class="legend">${[...new Map(L.map(l=>[l.lang,l])).values()].map(l=>`<span><i class="sw" style="background:${l.code==="en"?"var(--accent)":"var(--flag)"}"></i>${esc(l.lang)}${l.code!=="en"?`, ${l.from} to ${l.to}`:""}</span>`).join("")}</div></div>` | |
| : (G.languages && G.languages.length ? `<div class="panel"><span class="label">Languages</span><p style="margin-top:6px">${esc(G.languages.join(", "))}</p></div>` : ""); | |
| const gap = G.gap ? `<div class="panel stack"><span class="label">Collection gap</span><h2>${esc(G.gap.band)} priority</h2> | |
| <div>${G.gap.reasons.map(r=>`<div class="frow" style="grid-template-columns:1fr auto"><span>${esc(r.text)}</span><span class="chip ${r.level==="less common"?"accent":""}">${esc(r.level)}</span></div>`).join("")}</div> | |
| <p class="muted small">${esc(G.gap.note||"")}</p></div>` | |
| : `<div class="panel stack"><span class="label">Collection gap</span><p class="muted small">Needs the collection profile built from the catalogue export. Not available for this interview yet.</p></div>`; | |
| const flags = G.media?.flags?.length ? `<div class="panel"><span class="label">Needs human listening</span>${G.media.flags.map(f=>{const s=segAt(f.at);return `<div class="frow"><button class="tlink" data-seg="${s.segId}">${esc(f.at)}</button><span>${esc(f.text)}</span></div>`}).join("")}</div>` : ""; | |
| const parts = G.media?.parts?.length ? `<div class="panel"><span class="label">Media${G.media.simulated?" (simulated)":""}</span><div class="tablewrap"><table><tr><th>Part</th><th>Length</th><th>Audio</th></tr>${G.media.parts.map(p=>`<tr><td class="mono">${esc(p.part)}</td><td class="mono">${esc(p.duration)}</td><td>${esc(p.audio||p.audio_codec||"")}</td></tr>`).join("")}</table></div></div>` : ""; | |
| $("#p-brief").innerHTML = `<div class="grid2"><div class="stack"> | |
| <div class="panel stack"><span class="label">Summary</span><p class="summary">${esc(G.summary || "No summary: the agent step did not run for this interview.")}</p></div> | |
| ${chapters ? `<div class="panel stack"><span class="label">Chapters</span><ul class="chapters">${chapters}</ul></div>` : ""} | |
| </div><div class="stack">${gap}${langPanel}${flags}${parts}</div></div>`; | |
| } | |
| /* ---------- 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) + "<mark>" + plain + "</mark>" + html.slice(k+plain.length) : `<mark>${html}</mark>`; } | |
| 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 += `<button class="pl${fix?" fix":""}" data-place="${esc(m.key)}" title="${esc(g.name)}${g.period?" · "+esc(g.period):""} · ${esc(m.action)}">${esc(text.slice(m.start,m.end))}</button>`; 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 = `<div class="tools"> | |
| <input type="search" id="tq" placeholder="Search the transcript" value="${esc(tQuery)}" aria-label="Search the transcript"> | |
| <div class="seg" style="margin-left:0" role="group" aria-label="Speakers"><button data-f="all" aria-pressed="${tFilter==="all"}">All turns</button><button data-f="A" aria-pressed="${tFilter==="A"}">Narrator only</button></div> | |
| <span class="legend muted"><span><i class="sw" style="background:var(--accent)"></i>Place, linked</span><span><i class="sw" style="background:var(--flag)"></i>Place, corrected in review</span></span></div> | |
| <div class="panel" style="padding-top:6px">${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 ? `<div class="tr"><b>Machine translation:</b> ${markText(s.segId, s.translation, fq && s.translation.includes(fq) ? fq : "")}</div>` : ""; | |
| return `<div class="turn ${s.role==="Q"?"q":""}" id="t-${esc(s.segId)}"><span class="mono muted small">${esc(s.start||"")}</span><span class="role">${s.role==="Q"?"INT":"NAR"}</span><div class="txt">${main}${tr}</div></div>`; }).join("") | |
| || `<p class="muted" style="padding:16px 0">No turns match "${esc(tQuery)}".</p>`}</div>`; | |
| 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 += `<line x1="${X(lo)}" x2="${X(lo)}" y1="40" y2="${Hh-40}" stroke="var(--line)"/><text x="${X(lo)}" y="${Hh-22}" text-anchor="middle" font-size="11" fill="var(--muted)">${lo}°${lo<0?"W":"E"}</text>`; | |
| for(let la = Math.ceil(la0); la <= la1; la += 1) grid += `<line x1="70" x2="${W-40}" y1="${Y(la)}" y2="${Y(la)}" stroke="var(--line)"/><text x="62" y="${Y(la)+4}" text-anchor="end" font-size="11" fill="var(--muted)">${la}°N</text>`; | |
| const badge = (x,y,n) => `<circle cx="${x}" cy="${y}" r="11" fill="var(--panel)" stroke="var(--accent)"/><text x="${x}" y="${y+4}" text-anchor="middle" font-size="12" font-weight="600" fill="var(--accent)">${n}</text>`; | |
| 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 += `<path d="M${a[0]} ${a[1]} Q${mx} ${my} ${b[0]} ${b[1]}" fill="none" stroke="var(--accent)" stroke-width="2" ${dash || rough} marker-end="url(#ah)"/>${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 += `<path d="M${a[0]} ${a[1]} L${ex} ${ey}" fill="none" stroke="var(--accent)" stroke-width="2" ${approx(g) ? 'stroke-dasharray="2 4"' : ""} marker-end="url(#ah)"/>${badge((a[0]+ex)/2,(a[1]+ey)/2,j.n)} | |
| <text x="${right ? ex - 6 : ex + 6}" y="${below ? ey - 12 - 16 * offmap++ : ey + 22 + 16 * offmap++}" text-anchor="${right ? "end" : "start"}" font-size="12.5" font-weight="600" fill="var(--ink)" paint-order="stroke" stroke="var(--panel)" stroke-width="3">To ${esc(g.name)}${j.when ? ", " + esc(j.when) : ""}</text>`; | |
| } | |
| }); | |
| // 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 ? "" : `<circle cx="${x}" cy="${y}" r="15" fill="none" stroke="var(--muted)" stroke-dasharray="3 3"/>`; | |
| return `<g>${ring}<circle cx="${x}" cy="${y}" r="${on?8:6}" fill="${hollow?"var(--panel)":"var(--ink)"}" stroke="var(--ink)" stroke-width="${on?3:1.5}"/> | |
| <text x="${lx}" y="${pick.ty}" text-anchor="${anc}" font-size="13" font-weight="600" fill="var(--ink)" paint-order="stroke" stroke="var(--panel)" stroke-width="3">${esc(c.names[0])}</text> | |
| ${sub ? `<text x="${lx}" y="${pick.ty+15}" text-anchor="${anc}" font-size="11.5" fill="var(--muted)" paint-order="stroke" stroke="var(--panel)" stroke-width="3">${esc(sub)}</text>` : ""}</g>`; }).join(""); | |
| return `<svg viewBox="0 0 ${W} ${Hh}" width="100%" style="min-width:560px;max-width:100%" role="img" aria-label="Schematic map of places and journeys in this interview"> | |
| <defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="var(--accent)"/></marker></defs> | |
| <rect width="${W}" height="${Hh}" fill="var(--panel)"/>${grid}${arcs}${dots} | |
| <text x="${W-40}" y="${Hh-6}" text-anchor="end" font-size="11" fill="var(--muted)">Schematic, equirectangular. Coordinates approximate; dashed rings are places known only roughly.</text></svg> | |
| ${outside.length ? `<p class="muted small" style="margin:6px 0 0">Also mentioned, outside this view: ${esc(outside.join(", "))}.</p>` : ""}`; | |
| } | |
| 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 `<div class="muted act">Approximate: near ${esc((GAZ[g && g.anchor] || {}).name || "")}</div>`; | |
| if(prec === "country") return `<div class="muted act">Approximate: ${esc(g ? g.name : "")}, country only</div>`; | |
| if(prec === "unnamed") return `<div class="muted act">Not named in the testimony</div>`; | |
| if(prec === "uncertain" && g) return `<div class="act" style="color:var(--flag)">${esc(g.name)}? Spelling uncertain: ${esc(g.note || "")}</div>`; | |
| if(prec === "unplaced" || (key && !g)) return `<div class="act" style="color:var(--bad)">Not found: needs a curator</div>`; | |
| if(g && g.source === "geonames") return `<div class="muted act">${esc(g.name)}, GeoNames${g.ambiguous ? ", several towns share this name" : ""}</div>`; | |
| return ""; }; | |
| const pc = D.placeCoverage; | |
| const ms = D.mentions || [], js = G.journeys || [], rj = D.ruleJourneys || []; | |
| const ev = j => j.quote ? `<button class="tlink" data-seg="${esc(j.segId)}" data-q="${esc(j.quote)}">${esc(timeOf(j.segId))}</button> <span class="quote" style="font-size:14px">"${esc(j.quote)}"</span>${j.grounded===false?' <span class="chip bad">Rejected: quote not in transcript</span>':""}` | |
| : `<span class="chip flag">Inferred, no quote</span> <span class="muted">Needs review</span>`; | |
| $("#p-places").innerHTML = `<div class="stack"> | |
| <div class="panel stack"><span class="label">Journeys</span><div class="mapbox">${mapSVG(sel) || '<p class="muted">No mappable places.</p>'}</div> | |
| ${pc ? `<p class="muted small">${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.</p>` : ""} | |
| ${js.length ? `<div class="tablewrap"><table><tr><th>#</th><th>From</th><th>To</th><th>When</th><th>How</th><th>Evidence</th></tr> | |
| ${js.map((j,i)=>`<tr><td class="mono">${i+1}</td><td>${esc(j.from)}${loc(j.fromKey, j.fromPrecision)}</td><td>${esc(j.to)}${loc(j.toKey, j.toPrecision)}</td><td>${esc(j.when)}</td><td>${esc(j.how)}</td><td>${ev(j)}</td></tr>`).join("")}</table></div>` : '<p class="muted">No journeys drafted.</p>'} | |
| ${rj.length ? `<details><summary class="muted" style="cursor:pointer">Compare with the rule-based baseline (spatio-textual rule_dependency_v1, ${rj.length} candidates)</summary> | |
| <div class="tablewrap" style="margin-top:10px"><table><tr><th>From</th><th>To</th><th>Transport</th><th>Date</th><th>Evidence</th></tr> | |
| ${rj.map(j=>`<tr><td>${esc(j.start_location||"–")}</td><td>${esc(j.end_location||"–")}</td><td>${esc(j.transport_mode||"–")}</td><td>${esc(j.date||"–")}</td><td><button class="tlink" data-seg="${esc(j.segId)}" data-q="${esc(j.evidence_quote)}">${esc(timeOf(j.segId))}</button> ${esc(j.evidence_quote)}</td></tr>`).join("")}</table></div></details>` : ""} | |
| </div> | |
| <div class="panel stack"><span class="label">Place mentions: spatio-textual output and review</span> | |
| <p class="muted small">${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.</p> | |
| <div class="tablewrap"><table><tr><th>Said</th><th>At</th><th>Resolved as</th><th>Period name</th><th>Raw model output</th><th>Review</th></tr> | |
| ${ms.map(m=>{const g=GAZ[m.key]||{name:m.surface,kind:""}; return `<tr ${sel===m.key?'style="background:var(--accent-soft)"':""}><td>${esc(m.surface)}</td><td><button class="tlink" data-seg="${esc(m.segId)}">${esc(timeOf(m.segId))}</button></td><td>${esc(g.name)}<div class="muted act">${esc(g.kind)}</div></td><td>${esc(g.period||"–")}</td> | |
| <td class="mono act">${m.raw?esc(`${m.raw.text} · ${m.raw.label}${m.raw.resolution_status?" · "+m.raw.resolution_status:""}`):"not detected"}</td> | |
| <td><span class="chip ${actChip(m.action)}">${esc(m.action)}</span><div class="muted act">${esc(m.reason)}</div></td></tr>`}).join("")}</table></div></div></div>`; | |
| } | |
| /* ---------- 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 => `<div class="hrow" id="${h.id}"><div style="min-width:0"><div class="hname" style="${h.status==="Rejected"?"text-decoration:line-through;color:var(--muted)":""}">${esc(h.value)}</div> | |
| <div class="muted" style="font-size:12.5px;margin-top:4px">${h.source === "rule" ? `<span class="chip">Added by rule</span> ${esc(h.rule || "")}` : `<span class="conf"><i style="width:${Math.round((h.confidence||0)*100)}%"></i></span>confidence ${(h.confidence||0).toFixed(2)}`} · <span class="chip ${st(h.status)}">${h.status}</span></div> | |
| ${h.quote ? `<div class="quote">"${esc(h.quote)}" <button class="tlink" data-seg="${esc(h.segId)}" data-q="${esc(h.quote)}">${esc(timeOf(h.segId))}</button></div>` : ""} | |
| <div class="editbox" id="e-${h.id}" hidden><input type="text" id="ei-${h.id}" value="${esc(h.value)}" aria-label="Edit heading"><button class="btn primary" data-save="${h.id}">Save</button><button class="btn" data-cancel="${h.id}">Cancel</button></div></div> | |
| <div class="btns"><button class="btn" data-acc="${h.id}">Accept</button><button class="btn" data-edit="${h.id}">Edit</button><button class="btn" data-rej="${h.id}">Reject</button></div></div>`; | |
| $("#p-headings").innerHTML = `<div class="grid2"><div class="panel"> | |
| ${good.length ? cats.map(c => { const hs = good.filter(h => h.category === c); return hs.length ? `<div style="margin-top:6px"><span class="label">${c}</span>${hs.map(row).join("")}</div>` : ""; }).join("") : '<p class="muted">No heading suggestions for this interview.</p>'} | |
| ${stopped.length ? `<div style="margin-top:18px"><span class="label">Stopped by validators</span>${stopped.map(h=>`<div class="hrow"><div><div class="hname" style="text-decoration:line-through;color:var(--muted)">${esc(h.heading)}</div><div class="small muted">${h.in_vocabulary===false?"Not in the vocabulary. ":""}${h.grounded===false?"Quote not found in the transcript.":""}</div><div class="quote">"${esc(h.quote)}"</div></div></div>`).join("")}</div>` : ""} | |
| </div><div class="stack"> | |
| <div class="panel stack"><span class="label">Review progress</span> | |
| <div class="chips"><span class="chip good">${n("Accepted")} accepted</span><span class="chip accent">${n("Edited")} edited</span><span class="chip bad">${n("Rejected")} rejected</span><span class="chip">${n("Unreviewed")} to review</span></div> | |
| <p class="muted small">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.</p> | |
| <div class="btns" style="justify-content:start"><button class="btn primary" id="arf">Download ARF draft</button></div></div> | |
| <div class="panel stack"><span class="label">Audit trail</span><div class="log">${log.length?log.map(l=>`<div>${esc(l)}</div>`).join(""):'<p class="muted">Every decision is recorded here. Accept, edit or reject a heading to start.</p>'}</div></div> | |
| </div></div>`; | |
| 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 ? `<div class="panel stack"> | |
| <div class="chips"><span class="chip good">${n("supported")} supported</span><span class="chip bad">${n("contradicted")} contradicted</span><span class="chip flag">${n("incomplete")} incomplete</span><span class="chip">${n("not_mentioned")} not mentioned</span></div> | |
| <p class="muted small">Each field the donor reported is treated as a claim and checked against the recording.</p> | |
| <div class="tablewrap"><table><tr><th>Field</th><th>Donor says</th><th>Verdict</th><th>Evidence in the interview</th></tr> | |
| ${cl.map(c=>`<tr><td><b>${esc(c.field)}</b></td><td>${esc(c.donor)}</td><td><span class="chip ${vc(c.verdict)}">${esc(c.verdict.replace("_"," "))}</span></td> | |
| <td>${c.quote?`<button class="tlink" data-seg="${esc(c.segId)}" data-q="${esc(c.quote)}">${esc(timeOf(c.segId))}</button> <span class="quote" style="font-size:14.5px">"${esc(c.quote)}"</span>${c.grounded===false?' <span class="chip bad">Rejected: quote not in transcript</span>':""}`:""}${c.note?`<div class="muted small" style="margin-top:4px">${esc(c.note)}</div>`:""}</td></tr>`).join("")}</table></div></div>` | |
| : `<div class="panel"><p class="muted">No donor-reported details were supplied for this interview.</p></div>`; | |
| } | |
| /* ---------- 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 = `<div class="grid2"><div class="panel"><span class="label">Pipeline for this interview</span>${steps.map((s,i)=>`<div class="step"><span class="n">${i+1}</span><div><b>${s[0]}</b><div class="muted small">${esc(s[1])}</div>${s[4]?`<div class="muted small mono-detail">${esc(s[4])}</div>`:""}</div><span class="chip ${s[3]}">${esc(s[2])}</span></div>`).join("")} | |
| <p class="muted small" style="margin-top:10px">Built ${esc(r.created || "")}${r.curatorbot?` with CuratorBot ${esc(r.curatorbot)}`:""}.</p></div> | |
| <div class="stack"><div class="panel stack"><span class="label">Principles</span> | |
| <p><b>Curators decide.</b> CuratorBot drafts and flags; it never accepts, declines or catalogues.</p> | |
| <p><b>Evidence or nothing.</b> Every claim links to a moment in the interview.</p> | |
| <p><b>Closed vocabularies.</b> Headings come from authority lists, never free text.</p> | |
| <p><b>Language equity.</b> Poor transcription raises a listening flag and never lowers priority.</p></div></div></div>`; | |
| } | |
| /* ---------- 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 = `<span class="err">${esc(e.message)}</span>`; } | |
| }; | |
| $("#audio").onchange = async e => { | |
| const f = e.target.files[0]; if(!f) return; const st = $("#runstate"); | |
| st.innerHTML = `<span class="spin"></span> 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 = `<span class="err">${esc(err.message)}</span>`; } | |
| e.target.value = ""; | |
| }; | |
| $("#run").onclick = async () => { | |
| const txt = $("#tx").value.trim(), st = $("#runstate"); | |
| if(!txt){ st.innerHTML = '<span class="err">Paste a transcript or load the synthetic one first.</span>'; 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 = `<span class="spin"></span> 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", `<option value="${LIVE_ID}">Live analysis (not saved)</option>`); | |
| pick.value = LIVE_ID; currentTab = "brief"; load(liveBrief); setMode("demo"); st.textContent = "Done."; | |
| }catch(e){ st.innerHTML = `<span class="err">${esc(e.message)}</span>`; } | |
| finally{ clearInterval(tick); $("#run").disabled = !HEALTH.live; } | |
| }; | |
| boot(); | |