Drop-video button (blocks reruns), manual title, striped recording groups, collapse whisper loops, fix report _clean name clash
This commit is contained in:
+9
-5
@@ -38,13 +38,17 @@ def _tick(note):
|
||||
if PROG: PROG[1] += 1; db.tick(PROG[0], PROG[1], max(PROG[2], PROG[1] + 1) if note != "fine" else PROG[1], note)
|
||||
|
||||
|
||||
def _manual_title(name):
|
||||
p = db.out_dir(name) / "title.txt"
|
||||
return p.read_text(encoding="utf-8").strip() if p.exists() else ""
|
||||
|
||||
THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room
|
||||
|
||||
def _clean(o):
|
||||
def _strip_junk(o):
|
||||
"""Small models sometimes append '<closing braces> + a self-check' inside the last string value: cut it."""
|
||||
if isinstance(o, str): return re.split(r"[\]}]{2,}|[\u2705\u2714\u274c]", o)[0].strip()
|
||||
if isinstance(o, list): return [_clean(x) for x in o]
|
||||
if isinstance(o, dict): return {k: _clean(v) for k, v in o.items()}
|
||||
if isinstance(o, list): return [_strip_junk(x) for x in o]
|
||||
if isinstance(o, dict): return {k: _strip_junk(v) for k, v in o.items()}
|
||||
return o
|
||||
|
||||
|
||||
@@ -63,7 +67,7 @@ def chat(system, user, max_tokens, retries=2, think=False):
|
||||
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
|
||||
t = llama.content(json.load(r), f"report ({max_tokens} max)")
|
||||
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
|
||||
d = _clean(json.loads(t[t.find("{"):t.rfind("}") + 1]))
|
||||
d = _strip_junk(json.loads(t[t.find("{"):t.rfind("}") + 1]))
|
||||
if isinstance(d, dict): return d
|
||||
except (ValueError, KeyError): pass
|
||||
return None
|
||||
@@ -330,7 +334,7 @@ def run(name, window_words=3000):
|
||||
if screen and (screen[-1]["title"] or "").lower() == (r["title"] or "").lower(): screen[-1]["t_end"] = r["t_end"]
|
||||
else: screen.append(r)
|
||||
m = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name)
|
||||
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": title,
|
||||
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": _manual_title(name) or title,
|
||||
"tldr": tldr, "attendees": list(att.values()), "attendees_source": attendees_source, "known_spelling": bool(known),
|
||||
"name_map": cmap, "shares": shares, "chat": chats, "references": references, "screen": screen, "topics": topics}
|
||||
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
+49
-7
@@ -92,7 +92,7 @@ def pump():
|
||||
def run_all(start_from):
|
||||
if BATCH is not None: return False
|
||||
for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name"):
|
||||
launch(r[0], start_from)
|
||||
if db.media(r[0])[0]: launch(r[0], start_from) # no source video (drop_video): no re-elaboration
|
||||
return True
|
||||
|
||||
|
||||
@@ -123,7 +123,9 @@ TITLES = {} # name -> (report.json mtime, "title — date")
|
||||
|
||||
def title(n):
|
||||
f = out / n / "report.json"
|
||||
if not f.exists(): return ""
|
||||
if not f.exists():
|
||||
m = out / n / "title.txt"
|
||||
return m.read_text(encoding="utf-8").strip() if m.exists() else ""
|
||||
m = f.stat().st_mtime
|
||||
if TITLES.get(n, (0,))[0] != m:
|
||||
try: j = json.loads(f.read_text(encoding="utf-8")); TITLES[n] = (m, f"{j.get('meeting_title') or ''} — {j.get('date') or ''}")
|
||||
@@ -133,6 +135,21 @@ def title(n):
|
||||
|
||||
def busy(): return bool(QUEUE) or any(p.poll() is None for p in JOBS.values())
|
||||
|
||||
def set_title(name, t):
|
||||
"""Manual meeting title (out/<name>/title.txt, wins over Teams/LLM titles); empty clears it. Patches report.json and re-renders."""
|
||||
t = " ".join(t.split())[:200]
|
||||
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return False
|
||||
f = out / name / "title.txt"
|
||||
if t: f.write_text(t, encoding="utf-8")
|
||||
else: f.unlink(missing_ok=True)
|
||||
rj = out / name / "report.json"
|
||||
if rj.exists() and t:
|
||||
j = json.loads(rj.read_text(encoding="utf-8")); j["meeting_title"] = t
|
||||
rj.write_text(json.dumps(j, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
launch(name, "render")
|
||||
return True
|
||||
|
||||
|
||||
|
||||
def flow_pids(name=None):
|
||||
"""PIDs of the top `uv run --script flow.py <name>` processes (also flows started before a server restart)."""
|
||||
@@ -159,6 +176,19 @@ def cancel(name, reason="cancelled from web UI"):
|
||||
return bool(pids)
|
||||
|
||||
|
||||
def drop_video(name):
|
||||
"""Delete only the video/source file after the report: audio.opus, transcript, shots, report stay. Returns (MB freed, error)."""
|
||||
r = db.connect().execute("SELECT status FROM recordings WHERE name=?", (name,)).fetchone()
|
||||
j = JOBS.get(name)
|
||||
if not r or r["status"] != "done" or name in R or (j and j.poll() is None) or any(q[0] == name for q in QUEUE): return 0, "solo a report finito e senza run attivi"
|
||||
if not (out / name / "audio.opus").exists(): return 0, "manca audio.opus: video non eliminato"
|
||||
n = 0
|
||||
for e in (".webm", ".mp4", ".mkv", ".mov"):
|
||||
p = out / f"{name}{e}"
|
||||
if p.exists(): n += p.stat().st_size; p.unlink()
|
||||
return round(n / 1e6, 1), None
|
||||
|
||||
|
||||
def merge(names):
|
||||
"""Join webm parts of one call (restarted recording): stream copy in start order, events shifted by the cumulative length.
|
||||
Returns (merged_name, None) or (None, error). Originals stay; delete them from the GUI once the merged report is fine."""
|
||||
@@ -351,7 +381,8 @@ input:focus,select:focus{outline:2px solid var(--acc);outline-offset:-1px}
|
||||
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)}
|
||||
#sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px}
|
||||
table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tr:last-child td{border-bottom:0}
|
||||
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}
|
||||
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)}
|
||||
th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;letter-spacing:.05em}.card.t{padding:4px 8px;overflow-x:auto}
|
||||
.b{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:500;background:var(--gry);color:var(--gryf)}
|
||||
.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)}
|
||||
@@ -417,6 +448,10 @@ const r=await fetch("/speaker_map?name="+n,{method:"POST",body:JSON.stringify(m)
|
||||
const sel={};
|
||||
async function del_(n,label){if(!confirm(`Eliminare definitivamente "${label}"?\nVengono 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()}
|
||||
async function dropVid(n,mb){if(!confirm(`Eliminare il file video (${mb} MB)?\nReport, 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()}
|
||||
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()}
|
||||
const sec=s=>s.trim().split(":").reduce((a,x)=>a*60+(+x),0);
|
||||
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()}
|
||||
function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()}
|
||||
@@ -476,14 +511,14 @@ const runp=j.recs.map(r=>r.prog).filter(p=>p&&p.pct!=null);document.title=runp.l
|
||||
for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "]])if(document.activeElement!==s){s.innerHTML=j.llms.map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.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="<tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr>";
|
||||
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
|
||||
for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status;
|
||||
const nm=r.title||r.upload;
|
||||
h+=`<tr><td><input type=checkbox class=mg value="${r.name}">${nm?`<b>${E(nm)}</b><br><small>${r.name}</small>`:r.name}<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}
|
||||
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><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><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.running?`<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>`}`;
|
||||
<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?`<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)}
|
||||
if(open_.has(r.name))h+=await panel(r.name);h+="</tbody>"}
|
||||
if(!document.activeElement||document.activeElement.tagName!="INPUT"){t.innerHTML=h;for(const k in sel){const e=document.getElementById(k);if(e)e.value=sel[k]}}}catch(e){}}
|
||||
tick();setInterval(tick,3000);
|
||||
</script>"""
|
||||
@@ -555,7 +590,14 @@ class H(BaseHTTPRequestHandler):
|
||||
elif u.path == "/merge":
|
||||
m, err = merge([n for n in q.get("names", "").split(",") if n])
|
||||
self._send(m.encode() if m else err.encode(), 200 if m else 400)
|
||||
elif u.path == "/drop_video":
|
||||
mb, err = drop_video(name)
|
||||
self._send(f"{mb} MB liberati".encode() if not err else err.encode(), 200 if not err else 409)
|
||||
elif u.path == "/title":
|
||||
self._send(b"") if set_title(name, data.decode("utf-8", "replace")) else self._send(b"not found", 404)
|
||||
elif u.path == "/run":
|
||||
if not db.media(name)[0]:
|
||||
return self._send("video eliminato: rielaborazione non possibile".encode(), 409)
|
||||
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 0))
|
||||
self._send(b"" if ok else "già in coda o in esecuzione".encode(), 200 if ok else 409)
|
||||
elif u.path == "/run_all":
|
||||
|
||||
+4
-2
@@ -17,14 +17,16 @@ def _log(msg):
|
||||
|
||||
|
||||
def aggregate(segs):
|
||||
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run."""
|
||||
lines, buf, start, end = [], [], 0, 0
|
||||
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run. A segment repeated 3+ times in a row is a whisper loop (46x "Ciao."): keep 2."""
|
||||
lines, buf, start, end, last, rep = [], [], 0, 0, None, 0
|
||||
def flush():
|
||||
if buf:
|
||||
lines.append((int(start), " ".join(buf))); buf.clear()
|
||||
for s, e, t in segs:
|
||||
t = t.strip()
|
||||
if not t: continue
|
||||
rep = rep + 1 if t == last else 0; last = t
|
||||
if rep >= 2: continue
|
||||
if buf and s - end > 1: flush()
|
||||
if not buf: start = s
|
||||
buf.append(t); end = e
|
||||
|
||||
Reference in New Issue
Block a user