Add explanatory comments across codebase

This commit is contained in:
Stefano Zini
2026-11-04 14:23:18 +01:00
parent b8aa5548a2
commit 82b72b6c28
34 changed files with 934 additions and 0 deletions
+15
View File
@@ -1,29 +1,44 @@
<!doctype html><meta charset=utf-8><title>Meetings</title>
<!-- Local Web UI for recorded Teams meetings; ui.js renders and drives everything. -->
<link rel=stylesheet href=/ui.css>
<!-- Header: title, omp login status (omps) and queue summary (qs), both filled by tick() in ui.js. -->
<main><header><div><h1>Riunioni</h1><div class=hs><span id=omps title="login: menu Pinokio → Cloud login"></span><span id=qs></span></div></div>
<!-- Header actions: settings popover and upload. -->
<div class=ha>
<!-- Settings popover: skip-screenshots switch and LLM model pickers (wired by setSkip / setLlm in ui.js). -->
<details class=cfg><summary title="impostazioni di elaborazione">⚙ Impostazioni</summary><div class=pop>
<label class=sw title="non legge le schermate condivise: elaborazione molto più veloce, report solo dal parlato"><input type=checkbox id=skp onchange=setSkip()><i></i><span><b>Salta schermate</b><small>più veloce, report solo dal parlato</small></span></label>
<label class=fl>Modello schermate<select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select></label>
<label class=fl>Modello report<select id=llmr title="modello per il report" onchange=setLlm()></select></label></div></details>
<!-- Upload button; the hidden file input below does the picking. -->
<button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<!-- Hidden file input used by pick(). -->
<input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header>
<!-- Bulk-action bar, shown only when recordings are checked (upd() in ui.js). -->
<div class=card id=bulk hidden><b id=bn></b><a onclick=selAll(1)>tutte</a><a onclick=selAll(0)>nessuna</a><span class=sep></span>
<button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci</button>
<select id=bf title="step da cui rielaborare"><option>audio<option>transcribe<option>diarize<option>speakers<option>shots<option>docs<option>report<option>memory<option>render</select><button onclick=bulkRun() title="rielabora le registrazioni spuntate dallo step scelto">Rielabora da qui</button>
<button class=del onclick=bulkDrop() title="elimina solo i file video, report e trascrizione restano">Elimina video</button>
<button class=del onclick=bulkDel()>Elimina tutto</button></div>
<!-- Drag-and-drop hint; ui.js also accepts drops anywhere on the page. -->
<div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div>
<!-- Upload progress card (send() in ui.js). -->
<div class="card" id=ub hidden><div class=pg style="margin:0;border:0;padding:0;background:none"><div class=pgh><span><span class=big id=ubig>0%</span> &nbsp;<b id=utitle></b></span><button id=ucancel>annulla</button></div>
<div class=bar><i id=ubar></i></div><div class=sub><span id=utxt></span></div></div></div>
<!-- Search over speech and screen text, plus Q&A over the meetings. -->
<div class=card><div class=row><input id=q placeholder="Cerca nel parlato e sullo schermo"><button onclick=srch()>Cerca</button></div>
<div id=sr></div><div class=row><input id=qa placeholder="Chiedi alle riunioni"><select id=llma title="modello per le risposte (stesso del report)" onchange="llmr.value=llma.value;setLlm()"></select><button class=pri id=ab onclick=ask()>Chiedi</button></div><div id=ar></div></div>
<!-- Meetings table: rendered by tick() in ui.js. -->
<div class="card t"><table id=t></table></div></main>
<!-- Preview and crop dialog (play() in ui.js). -->
<dialog id=cdlg><div class=pgh><b id=ctitle></b><button onclick=cclose()>✕ chiudi</button></div>
<video id=cv controls preload=metadata></video>
<!-- Crop controls: start and end time as mm:ss or h:mm:ss. -->
<div class=row style="margin-top:10px"><button onclick="cs.value=fmt(cv.currentTime)">⇤ inizio = qui</button><input class=tm id=cs value="00:00">
<input class=tm id=ce><button onclick="ce.value=fmt(cv.currentTime)">fine = qui ⇥</button>
<button onclick=cplay()>▶ anteprima ritaglio</button><button class=pri id=cgo_ onclick="cgo(0)">✂ Ritaglia e salva come nuova riunione</button><button id=cgi_ onclick="cgo(1)">✂ Ritaglia e salva in questa riunione</button></div>
<!-- Progress bar for the crop re-encode (polled from /crop_progress). -->
<progress id=cpr max=100 value=0 hidden style="width:100%"></progress>
<div id=cmsg>L'originale resta intatto: il ritaglio diventa una nuova riunione (mm:ss o h:mm:ss).</div></dialog>
<!-- Web UI logic. -->
<script src=/ui.js></script>
+47
View File
@@ -1,54 +1,101 @@
/* Theme colours as CSS variables; light theme by default. */
:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442;--acc2:#b05535;--on:#fff;
--red:#f6e0dc;--redf:#a33a2a;--amb:#f7ecd6;--ambf:#8a5a12;--grn:#e2eedf;--grnf:#3d6b35;--gry:#ebe9e1;--gryf:#5e5d57}
/* Dark theme overrides, applied when the OS prefers dark. */
@media (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757;--acc2:#e58a6c;--on:#1f1e1d;
--red:#4a2b26;--redf:#f0a597;--amb:#4a3d24;--ambf:#ecc77f;--grn:#2d3f2a;--grnf:#a8d39c;--gry:#3a3a35;--gryf:#c2c0b6}}
/* Base reset and body typography. */
*{box-sizing:border-box}body{font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;margin:0;padding:32px 24px 64px;background:var(--bg);color:var(--fg)}
/* Centred page column; header wraps on narrow windows. */
main{max-width:1200px;margin:auto}header{display:flex;align-items:end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px}
/* Serif page heading. */
h1{font:500 30px/1.2 ui-serif,Georgia,"Times New Roman",serif;letter-spacing:-.01em;margin:0}
/* Card container for each section. */
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:16px}
/* Flex rows for toolbars and search; inputs grow to fill. */
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.row+.row{margin-top:10px}.row input{flex:1;min-width:220px}
/* Shared form-control look. */
input,select,button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:6px 10px}
/* Accent focus ring. */
input:focus,select:focus{outline:2px solid var(--acc);outline-offset:-1px}
/* Default buttons; primary buttons (.pri) use the accent colour. */
button{cursor:pointer;background:var(--soft)}button:hover{border-color:var(--mut)}button:disabled{opacity:.5;cursor:default}
button.pri{background:var(--acc);border-color:var(--acc);color:var(--on)}button.pri:hover{background:var(--acc2)}
/* Search and Q&A result containers. */
#sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px}
/* Meetings table: full width, rows separated by lines. */
table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tbody.rec:last-child tr:last-child td{border-bottom:0}
/* Alternate background per recording group (tbody.rec); accent bar marks the main row. */
tbody.rec:nth-of-type(even) td{background:color-mix(in srgb,var(--acc) 7%,transparent)}tbody.rec tr.main td:first-child{box-shadow:inset 3px 0 var(--acc)}tbody.rec tr:last-child td{border-bottom:2px solid var(--line)}
/* Table headers. */
th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;letter-spacing:.05em}.card.t{padding:4px 8px;overflow-x:auto}
/* Status badge pill. */
.b{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:500;background:var(--gry);color:var(--gryf)}
/* Status colours: red = recording/error/cancelled, amber = in progress, green = done. */
.recording,.error,.cancelled{background:var(--red);color:var(--redf)}.audio,.transcribing,.diarizing,.identifying,.shots,.docs,.report,.memory{background:var(--amb);color:var(--ambf)}.done{background:var(--grn);color:var(--grnf)}
/* Links, muted small text, speaker-panel row background. */
a{color:var(--acc);cursor:pointer;margin-right:10px;text-decoration:none}a:hover{text-decoration:underline}small{color:var(--mut)}.sp td{background:var(--soft)}.sp div{margin-bottom:8px}
/* Speaker-panel footer buttons. */
.sp .sa{display:flex;gap:8px;justify-content:flex-end;margin-top:12px;padding-top:12px;border-top:1px solid var(--line)}.sp .sa button{padding:7px 16px;font-weight:500}.sp td{padding:14px 16px}
/* Spacing for table action buttons; muted queue counter. */
td button,td select{margin:0 4px 4px 0}#qs{color:var(--mut)}
/* Progress panel (.pg) shown while a pipeline runs. */
.pg{padding:14px 16px 12px;background:var(--soft);border:1px solid var(--line);border-radius:12px;margin:0 0 8px}
/* Progress panel header row. */
.pgh{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap;margin-bottom:8px}.pgh b{font-size:15px}.pgh .n{color:var(--mut)}
/* Large percentage figure and ETA text. */
.big{font:600 22px/1 ui-serif,Georgia,serif;letter-spacing:-.01em}.eta{color:var(--mut);font-size:13px}.eta b{color:var(--fg);font-size:13px}
/* Progress bar track; .thin is the per-step bar. */
.bar{height:12px;background:var(--line);border-radius:99px;overflow:hidden}.bar.thin{height:6px;margin-top:10px}
/* Bar fill: animated diagonal stripes (moved by the mv keyframes). */
.bar>i{display:block;height:100%;width:0;border-radius:99px;transition:width .9s ease;background-color:var(--acc);
background-image:linear-gradient(45deg,rgba(255,255,255,.2) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.2) 50%,rgba(255,255,255,.2) 75%,transparent 75%),linear-gradient(90deg,var(--acc),var(--acc2));
background-size:24px 24px,100% 100%;animation:mv 1s linear infinite}
@keyframes mv{to{background-position:24px 0,0 0}}
/* Indeterminate bar: sliding 30% segment (used while progress is unknown). */
.bar.ind>i{width:30%!important;animation:mv 1s linear infinite,ind 1.6s ease-in-out infinite}@keyframes ind{0%{margin-left:-30%}100%{margin-left:100%}}
/* Step chips row. */
.steps{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
/* Step chip base. */
.st{font-size:12px;padding:3px 10px;border-radius:99px;background:var(--card);border:1px solid var(--line);color:var(--mut);white-space:nowrap}
/* Step chip states: ok, running (pulsing), skipped (struck through). */
.st.ok{background:var(--grn);color:var(--grnf);border-color:transparent}.st.run{background:var(--acc);color:var(--on);border-color:transparent;animation:pulse 1.8s ease-in-out infinite}.st.skip{opacity:.4;text-decoration:line-through}
@keyframes pulse{50%{opacity:.72}}
/* Caption line under the progress bar. */
.sub{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:6px;font-size:12.5px;color:var(--mut)}
/* Live activity line with pulsing dot. */
.live{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:13px;color:var(--mut)}.dot{flex:none;width:9px;height:9px;border-radius:50%;background:var(--grnf);animation:pulse 1s ease-in-out infinite}
/* Live activity severity: warn = amber, bad = red with a static dot. */
.live.warn,.live.warn b{color:var(--ambf)}.live.warn .dot{background:var(--ambf)}.live.bad,.live.bad b{color:var(--redf)}.live.bad .dot{background:var(--redf);animation:none}
/* Upload card stays visible while scrolling. */
#ub{position:sticky;top:12px;z-index:5}#ub .pgh{margin-bottom:10px}
/* Dashed outline while a file is dragged over the page. */
body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14px}
/* Hint text. */
#hint{color:var(--mut);font-size:12.5px}
/* Destructive buttons. */
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}
/* Preview/crop dialog. */
dialog{border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--fg);padding:16px;width:min(960px,94vw)}dialog::backdrop{background:rgba(0,0,0,.5)}
/* Video inside the dialog. */
dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}
/* Header layout; separator line under it; the subtitle line hides when empty. */
header{align-items:center;padding-bottom:16px;border-bottom:1px solid var(--line)}.hs{display:flex;gap:12px;flex-wrap:wrap;margin-top:4px;font-size:12.5px;color:var(--mut)}.hs:empty{display:none}
/* Header action group. */
.ha{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.ha>button,.cfg summary{padding:8px 14px;font-weight:500}
/* Settings dropdown (details/summary). */
.cfg{position:relative}.cfg summary{list-style:none;cursor:pointer;user-select:none;background:var(--soft);border:1px solid var(--line);border-radius:9px}.cfg summary::-webkit-details-marker{display:none}.cfg summary:hover,.cfg[open] summary{border-color:var(--mut)}
/* Settings popover panel. */
.pop{position:absolute;right:0;top:calc(100% + 8px);z-index:20;width:300px;display:flex;flex-direction:column;gap:14px;padding:16px;background:var(--card);border:1px solid var(--line);border-radius:14px;box-shadow:0 10px 30px rgba(0,0,0,.18)}
/* On/off switch: the checkbox is hidden and the track (i) is styled. */
.sw{display:flex;gap:12px;align-items:center;cursor:pointer}.sw span{display:flex;flex-direction:column}.sw small{font-size:12px}
/* Switch track. */
.sw input{position:absolute;opacity:0;width:0;height:0}.sw i{flex:none;position:relative;width:38px;height:22px;border-radius:99px;background:var(--line);transition:background .15s}
/* Switch knob. */
.sw i::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s}
/* Checked state: knob slides 16 px. */
.sw input:checked+i{background:var(--acc)}.sw input:checked+i::after{transform:translateX(16px)}.sw input:focus-visible+i{outline:2px solid var(--acc);outline-offset:2px}.sw input:disabled+i{opacity:.5}
/* Labelled select in the settings popover. */
.fl{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--mut)}.fl select{width:100%;font-size:14px;color:var(--fg)}
/* Bulk-action bar: sticky at the top while visible. */
#bulk{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 14px;position:sticky;top:12px;z-index:6;box-shadow:0 6px 20px rgba(0,0,0,.12)}#bulk[hidden]{display:none}#bulk a{cursor:pointer}#bulk .sep{flex:1}
+84
View File
@@ -1,78 +1,137 @@
// Web UI logic: polls /status every 3 s, renders the meetings table, and wires search, Q&A, upload, crop and bulk actions to the local server.
// Escape text for innerHTML (&, <, >, ").
const E=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
// Seconds -> mm:ss (minutes can exceed 59; no hour form here).
const fmt=s=>{s=Math.round(s);return String(Math.floor(s/60)).padStart(2,"0")+":"+String(s%60).padStart(2,"0")};
// Enter in the search box runs the search.
q.onkeydown=e=>{if(e.key=="Enter")srch()};
// Enter in the Q&A box asks the question.
qa.onkeydown=e=>{if(e.key=="Enter")ask()};
// Q&A: /ask answers from the meeting data. The model may take minutes to load on first use.
async function ask(){if(!qa.value)return;ar.innerHTML="<small>…avvio modelli / risposta (può richiedere qualche minuto)</small>";
const r=await fetch("/ask?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return}const j=await r.json();
// Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing.
ar.innerHTML="<div>"+E(j.answer).replace(/\[(\d+)\]/g,(m,n)=>{const s=j.sources[n-1];return s?`<a href="/report?name=${s.name}#${s.anchor}" target=_blank>[${n}]</a>`:m})+"</div>"+
j.sources.map(s=>`<div><small>[${s.n}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} ${fmt(s.t)} (${s.kind}): ${E(s.text)}</small></div>`).join("")}
// Search over speech and screen text (/search).
async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json();
// Speech hits: [meeting, seconds, speaker, text]. Screen hits: [meeting, seconds, speaker, text, shot file] and link to the screenshot.
sr.innerHTML=j.speech.map(r=>`<div>${E(r[0])} ${fmt(r[1])} ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")+j.screen.map(r=>`<div>🖥 <a href="/shot?name=${r[0]}&file=shots/${r[4]}" target=_blank>${E(r[0])} ${fmt(r[1])}</a> ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")}
// Start a pipeline run from the chosen step (/run); 409 means it is already running.
async function run(n){const f=document.getElementById("f-"+n).value;const r=await fetch(`/run?name=${n}&from=${f}`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()}
// Names of the checked recording rows (.mg checkboxes).
const sel_=()=>[...document.querySelectorAll(".mg:checked")].map(x=>x.value);
// Show the bulk bar only when something is checked, and show the selected count.
function upd(){const n=sel_().length;bulk.hidden=!n;bn.textContent=`${n} selezionat${n==1?"a":"e"}`}
// Check or uncheck all recording rows.
function selAll(v){document.querySelectorAll(".mg").forEach(x=>x.checked=!!v);upd()}
// Run one POST per selected recording and collect failures into a single alert.
async function bulk_(path,names,label){let bad=[];for(const n of names){const r=await fetch(`${path}${path.includes("?")?"&":"?"}name=${n}`,{method:"POST"});if(!r.ok)bad.push(`${n}: ${await r.text()}`)}
if(bad.length)alert(`${label}: ${names.length-bad.length}/${names.length} ok\n`+bad.join("\n"));tick()}
// Re-run the selected recordings from the step chosen in #bf.
function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")}
// Bulk delete of video files only; report, transcript and screenshots are kept.
function bulkDrop(){const n=sel_();if(confirm(`Eliminare i file video di ${n.length} riunioni?
Report, trascrizione, audio e schermate restano, ma non potranno più essere rielaborate. Non si può annullare.`))bulk_("/drop_video",n,"elimina video")}
// Bulk delete of whole recordings; asks for confirmation first.
function bulkDel(){const n=sel_();if(confirm(`Eliminare definitivamente ${n.length} riunioni?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))bulk_("/delete",n,"elimina")}
// Merge two or more checked recordings (same meeting restarted) into one.
async function mergeSel(){const n=sel_();if(n.length<2)return alert("spunta almeno 2 registrazioni");const r=await fetch("/merge?names="+n.join(","),{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Names whose speakers panel is open; kept across re-renders.
const open_=new Set();
// Toggle the speakers panel for one recording and re-render.
async function spk(n){editing=false;open_.has(n)?open_.delete(n):open_.add(n);tick()}
// Speakers panel: diarization label -> person mapping, with a datalist of candidate names.
async function panel(n){const j=await (await fetch("/speakers?name="+n)).json();
return `<tr class=sp><td colspan=7><datalist id="cand-${n}">${j.candidates.map(c=>`<option value="${E(c)}">`).join("")}</datalist>`+
j.rows.map(r=>`<div><b>${E(r.label)}</b> ${fmt(r.talk_s)} <input data-n="${n}" data-l="${E(r.label)}" list="cand-${n}" value="${E(r.person)}"> ${r.source}${r.source=="auto"&&r.overlap_s!=null?" "+Math.round(r.overlap_s)+"s":""}<br><small>${r.samples.map(E).join(" | ")}</small></div>`).join("")+
`<div class=sa><button class=pri onclick="saveSpk('${n}')">✓ Salva nomi</button><button onclick="spk('${n}')">✕ Chiudi</button></div>`}
// Read the label -> person inputs and save them (/speaker_map).
async function saveSpk(n){const m={};document.querySelectorAll(`input[data-n="${n}"]`).forEach(i=>m[i.dataset.l]=i.value);
const r=await fetch("/speaker_map?name="+n,{method:"POST",body:JSON.stringify(m)});editing=false;const t=await r.text();open_.delete(n);tick();alert(t)}
// Recompute the automatic title from the report.
async function retitle(n){const r=await fetch(`/run?name=${n}&from=title`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
const sel={};
// Delete one recording after confirmation.
async function del_(n,label){if(!confirm(`Eliminare definitivamente "${label}"?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))return;
const r=await fetch("/delete?name="+n,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Delete only the video file of one recording (report and transcript stay).
async function dropVid(n,mb){if(!confirm(`Eliminare il file video (${mb} MB)?
Report, trascrizione, audio e schermate restano, ma la riunione non potrà più essere rielaborata. Non si può annullare.`))return;
const r=await fetch("/drop_video?name="+n,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Prompt for a new title; empty means automatic. The date suffix is stripped from the default text.
async function setTitle(n,cur){const t=prompt("Titolo della riunione (vuoto = automatico)",cur.replace(/ — \d{4}-\d\d-\d\d.*$/,""));if(t===null)return;
const r=await fetch("/title?name="+n,{method:"POST",body:t});if(!r.ok)alert(await r.text());tick()}
// "mm:ss" or "h:mm:ss" -> seconds.
const sec=s=>s.trim().split(":").reduce((a,x)=>a*60+(+x),0);
// Open the preview dialog for recording n; the video is streamed from /video.
function play(n,d,t){cv.src="/video?name="+n;ctitle.textContent=t;cs.value="00:00";ce.value=d?fmt(d):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration)};cdlg.showModal()}
// Stop and unload the video so the file handle is released.
function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()}
// Esc closes the dialog through the same cleanup.
cdlg.addEventListener("cancel",cclose);
// Play from the start time; pause at the end time when one is set.
function cplay(){cv.currentTime=sec(cs.value);cv.play();const e=sec(ce.value);cv.ontimeupdate=()=>{if(e>0&&cv.currentTime>=e){cv.pause();cv.ontimeupdate=null}}}
// Crop: inplace replaces the original (after confirm); otherwise a new meeting is created from the clip.
async function cgo(inplace){const a=sec(cs.value),b=sec(ce.value),n=new URL(cv.src).searchParams.get("name");
// Validate the interval: start >= 0 and end after start.
if(!(a>=0&&b>a)){cmsg.textContent="intervallo non valido";return}
// Replacing the original is irreversible, so confirm first.
if(inplace&&!confirm("Sostituire il video di questa riunione con il ritaglio? L'originale va perso e la riunione viene rielaborata da zero."))return;
if(inplace){cv.pause();cv.removeAttribute("src");cv.load()} // release the file: Windows can't replace a source the browser has open
// Disable both crop buttons while the re-encode runs.
cgo_.disabled=cgi_.disabled=true;cmsg.textContent="ritaglio in corso… (ricodifica, può richiedere minuti)";cpr.value=0;cpr.hidden=false;
// Poll crop progress every 700 ms while the blocking /crop request is pending.
const iv=setInterval(async()=>{try{const p=(await(await fetch("/crop_progress?name="+n,{method:"POST"})).json()).pct;if(p!=null){cpr.value=p;cmsg.textContent=`ritaglio in corso… ${Math.round(p)}%`}}catch(e){}},700);
// Blocking request: the server re-encodes the clip, which can take minutes.
const r=await fetch(`/crop?name=${n}&start=${a}&end=${b}${inplace?"&inplace=1":""}`,{method:"POST"});clearInterval(iv);cgo_.disabled=cgi_.disabled=false;cpr.hidden=true;
// Show the result and refresh the table.
if(!r.ok){cmsg.textContent="errore: "+await r.text();return}cmsg.textContent=inplace?"✓ riunione ritagliata, rielaborazione avviata":"✓ creata nuova riunione, elaborazione avviata";tick()}
// Cancel a running or queued pipeline (after confirm).
async function stopRun(n){if(!confirm(`Fermare ${n}?`))return;await fetch("/cancel?name="+n,{method:"POST"});tick()}
// Save the screenshot-model and report-model choice on the server.
async function setLlm(){const r=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Save the "skip screenshots" switch on the server.
async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()}
// Italian labels for pipeline steps.
const LBL={audio:"Audio",transcribing:"Trascrizione",diarizing:"Chi parla",identifying:"Nomi parlanti",shots:"Schermate",docs:"Documentazione",report:"Report",memory:"Memoria"};
// What each step does, shown under the progress bar.
const HOW={audio:"pulizia e normalizzazione dell'audio",transcribing:"Whisper trascrive il parlato",diarizing:"riconoscimento di chi parla",identifying:"abbinamento voci-nomi",shots:"il modello di visione legge ogni schermata condivisa",docs:"ricerca su Confluence e Jira",report:"il modello scrive argomenti, decisioni e azioni",memory:"indicizzazione per la ricerca tra riunioni"};
// Seconds -> "N s", "N min" or "H h MM min".
const dur=s=>{if(s==null||!isFinite(s))return"–";s=Math.max(0,Math.round(s));if(s<60)return s+" s";const m=Math.round(s/60);return m<60?m+" min":Math.floor(m/60)+" h "+String(m%60).padStart(2,"0")+" min"};
// Seconds from now -> local HH:MM.
const clock=s=>new Date(Date.now()+s*1000).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});
// Per recording: last [timestamp, tokens decoded], used to compute tokens/s between ticks.
const LT={};
// LLM activity line: prompt reading vs token writing; idle time sets the severity colour.
function live(n,p){const l=p.llm;let txt="",act=false;
// Model is busy: compare token counts with the previous tick.
if(l&&l.is_processing){act=true;const k=n,prev=LT[k],now=Date.now(),d=l.n_decoded||0;
// Tokens/s from the delta since the previous tick.
if(d>0){const tps=prev&&d>prev[1]?(d-prev[1])/((now-prev[0])/1000):null;txt=`Il modello sta scrivendo: <b>${d}</b> token${tps?` · <b>${tps.toFixed(1)}</b> token/s`:""}`}
else txt=`Il modello sta leggendo il contesto: <b>${l.n_prompt_tokens_processed||0}</b> di ${l.n_prompt_tokens} token`;
// Store this sample for the next tick.
LT[k]=[now,d]}
// Severity by idle time: under 90 s ok, under 300 s warn, otherwise bad.
const idle=p.idle,cls=act||idle<90?"":idle<300?"warn":"bad";
// Status text for the idle time.
const tail=act?`ultimo passo completato ${dur(idle)} fa`:idle<90?`attivo · aggiornato ${dur(idle)} fa`:idle<300?`nessun avanzamento da <b>${dur(idle)}</b>: può essere normale (avvio modello, passo lungo)`:`nessuna attività da <b>${dur(idle)}</b>: possibile blocco, controlla il log Prefect o premi stop`;
return `<div class="live ${cls}"><span class=dot></span><span>${txt?txt+" — ":""}${tail}</span></div>`}
// Progress panel for a recording: boot, queued, or running pipeline.
function progPanel(r){const p=r.prog;
// Pipeline starting: the Python environment can take minutes on the first run.
if(!p&&r.running)return `<tr><td colspan=7><div class=pg><div class=pgh><span><span class=big>…</span> &nbsp;<b>Avvio della pipeline</b> <span class=n>— preparazione dell'ambiente Python (la prima volta scarica le dipendenze: qualche minuto)</span></span></div><div class="bar ind"><i></i></div><div class="live"><span class=dot></span><span>${E(r.boot||"in avvio…")}</span></div></div>`;
// Queued behind another run, or nothing to show.
if(!p)return r.status=="queued"?`<tr><td colspan=7><div class=pg><div class=pgh><b>In coda</b><span class=eta>parte appena finisce l'elaborazione in corso</span></div><div class="bar ind"><i></i></div></div>`:"";
// Overall percent (null if unknown) and the running step.
const pct=p.pct!=null?Math.round(p.pct*100):null,cur=p.plan.find(x=>x.state=="run");
// Step chips: skipped / done with duration / running with fraction / pending with estimate.
const chips=p.plan.map(x=>x.state=="skip"?`<span class="st skip" title="non rieseguito">${LBL[x.s]}</span>`:x.state=="done"?`<span class="st ok">✓ ${LBL[x.s]} · ${dur(x.secs)}</span>`:x.state=="run"?`<span class="st run">● ${LBL[x.s]} · ${Math.round(x.frac*100)}%</span>`:`<span class=st>${LBL[x.s]} · ~${dur(x.est)}</span>`).join("");
// Done-of-total counter and step label.
const cnt=p.total?`${p.done} di ${p.total}`:"",step=LBL[p.step]||p.step;
// Panel markup: header, progress bars, step chips and live status.
return `<tr><td colspan=7><div class=pg>
<div class=pgh><span><span class=big>${pct!=null?pct+"%":"…"}</span> &nbsp;<b>${step}</b> <span class=n>— ${E(p.note||HOW[p.step]||"")}</span></span>
<span class=eta>${p.eta!=null?`fine prevista <b>~${clock(p.eta)}</b> · mancano <b>${dur(p.eta)}</b> · `:""}trascorso ${dur(p.elapsed)}</span></div>
@@ -82,35 +141,60 @@ return `<tr><td colspan=7><div class=pg>
<div class=sub><span>${step}: ${cnt?cnt+" · ":""}${Math.round(p.frac*100)}%</span><span>${cur?`questo passo: ancora ~${dur(cur.left)} (in corso da ${dur(cur.secs)})`:""}</span></div>
${live(r.name,p)}</div>`}
function pick(){up.click()}
// Upload with XHR so we get upload progress events. Target: POST /upload?filename=.
function send(f){const x=new XMLHttpRequest(),t0=Date.now();ub.hidden=false;ubar.style.width="0%";utitle.textContent="Caricamento di "+f.name;ubig.textContent="0%";
// Update bar, percent, MB/s and ETA from upload progress.
x.upload.onprogress=e=>{if(!e.lengthComputable)return;const p=e.loaded/e.total,s=(Date.now()-t0)/1000,v=e.loaded/Math.max(s,.1);
ubar.style.width=(p*100).toFixed(1)+"%";ubig.textContent=Math.floor(p*100)+"%";
utxt.textContent=`${(e.loaded/1e6).toFixed(0)} di ${(e.total/1e6).toFixed(0)} MB · ${(v/1e6).toFixed(1)} MB/s · mancano ${dur((e.total-e.loaded)/v)}`};
// Upload finished on the client; the server now validates the file and starts processing.
x.upload.onload=()=>{utxt.textContent="File ricevuto: controllo del formato e avvio dell'elaborazione…"};
// Success: show the recording duration; hide the card after 6 s.
x.onload=()=>{if(x.status==200){const j=JSON.parse(x.responseText);ubig.textContent="✓";utxt.textContent=`Avviata l'elaborazione (${dur(j.duration_s)} di registrazione): segui l'avanzamento qui sotto`;setTimeout(()=>ub.hidden=true,6000)}
else{ubig.textContent="!";utxt.textContent="Errore: "+x.responseText}tick()};
// Network error.
x.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
// Cancel: abort the request and hide the card.
ucancel.onclick=()=>{x.abort();ub.hidden=true};
// File is sent as the raw request body.
x.open("POST","/upload?filename="+encodeURIComponent(f.name));x.send(f)}
// File picker upload; reset the input so the same file can be picked again.
up.onchange=()=>{if(up.files[0])send(up.files[0]);up.value=""};
// Dragging over the page: highlight the drop zone.
addEventListener("dragover",e=>{e.preventDefault();document.body.classList.add("drag")});
// Leaving the window (no relatedTarget) clears the highlight.
addEventListener("dragleave",e=>{if(!e.relatedTarget)document.body.classList.remove("drag")});
// Drop anywhere on the page: upload the first file.
addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("drag");const f=e.dataTransfer.files[0];if(f)send(f)});
// Refresh the whole UI from /status: header, LLM pickers, table.
async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.ask_blocked;ab.title=j.ask_blocked?"pipeline in corso":"";
// Browser tab title shows the progress of the first running pipeline.
const runp=j.recs.map(r=>r.prog).filter(p=>p&&p.pct!=null);document.title=runp.length?`${Math.round(runp[0].pct*100)}% · ${LBL[runp[0].step]} · Riunioni`:"Riunioni";
// Refill the LLM pickers from the server list; skip the focused one so the user's choice is not overwritten.
for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "],[llma,1,""]])if(document.activeElement!==s){s.innerHTML=j.llms[i].map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.disabled=j.busy}
// Skip-screenshots switch; disabled while busy.
skp.checked=j.skip_shots;skp.disabled=j.busy;
// omp login status: red and showing the error when logged out.
const o=j.omp;omps.innerHTML=!o.exe?`<span style="color:var(--redf)">omp non installato</span>`:[["github-copilot","Copilot"],["anthropic","Anthropic"]].map(([k,l])=>`<span title="${E(o[k]||"login valido")}"${o[k]?' style="color:var(--redf)"':""}>${o[k]?"✗":"✓"} ${l}</span>`).join(" · ");
// Queue size in the header.
qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:"";
// Remember step-select values so they survive the re-render.
document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value);
// Table header.
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
// One tbody per recording; "running" when the status is done but the process is still alive.
for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status;
// Display title, falling back to the upload name.
const nm=r.title||r.upload;
// Main row: checkbox, title and rename buttons; status badge with error text and time since last data.
h+=`<tbody class=rec><tr class=main><td><input type=checkbox class=mg value="${r.name}">${nm?`<b>${E(nm)}</b><br><small>${r.name}</small>`:r.name} <button class=del title="modifica titolo" onclick="setTitle('${r.name}','${E(r.title||r.upload||"").replace(/'/g,"")}')">✎</button>${r.mb&&r.files.includes("report.html")?`<button class=del title="ricalcola titolo" onclick="retitle('${r.name}')">↻</button>`:""}<td><span class="b ${r.status}" title="${E(r.error)}">${r.status}</span>${r.receiving_age_s!=null&&r.status=="recording"?` <small>${r.receiving_age_s}s ago</small>`:""}${r.error?`<br><small>${E(r.error)}</small>`:""}<td>${r.duration_s?fmt(r.duration_s):""}<td>${r.speakers??""}<td>${r.mb}
<td>${r.files.includes("report.html")?`<a href="/report?name=${r.name}" target=_blank>report</a><a href="/pdf?name=${r.name}" target=_blank>pdf</a>`:""}${r.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${r.flow_run_id}" target=_blank>prefect</a>`:""}
<td>${r.mb?`<select id="f-${r.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(s=>`<option>${s}`).join("")}</select><button onclick="run('${r.name}')">run</button>`:""}<button onclick="spk('${r.name}')">speakers</button>${r.mb?`<button title="anteprima e ritaglio" onclick="play('${r.name}',${r.duration_s||0},'${E(nm||r.name).replace(/'/g,"")}')">▶ video</button>`:""}${r.mb&&r.status=="done"&&!r.running?`<button title="elimina solo il file video: report, trascrizione e schermate restano, ma non si può più rielaborare" onclick="dropVid('${r.name}',${r.mb})">🎞 elimina video</button>`:""}${r.running||r.status=="queued"?`<button onclick="stopRun('${r.name}')">stop</button>`:`<button class=del title="elimina la riunione" onclick="del_('${r.name}','${E(nm||r.name).replace(/'/g,"")}')">🗑</button>`}`;
h+=progPanel(r);
if(open_.has(r.name))h+=await panel(r.name);h+="</tbody>"}
// Re-render only when not editing a speaker field and no table input has focus, so user input is kept.
const ae=document.activeElement;if(!editing&&!(ae&&t.contains(ae)&&/^(INPUT|SELECT)$/.test(ae.tagName))){const ck=[...document.querySelectorAll(".mg:checked")].map(x=>x.value);t.innerHTML=h;for(const k in sel){const e=document.getElementById(k);if(e)e.value=sel[k]}document.querySelectorAll(".mg").forEach(x=>x.checked=ck.includes(x.value));upd()}}catch(e){}}
// Set while typing in a speaker name input.
let editing=false;t.addEventListener("input",e=>{if(e.target.dataset.n)editing=true});t.addEventListener("change",e=>{if(e.target.classList.contains("mg"))upd()});
// Initial load, then poll every 3 s.
tick();setInterval(tick,3000);