${data.candidates.map(candidate=>``).join("")} `+
data.rows.map(row=>`${E(row.label)} ${fmt(row.talk_s)} ${row.source}${row.source==="auto"&&row.overlap_s!=null?" "+Math.round(row.overlap_s)+"s":""}${row.samples.map(E).join(" | ")}
`).join("")+
`✓ Salva nomi ✕ Chiudi
`}
// Read the label -> person inputs and save them (/speaker_map).
async function saveSpk(name){const labels={};document.querySelectorAll(`input[data-n="${name}"]`).forEach(input=>labels[input.dataset.l]=input.value);
const response=await fetch("/speaker_map?name="+name,{method:"POST",body:JSON.stringify(labels)});editing=false;const text=await response.text();open_.delete(name);tick();alert(text)}
// Recompute the automatic title from the report.
async function retitle(name){const response=await fetch(`/run?name=${name}&from=title`,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
const sel={};
// Mini modal with the secondary actions of one recording: rerun from step, drop video, delete.
function more(name,mb,label,canDrop,title,canRetitle,blocked){
mbody.innerHTML=`${label} 👥 partecipanti speakers ✎ modifica titolo `+(canRetitle?`↻ ricalcola titolo `:"")+`↻ riprocessa `+
`📂 mostra su disco `+
(canDrop&&!blocked?`🎞 elimina video `:"")+
(blocked?"":`🗑 elimina riunione `)+`✕ chiudi `;mdlg.showModal()}
// Ask the server to open the meeting folder in Explorer.
async function reveal(name){const response=await fetch("/reveal?name="+name,{method:"POST"});if(!response.ok)alert(await response.text())}
// Participants: named speakers (unnamed labels shown as-is) with talk time, in the same modal.
async function who(name){const data=await (await fetch("/speakers?name="+name)).json();
mbody.innerHTML=`Partecipanti `+(data.rows.map(row=>`${E(row.person||row.label)} ${fmt(row.talk_s)}
`).join("")||"nessun dato
")+`✕ chiudi `}
const mclose=()=>mdlg.close();
// Delete one recording after confirmation.
async function del_(name,label){if(!confirm(`Eliminare definitivamente "${label}"?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))return;
const response=await fetch("/delete?name="+name,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Delete only the video file of one recording (report and transcript stay).
async function dropVid(name,mb){if(!confirm(`Eliminare il file video (${mb} MB)?
Report, trascrizione, audio e schermate restano; la rielaborazione salterà i passaggi che richiedono il video (audio, schermate). Non si può annullare.`))return;
const response=await fetch("/drop_video?name="+name,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Title dialog; empty means automatic. The date suffix is stripped from the default text.
let tname="";
function setTitle(name,cur){tname=name;tin.value=cur.replace(/ — \d{4}-\d\d-\d\d.*$/,"");tdlg.showModal();tin.select()}
async function saveTitle(){const response=await fetch("/title?name="+tname,{method:"POST",body:tin.value});tdlg.close();if(!response.ok)alert(await response.text());tick()}
// "mm:ss" or "h:mm:ss" -> seconds.
const sec=str=>str.trim().split(":").reduce((acc,part)=>acc*60+(+part),0);
// Open the preview dialog for recording n; the video is streamed from /video. Optional at = seconds to start playing from (used by the Q&A sources).
function play(name,duration,title,start){cv.src="/video?name="+name;ctitle.textContent=title;cs.value="00:00";ce.value=duration?fmt(duration):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration);if(start>0){cv.currentTime=start;cv.play().catch(()=>{})}};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 endTime=sec(ce.value);cv.ontimeupdate=()=>{if(endTime>0&&cv.currentTime>=endTime){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 start=sec(cs.value),end=sec(ce.value),name=new URL(cv.src).searchParams.get("name");
// Validate the interval: start >= 0 and end after start.
if(!(start>=0&&end>start)){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 percent=(await(await fetch("/crop_progress?name="+name,{method:"POST"})).json()).pct;if(percent!=null){cpr.value=percent;cmsg.textContent=`ritaglio in corso… ${Math.round(percent)}%`}}catch{/* poll failed: next tick retries */}},700);
// Blocking request: the server re-encodes the clip, which can take minutes.
const response=await fetch(`/crop?name=${name}&start=${start}&end=${end}${inplace?"&inplace=1":""}`,{method:"POST"});clearInterval(iv);cgo_.disabled=cgi_.disabled=false;cpr.hidden=true;
// Show the result and refresh the table.
if(!response.ok){cmsg.textContent="errore: "+await response.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(name){if(!confirm(`Fermare ${name}?`))return;await fetch("/cancel?name="+name,{method:"POST"});tick()}
// Save the screenshot-model and report-model choice on the server.
async function setLlm(){const response=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!response.ok)alert(await response.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:"Riconoscimento voci",identifying:"Assegnazione nomi",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:"separazione dei partecipanti in base alla voce",identifying:"associazione di ogni voce al nome del partecipante",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=seconds=>{if(seconds==null||!isFinite(seconds))return"–";seconds=Math.max(0,Math.round(seconds));if(seconds<60)return seconds+" s";const minutes=Math.round(seconds/60);return minutes<60?minutes+" min":Math.floor(minutes/60)+" h "+String(minutes%60).padStart(2,"0")+" min"};
// Seconds from now -> local HH:MM.
const clock=seconds=>new Date(Date.now()+seconds*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(name,prog){const info=prog.llm;let txt="",act=false;
// Model is busy: compare token counts with the previous tick.
if(info&&info.is_processing){act=true;const key=name,prev=LT[key],now=Date.now(),decoded=info.n_decoded||0;
// Tokens/s from the delta since the previous tick.
if(decoded>0){const tps=prev&&decoded>prev[1]?(decoded-prev[1])/((now-prev[0])/1000):null;txt=`Il modello sta scrivendo: ${decoded} token${tps?` · ${tps.toFixed(1)} token/s`:""}`}
else txt=`Il modello sta leggendo il contesto: ${info.n_prompt_tokens_processed||0} di ${info.n_prompt_tokens} token`;
// Store this sample for the next tick.
LT[key]=[now,decoded]}
// Severity by idle time: under 90 s ok, under 300 s warn, otherwise bad.
const idle=prog.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 ${dur(idle)} : può essere normale (avvio modello, passo lungo)`:`nessuna attività da ${dur(idle)} : possibile blocco, controlla il log Prefect o premi stop`;
return `${txt?txt+" — ":""}${tail}
`}
// Progress panel for a recording: boot, queued, or running pipeline.
function progPanel(row){const prog=row.prog,stop=`${row.flow_run_id?`prefect `:""}■ stop `;
// Pipeline starting: the Python environment can take minutes on the first run.
if(!prog&&row.running)return `
${pct!=null?pct+"%":"…"} ${step} — ${E(prog.note||HOW[prog.step]||"")}
${prog.eta!=null?`fine prevista ~${clock(prog.eta)} · mancano ${dur(prog.eta)} · `:""}trascorso ${dur(prog.elapsed)} ${stop}
${chips}
${step}: ${cnt?cnt+" · ":""}${Math.round(prog.frac*100)}% ${cur?`questo passo: ancora ~${dur(cur.left)} (in corso da ${dur(cur.secs)})`:""}
${live(row.name,prog)}
`}
function pick(){up.click()}
// Upload with XHR so we get upload progress events. Target: POST /upload?filename=.
function send(file){const xhr=new XMLHttpRequest(),t0=Date.now();ub.hidden=false;ubar.style.width="0%";utitle.textContent="Caricamento di "+file.name;ubig.textContent="0%";
// Update bar, percent, MB/s and ETA from upload progress.
xhr.upload.onprogress=event=>{if(!event.lengthComputable)return;const fraction=event.loaded/event.total,elapsed=(Date.now()-t0)/1000,speed=event.loaded/Math.max(elapsed,.1);
ubar.style.width=(fraction*100).toFixed(1)+"%";ubig.textContent=Math.floor(fraction*100)+"%";
utxt.textContent=`${(event.loaded/1e6).toFixed(0)} di ${(event.total/1e6).toFixed(0)} MB · ${(speed/1e6).toFixed(1)} MB/s · mancano ${dur((event.total-event.loaded)/speed)}`};
// Upload finished on the client; the server now validates the file and starts processing.
xhr.upload.onload=()=>{utxt.textContent="File ricevuto: controllo del formato e avvio dell'elaborazione…"};
// Success: show the recording duration; hide the card after 6 s.
xhr.onload=()=>{if(xhr.status===200){const data=JSON.parse(xhr.responseText);ubig.textContent="✓";utxt.textContent=`Avviata l'elaborazione (${dur(data.duration_s)} di registrazione): segui l'avanzamento qui sotto`;setTimeout(()=>ub.hidden=true,6000)}
else{ubig.textContent="!";utxt.textContent="Errore: "+xhr.responseText}tick()};
// Network error.
xhr.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
// Cancel: abort the request and hide the card.
ucancel.onclick=()=>{xhr.abort();ub.hidden=true};
// File is sent as the raw request body.
xhr.open("POST","/upload?filename="+encodeURIComponent(file.name));xhr.send(file)}
// 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",event=>{event.preventDefault();document.body.classList.add("drag")});
// Leaving the window (no relatedTarget) clears the highlight.
addEventListener("dragleave",event=>{if(!event.relatedTarget)document.body.classList.remove("drag")});
// Drop anywhere on the page: upload the first file.
addEventListener("drop",event=>{event.preventDefault();document.body.classList.remove("drag");const file=event.dataTransfer.files[0];if(file)send(file)});
// Meetings per page and current page index (0-based); goPg changes page and re-renders.
const PS=100;let pg_=0;
function goPg(delta){pg_+=delta;tick()}
// Refresh the whole UI from /status: header, LLM pickers, table.
async function tick(){try{const data=await (await fetch("/status")).json();ab.disabled=data.ask_blocked;ab.title=data.ask_blocked?"pipeline in corso":"";
// Browser tab title shows the progress of the first running pipeline.
const runp=data.recs.map(row=>row.prog).filter(prog=>prog&&prog.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 [select,index,prefix] of [[llm,0,"shots: "],[llmr,1,"report: "],[llma,1,""]])if(document.activeElement!==select){select.innerHTML=data.llms[index].map(([key,label])=>`${prefix}${E(label)}`).join("");select.value=data.llm[index];select.disabled=data.busy}
// Skip-screenshots switch; disabled while busy.
skp.checked=data.skip_shots;skp.disabled=data.busy;
// omp login status: red and showing the error when logged out.
const ompStatus=data.omp;omps.innerHTML=!ompStatus.exe?`omp non installato `:[["github-copilot","Copilot"],["anthropic","Anthropic"]].map(([key,label])=>`${ompStatus[key]?"✗":"✓"} ${label} `).join(" · ");
// Queue size in the header.
qs.textContent=data.queue?`rielaborazione: ${data.queue} da completare`:"";
// Remember step-select values so they survive the re-render.
document.querySelectorAll("select[id^=f-]").forEach(select=>sel[select.id]=select.value);
// Table header.
let html="riunione stato durata speaker dimensione azioni ";
// Pagination: PS meetings per page; clamp the page if recordings were removed, then draw the pager.
const pages=Math.max(1,Math.ceil(data.recs.length/PS));if(pg_>=pages)pg_=pages-1;
pgr.innerHTML=pages>1?`‹ pagina ${pg_+1} di ${pages} (${data.recs.length} riunioni) › `:"";
// One tbody per recording on the current page; "running" when the status is done but the process is still alive.
for(const row of data.recs.slice(pg_*PS,(pg_+1)*PS)){
// Display title, falling back to the upload name.
const nm=row.title||row.upload,act=!!(row.prog||row.running||row.status==="queued");
// Main row: checkbox, title and rename buttons; status badge with error text and time since last data.
html+=`${nm?`${E(nm)} ${act?" ":""}${row.name} `:row.name+(act?" ":"")} ${row.status} ${row.receiving_age_s!=null&&row.status==="recording"?` ${row.receiving_age_s}s ago `:""}${row.error?`${E(row.error)} `:""}${row.duration_s?fmt(row.duration_s):""} ${row.speakers??""} ${row.mb?row.mb+" MB":""}
`;
html+=pgo.has(row.name)?progPanel(row):"";
if(open_.has(row.name))html+=await panel(row.name);html+=" "}
// 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(box=>box.value);t.innerHTML=html;for(const id in sel){const element=document.getElementById(id);if(element)element.value=sel[id]}document.querySelectorAll(".mg").forEach(box=>box.checked=ck.includes(box.value));upd()}}catch{/* poll failed: next tick retries */}}
// Set while typing in a speaker name input.
let editing=false;t.addEventListener("input",event=>{if(event.target.dataset.n)editing=true});t.addEventListener("change",event=>{if(event.target.classList.contains("mg"))upd()});
// Initial load, then poll every 3 s.
tick();setInterval(tick,3000);