Add 'skip shots' GUI toggle and crop progress bar

This commit is contained in:
Stefano Zini
2026-11-04 09:06:37 +01:00
parent 9a69b78ff7
commit 71b0d39b2a
2 changed files with 28 additions and 8 deletions
+6 -2
View File
@@ -94,8 +94,12 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str
try: done = json.loads(sj.read_text(encoding="utf-8"))
except (OSError, ValueError): done = []
# complete = every referenced frame/crop is still on disk (a run cancelled mid-shots wipes them while shots.json is stale)
skip_shots = start_from != "shots" and bool(done) and all((sd / f).exists() for s in done for f in (s.get("file"), s.get("view")) if f)
if skip_shots and go("shots"): print("shots already done: skipped (run from 'shots' to redo)")
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
skip_shots = no_shots or (start_from != "shots" and bool(done) and all((sd / f).exists() for s in done for f in (s.get("file"), s.get("view")) if f))
if no_shots and not done:
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
db.replace_shots(name, [])
if skip_shots and go("shots"): print("shots skipped" if no_shots else "shots already done: skipped (run from 'shots' to redo)")
if start_from == "render":
memory.run(name, link=False)
else:
+22 -6
View File
@@ -21,6 +21,7 @@ HERE = Path(__file__).parent
out = db.OUT; out.mkdir(exist_ok=True)
R = {} # name -> {"last": ts of last chunk}
JOBS = {} # name -> Popen
CROP = {} # name -> % of running crop
PREFECT = "http://127.0.0.1:4200"
ENV = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
ENV.update(PREFECT_API_URL=PREFECT + "/api", NO_PROXY="127.0.0.1,localhost")
@@ -308,7 +309,7 @@ def status():
if d["running"] and not d["prog"]: d["boot"] = last_log(n)
w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0
rs.append(d)
return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE),
return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE), "skip_shots": (db.GLOBAL / "skip_shots.txt").exists(),
"llm": [llama.current(True), llama.current(False)], "llms": [[[k, llama.label(k)] for k in llama.available(v)] for v in (True, False)]}
@@ -407,7 +408,7 @@ body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}
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)}
dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}</style>
<main><header><h1>Riunioni</h1><div class=row><span id=qs></span><select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select><select id=llmr title="modello per il report" onchange=setLlm()></select><button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci spuntati</button><button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<main><header><h1>Riunioni</h1><div class=row><span id=qs></span><label title="non legge le schermate condivise: elaborazione molto più veloce, report solo dal parlato"><input type=checkbox id=skp onchange=setSkip()> Salta schermate</label><select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select><select id=llmr title="modello per il report" onchange=setLlm()></select><button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci spuntati</button><button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header>
<div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div>
<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>
@@ -420,6 +421,7 @@ dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog
<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()>✂ Ritaglia e salva come nuova riunione</button></div>
<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>
<script>
const E=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
@@ -456,11 +458,13 @@ cdlg.addEventListener("cancel",cclose);
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}}}
async function cgo(){const a=sec(cs.value),b=sec(ce.value),n=new URL(cv.src).searchParams.get("name");
if(!(a>=0&&b>a)){cmsg.textContent="intervallo non valido";return}
cgo_.disabled=true;cmsg.textContent="ritaglio in corso… (ricodifica, può richiedere minuti)";
const r=await fetch(`/crop?name=${n}&start=${a}&end=${b}`,{method:"POST"});cgo_.disabled=false;
cgo_.disabled=true;cmsg.textContent="ritaglio in corso… (ricodifica, può richiedere minuti)";cpr.value=0;cpr.hidden=false;
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);
const r=await fetch(`/crop?name=${n}&start=${a}&end=${b}`,{method:"POST"});clearInterval(iv);cgo_.disabled=false;cpr.hidden=true;
if(!r.ok){cmsg.textContent="errore: "+await r.text();return}cmsg.textContent="✓ creata nuova riunione, elaborazione avviata";tick()}
async function stopRun(n){if(!confirm(`Fermare ${n}?`))return;await fetch("/cancel?name="+n,{method:"POST"});tick()}
async function setLlm(){const r=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()}
const LBL={audio:"Audio",transcribing:"Trascrizione",diarizing:"Chi parla",identifying:"Nomi parlanti",shots:"Schermate",docs:"Documentazione",report:"Report",memory:"Memoria"};
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"};
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"};
@@ -506,6 +510,7 @@ addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("d
async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.busy;ab.title=j.busy?"pipeline in corso":"";
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";
for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "]])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}
skp.checked=j.skip_shots;skp.disabled=j.busy;
qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:"";
document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value);
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
@@ -583,6 +588,7 @@ class H(BaseHTTPRequestHandler):
if (j and j.poll() is None) or name in R or any(x[0] == name for x in QUEUE): return self._send("in elaborazione o in registrazione: ferma prima".encode(), 409)
db.delete_recording(name); JOBS.pop(name, None); self._send()
elif u.path == "/crop": self.crop(name, q)
elif u.path == "/crop_progress": self._json({"pct": CROP.get(name)})
elif u.path == "/cancel":
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
elif u.path == "/merge":
@@ -602,6 +608,11 @@ class H(BaseHTTPRequestHandler):
f = q.get("from", "audio")
if f not in STEPS: return self._send(b"bad step", 400)
self._send(b"") if run_all(f) else self._send("rielaborazione già in corso".encode(), 409)
elif u.path == "/skip_shots":
f = db.GLOBAL / "skip_shots.txt"
if q.get("v") == "1": f.write_text("1")
else: f.unlink(missing_ok=True)
self._send()
elif u.path == "/llm":
ks = [q.get("shots"), q.get("report")]
if not (ks[0] in llama.available(True) and ks[1] in llama.available(False)): return self._send(b"modello non installato", 400)
@@ -644,8 +655,13 @@ class H(BaseHTTPRequestHandler):
new = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S"); ext = ".mp4" if v else ".m4a"
dst = db.out_dir(new) / f"source{ext}"; tmp = dst.with_name(f"source{ext}.part")
enc = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"] if v else ["-vn"]
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(s), "-t", str(e - s), "-i", str(src), *enc,
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-f", "mp4", str(tmp)], capture_output=True, text=True)
CROP[name] = 0
p = subprocess.Popen(["ffmpeg", "-y", "-v", "error", "-progress", "pipe:1", "-nostats", "-ss", str(s), "-t", str(e - s), "-i", str(src), *enc,
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-f", "mp4", str(tmp)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for ln in p.stdout:
if ln.startswith("out_time_us=") and ln[12:].strip().lstrip("-").isdigit(): CROP[name] = min(99, max(0, int(ln[12:]) / 1e4 / (e - s)))
err = p.stderr.read(); p.wait(); CROP.pop(name, None)
r = type("R", (), {"returncode": p.returncode, "stderr": err})
if r.returncode or not tmp.exists() or not tmp.stat().st_size:
tmp.unlink(missing_ok=True); dst.parent.rmdir(); return self._send(f"ffmpeg: {r.stderr[-300:]}".encode(), 500)
tmp.replace(dst)