Allow reprocessing after video drop: skip audio/shots steps lacking media, limit reprocess dropdown to docs+; plus pending ext/report/ui changes

This commit is contained in:
Stefano Zini
2026-11-06 10:56:30 +01:00
parent d1d71ddafc
commit b80207a186
6 changed files with 36 additions and 23 deletions
+5 -3
View File
@@ -37,7 +37,9 @@ async function start(streamId, tabId) {
recordingName = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
// Tab capture stream: the chromeMediaSource constraint is the only way to get tab audio/video in an extension.
const captureConstraint = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: streamId } };
tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: captureConstraint });
const videoConstraint = { mandatory: { ...captureConstraint.mandatory, maxFrameRate: 15 } }; // fewer fps = more bits per frame for slides/text
tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: videoConstraint });
for (const t of tabStream.getVideoTracks()) t.contentHint = "detail"; // favor sharpness over motion
// Mixer: tab audio + optional mic are mixed into one destination track.
audioContext = new AudioContext();
const dest = audioContext.createMediaStreamDestination();
@@ -51,8 +53,8 @@ async function start(streamId, tabId) {
} catch { micStream = null; }
// Output stream: tab video + mixed audio.
const outStream = new MediaStream([...tabStream.getVideoTracks(), ...dest.stream.getAudioTracks()]);
// VP8 video + Opus audio at 1 Mbps video, a format the server's ffmpeg pipeline accepts.
recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
// VP8 video + Opus audio at 3 Mbps video (1 Mbps gave blocky/ringing text on shared screens).
recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 3e6 });
// Each 10 s chunk is uploaded in order through the uploadQueue promise chain.
recorder.ondataavailable = event => {
// Chain the upload on uploadQueue so chunks reach the server in order; count success or failure, then flush events.
+11 -6
View File
@@ -185,14 +185,19 @@ def meeting(
except (OSError, ValueError):
previous_shots = []
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
skip_shots = no_shots
# Toggle on with no prior shots: write empty placeholders so downstream steps find their files.
if no_shots and not previous_shots:
# Dropped video: reuse the shots already extracted; dropped source: reuse audio.opus (no audio/shots re-extraction).
no_video = db.media(name)[1] is None
skip_shots = no_shots or no_video
# Toggle on (or no video) with no prior shots: write empty placeholders so downstream steps find their files.
if skip_shots and not previous_shots:
for file_name in ("shots.json", "glossary.json"):
(db.out_dir(name) / file_name).write_text("[]")
db.replace_shots(name, [])
if skip_shots and should_run("shots"):
print("shots skipped")
def audio_ok():
return (db.out_dir(name) / "audio.opus").exists()
# Title/render restart: re-run only text-only post-processing, no vision model needed.
if start_from == "title":
llama_server.ensure(vision=False)
@@ -201,14 +206,14 @@ def meeting(
elif start_from == "render":
memory.run(name, link=False)
else:
if should_run("audio"):
if should_run("audio") and db.media(name)[0]:
audio_task(name)
# Speaker labelling: diarize, then name mapping.
def speaker_chain():
return (
[diarize_task(name, speakers), speakers_task(name)]
if should_run("diarize")
if should_run("diarize") and audio_ok()
else ([speakers_task(name)] if should_run("speakers") else None)
)
@@ -245,7 +250,7 @@ def meeting(
shots_future.result()
else:
# Sequential path (CUDA, or NPU without shots).
if should_run("transcribe"):
if should_run("transcribe") and audio_ok():
transcribe_task(name, model, device)
speaker_chain()
if should_run("shots") and not skip_shots:
+8 -3
View File
@@ -66,6 +66,11 @@ def _tick(note):
db.tick(PROG[0], PROG[1], max(PROG[2], PROG[1] + 1) if note != "fine" else PROG[1], note)
# User refinement prompt saved in meta (set from the reprocess dialog); appended to topic and overview prompts.
def _refine(name):
text = db.meta(name).get("refine", "")
return f"\nIstruzioni aggiuntive dell'utente per il report: {text}" if text else ""
# Title typed manually in the meeting metadata (wins over the LLM title).
def _manual_title(name):
return db.meta(name).get("title", "")
@@ -492,8 +497,8 @@ def run(name, window_words=3000):
n_chunks + 3 * n_chunks + 1,
] # chunks + ~3 topics per chunk (docs pass) + overview
db.tick(name, 0, PROG[2], f"argomenti: blocco 1 di {n_chunks}")
# System prompt + glossary (or "nessuno").
system = SYS_A + (", ".join(glossary) or "nessuno")
# System prompt + glossary (or "nessuno") + optional user refinement.
system = SYS_A + (", ".join(glossary) or "nessuno") + _refine(name)
topics, buffer, words, wstart = [], [], 0, 0
# Send the buffered chunk to the LLM and append its topics.
@@ -569,7 +574,7 @@ def run(name, window_words=3000):
# Overview pass: title and TL;DR from the topics.
overview = (
chat(
SYS_B,
SYS_B + _refine(name),
json.dumps(
[
{
+5 -5
View File
@@ -217,8 +217,7 @@ def run_all(start_from):
for row in db.connect().execute(
"SELECT name FROM recordings WHERE status!='recording' ORDER BY name"
):
if db.media(row[0])[0]:
launch(row[0], start_from) # no source video (drop_video): no re-elaboration
launch(row[0], start_from)
return True
@@ -929,7 +928,7 @@ class Handler(BaseHTTPRequestHandler):
# POST: ingestion (/chunk, /events, /upload), recording control, and actions.
def do_POST(self):
parsed = urlparse(self.path)
params = {key: value[0] for key, value in parse_qs(parsed.query).items()}
params = {key: value[0] for key, value in parse_qs(parsed.query, keep_blank_values=True).items()}
name = Path(params.get("name", "x")).name
if parsed.path == "/upload":
return self.upload(params)
@@ -1019,9 +1018,10 @@ class Handler(BaseHTTPRequestHandler):
b"not found", 404
)
elif parsed.path == "/run":
if not db.media(name)[0]:
return self._send(b"video eliminato: rielaborazione non possibile", 409)
# Re-run the flow from a step (default audio), with optional speaker count.
# `refine` (even empty) replaces the saved report-refinement prompt; absent = keep.
if "refine" in params:
db.set_meta(name, refine=params["refine"].strip())
launched = launch(name, params.get("from", "audio"), int(params.get("speakers") or 0))
self._send(
b"" if launched else "già in coda o in esecuzione".encode(),
+1
View File
@@ -47,6 +47,7 @@
<div class=sa><button class=pri onclick=saveTitle()>✓ Salva titolo</button><button onclick=tdlg.close()>✕ Chiudi</button></div></dialog>
<!-- Reprocess dialog (reprocess() in ui.js). -->
<dialog id=rdlg style="width:min(380px,94vw)"><b>Riprocessa riunione</b><div class=row style="margin-top:12px;align-items:center">Inizia da: <select id=rstep></select></div>
<textarea id=rprompt rows=4 style="width:100%;margin-top:10px" placeholder="Raffina il report (opzionale), es. «più dettaglio sulle decisioni». Ha effetto se si riparte da report o prima. Vuoto = nessuna istruzione."></textarea>
<div class=sa><button class=pri onclick=run()>▶ Inizia</button><button onclick=rdlg.close()>✕ Chiudi</button></div></dialog>
<!-- Web UI logic. -->
<script src=/ui.js></script>
+6 -6
View File
@@ -35,8 +35,8 @@ async function srch(){if(!q.value){sr.innerHTML="";return}const results=await (a
sr.innerHTML=results.speech.map(hit=>`<div>${E(hit[0])} ${fmt(hit[1])} ${E(hit[2]||"")}: ${E(hit[3])}</div>`).join("")+results.screen.map(hit=>`<div>🖥 <a href="/shot?name=${hit[0]}&file=shots/${hit[4]}" target=_blank>${E(hit[0])} ${fmt(hit[1])}</a> ${E(hit[2]||"")}: ${E(hit[3])}</div>`).join("")+CLOSE("q","sr")}
// Reprocess dialog: pick the first step, then start the pipeline from it (/run); 409 means it is already running.
let rname="";
function reprocess(name){rname=name;rstep.innerHTML=["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(step=>`<option>${step}`).join("");rdlg.showModal()}
async function run(){const response=await fetch(`/run?name=${rname}&from=${rstep.value}`,{method:"POST"});rdlg.close();if(response.status===409)alert("già in esecuzione");tick()}
function reprocess(name,mb){rname=name;rstep.innerHTML=["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].slice(mb?0:5).map(step=>`<option>${step}`).join("");rprompt.value="";rdlg.showModal()}
async function run(){const response=await fetch(`/run?name=${rname}&from=${rstep.value}&refine=${encodeURIComponent(rprompt.value)}`,{method:"POST"});rdlg.close();if(response.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.
@@ -50,7 +50,7 @@ if(bad.length)alert(`${label}: ${names.length-bad.length}/${names.length} ok\n`+
function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")}
// Bulk delete of video files only; report, transcript and screenshots are kept.
function bulkDrop(){const names=sel_();if(confirm(`Eliminare i file video di ${names.length} riunioni?
Report, trascrizione, audio e schermate restano, ma non potranno più essere rielaborate. Non si può annullare.`))bulk_("/drop_video",names,"elimina video")}
Report, trascrizione, audio e schermate restano; la rielaborazione salterà i passaggi che richiedono il video. Non si può annullare.`))bulk_("/drop_video",names,"elimina video")}
// Bulk delete of whole recordings; asks for confirmation first.
function bulkDel(){const names=sel_();if(confirm(`Eliminare definitivamente ${names.length} riunioni?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))bulk_("/delete",names,"elimina")}
@@ -76,7 +76,7 @@ async function retitle(name){const response=await fetch(`/run?name=${name}&from=
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=`<b>${label}</b><button onclick="who('${name}')">👥 partecipanti</button><button onclick="mclose();spk('${name}')">speakers</button><button onclick="mclose();setTitle('${name}','${title}')">✎ modifica titolo</button>`+(canRetitle?`<button onclick="mclose();retitle('${name}')">↻ ricalcola titolo</button>`:"")+(mb?`<button ${blocked?"disabled":""} onclick="mclose();reprocess('${name}')">↻ riprocessa</button>`:"")+
mbody.innerHTML=`<b>${label}</b><button onclick="who('${name}')">👥 partecipanti</button><button onclick="mclose();spk('${name}')">speakers</button><button onclick="mclose();setTitle('${name}','${title}')">✎ modifica titolo</button>`+(canRetitle?`<button onclick="mclose();retitle('${name}')">↻ ricalcola titolo</button>`:"")+`<button ${blocked?"disabled":""} onclick="mclose();reprocess('${name}',${mb})">↻ riprocessa</button>`+
`<button onclick="mclose();reveal('${name}')">📂 mostra su disco</button>`+
(canDrop&&!blocked?`<button onclick="mclose();dropVid('${name}',${mb})">🎞 elimina video</button>`:"")+
(blocked?"":`<button class=del onclick="mclose();del_('${name}','${label}')">🗑 elimina riunione</button>`)+`<button onclick="mclose()">✕ chiudi</button>`;mdlg.showModal()}
@@ -92,7 +92,7 @@ Vengono cancellati registrazione, trascrizione, schermate e report. Non si può
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, ma la riunione non potrà più essere rielaborata. Non si può annullare.`))return;
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="";
@@ -228,7 +228,7 @@ for(const row of data.recs.slice(pg_*PS,(pg_+1)*PS)){
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+=`<tbody class=rec><tr class=main><td><input type=checkbox class=mg value="${row.name}"><span class="ttl${act?" act":""}"${act?` onclick="togPg('${row.name}')" title="mostra/nascondi avanzamento"`:""}>${nm?`<b>${E(nm)}</b>${act?"<span class=spin></span>":""}<br><small>${row.name}</small>`:row.name+(act?"<span class=spin></span>":"")}</span><td><span class="b ${row.status}" title="${E(row.error)}">${row.status}</span>${row.receiving_age_s!=null&&row.status==="recording"?` <small>${row.receiving_age_s}s ago</small>`:""}${row.error?`<br><small>${E(row.error)}</small>`:""}<td>${row.duration_s?fmt(row.duration_s):""}<td>${row.speakers??""}<td>${row.mb?row.mb+" MB":""}
<td><div class=acts><a class="btn pri"${row.files.includes("report.html")?` href="/report?name=${row.name}" target=_blank`:""}>📄 report</a><a class=btn${row.files.includes("report.html")?` href="/pdf?name=${row.name}" target=_blank`:""}>pdf</a><button title="anteprima e ritaglio" ${row.mb?"":"disabled"} onclick="play('${row.name}',${row.duration_s||0},'${E(nm||row.name).replace(/'/g,"")}')">▶ video</button><button title="altre azioni" onclick="more('${row.name}',${row.mb||0},'${E(nm||row.name).replace(/'/g,"")}',${!!(row.mb&&row.status==="done"&&!row.running)},'${E(row.title||row.upload||"").replace(/'/g,"")}',${!!(row.mb&&row.files.includes("report.html"))},${!!(row.running||row.status==="queued"||row.status==="recording")})">⋯</button></div>`;
<td><div class=acts><a class="btn pri"${row.files.includes("report.html")?` href="/report?name=${row.name}" target=_blank`:""}>📄 report</a><a class=btn${row.files.includes("report.html")?` href="/pdf?name=${row.name}" target=_blank`:""}>pdf</a><button title="anteprima e ritaglio" ${row.mb?"":"disabled"} onclick="play('${row.name}',${row.duration_s||0},'${E(nm||row.name).replace(/'/g,"")}')">▶ video</button><button title="altre azioni" onclick="more('${row.name}',${row.mb||0},'${E(nm||row.name).replace(/'/g,"")}',${!!(row.mb&&row.status==="done"&&!row.running)},'${E(row.title||row.upload||"").replace(/'/g,"")}',${!!row.files.includes("report.html")},${!!(row.running||row.status==="queued"||row.status==="recording")})">⋯</button></div>`;
html+=pgo.has(row.name)?progPanel(row):"";
if(open_.has(row.name))html+=await panel(row.name);html+="</tbody>"}
// Re-render only when not editing a speaker field and no table input has focus, so user input is kept.