GUI: upload, live progress + ETA, delete; report thinking; docs twg fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stefano Zini
2026-11-02 17:23:40 +01:00
co-authored by Claude Opus 5.5
parent edb8ee3731
commit cbe111bc34
9 changed files with 309 additions and 29 deletions
+76 -2
View File
@@ -1,5 +1,5 @@
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
import json, re, sqlite3
import json, re, sqlite3, time
from pathlib import Path
HERE = Path(__file__).parent
@@ -95,12 +95,86 @@ def out_dir(name) -> Path:
return d
# ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ----
ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses
FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying",
"shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory"}
STATS = OUT / "step_stats.json"
# seconds of work per minute of audio, measured 2026-11-02 on RTX 500 Ada 4 GB + Core Ultra 7 155H (40-min call);
# replaced by a moving average of real runs as soon as one finishes (keys "<step>" or "<step>@<model>")
SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30,
"docs": 2, "report@qwen35b": 21, "report@qwen4b": 7, "report": 15, "memory": 1}
def _jload(p, default):
try: return json.loads(p.read_text(encoding="utf-8"))
except (OSError, ValueError): return default
def _jsave(p, o):
tmp = p.with_suffix(".tmp"); tmp.write_text(json.dumps(o), encoding="utf-8")
try: tmp.replace(p)
except OSError: pass # reader had it open: next tick writes again
def spm(key):
return {**SPM, **_jload(STATS, {})}.get(key) or SPM.get(key.split("@")[0], 5)
def delete_recording(name):
"""Remove a meeting everywhere: DB rows in every table keyed by name, out/<name>/ and out/<name>.* files."""
import shutil
c = connect()
for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"):
c.execute(f"DELETE FROM {t} WHERE name=?", (name,))
shutil.rmtree(OUT / name, ignore_errors=True)
for p in OUT.glob(f"{name}.*"): p.unlink(missing_ok=True)
def progress(name):
return _jload(OUT / name / "progress.json", None)
def progress_start(name, start_from):
now = time.time()
_jsave(out_dir(name) / "progress.json", {"run_start": now, "start": FROM.get(start_from, "audio"), "step": None, "key": None,
"step_start": now, "done": 0, "total": 0, "note": "", "updated": now, "steps": []})
def step(name, status, key=None):
"""Close the previous step (learn its speed), open `status` ("done" closes the run)."""
set_status(name, status)
p = progress(name)
if not p: return
now = time.time()
if p["step"]:
p["steps"].append([p["step"], p["step_start"], now])
row = connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
mins = (row[0] or 0) / 60 if row else 0
if mins > 1 and now - p["step_start"] > 5: # skip no-op steps
st = _jload(STATS, {}); k = p["key"] or p["step"]; v = (now - p["step_start"]) / mins
st[k] = round(v if k not in st else 0.5 * st[k] + 0.5 * v, 2); _jsave(STATS, st)
p.update(step=None if status == "done" else status, key=key or status, step_start=now, done=0, total=0, note="", updated=now)
_jsave(OUT / name / "progress.json", p)
def tick(name, done, total, note=""):
"""In-step progress; also the heartbeat the GUI uses to show the run is alive."""
p = progress(name)
if not p: return
now = time.time()
if done == 0 and total: p["t0"] = now # loop starts now: rate excludes model load / frame extraction before it
p.update(done=done, total=total, note=note, updated=now)
_jsave(OUT / name / "progress.json", p)
def media(name):
def first(*exts):
for e in exts:
p = OUT / f"{name}{e}"
if p.exists(): return p
return first(".webm", ".wav"), first(".webm", ".mp4")
# audio source, video source; .mkv/.mov/.m4a/.mp3 come from GUI uploads (meet_*)
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov")
def add_events(name, rows):
+2
View File
@@ -27,7 +27,9 @@ def run(name, speakers=5, threshold=0.85):
def progress(done, total): # sherpa calls this per processed chunk; print every 10 %
pct = done * 100 // max(total, 1)
if pct // 10 > last[0]: last[0] = pct // 10; print(f"diarize {pct}% ({done}/{total}, {time.time() - t0:.0f} s)", flush=True)
if done % 20 == 0 or done == total: db.tick(name, done, total, "impronte vocali dei segmenti")
return 0
db.tick(name, 0, 0, "segmentazione dell'audio (~1-2 min)")
segs = [(s.start, s.end, s.speaker) for s in sd.process(audio, callback=progress).sort_by_start_time()]
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True)
+4
View File
@@ -17,6 +17,10 @@ def _twg(*args, timeout=120):
if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON
except ValueError: out = None
# twg >= 1.3 spools large results to a file and prints a YAML envelope: output_files: stdout: "<path>"
if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)):
try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError): pass
else: out = r.stdout if r.returncode == 0 else None
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
env = {**env, "HTTPS_PROXY": PROXY, "HTTP_PROXY": PROXY}
+8 -3
View File
@@ -21,7 +21,8 @@ STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report"
def step_status(name, s):
db.set_status(name, s)
# key per model for the LLM steps: their speed (and so the ETA) depends on it
db.step(name, s, f"{s}@{llama.current(s == 'shots')}" if s in ("shots", "report") else s)
@task(name="audio")
@@ -87,6 +88,7 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 5, model: str
L = Llama(name)
try:
db.upsert_recording(name, flow_run_id=str(flow_run.id))
db.progress_start(name, start_from)
if start_from == "render":
memory.run(name, link=False)
else:
@@ -112,11 +114,11 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 5, model: str
if go("transcribe"): t_transcribe(name, model, device)
spk_chain()
if go("shots"): L.ensure(); t_shots(name)
L.ensure(vision=False) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
if go("docs"): t_docs(name)
L.ensure(vision=False) # report/memory are text-only: drop the vision encoder, use the text profile
if go("report"): t_report(name)
t_memory(name)
db.set_status(name, "done")
db.step(name, "done")
except Exception as e:
db.set_status(name, "error", repr(e)[:500])
raise
@@ -135,6 +137,9 @@ def bench(name):
if __name__ == "__main__":
if sys.argv[1:] == ["--prefect-server"]: # server.py: run Prefect from this cached env (an ephemeral --with env needs PyPI)
import subprocess
sys.exit(subprocess.call([sys.executable, "-m", "prefect", "server", "start", "--host", "127.0.0.1", "--port", "4200"]))
sys.stdout.reconfigure(encoding="utf-8")
ap = argparse.ArgumentParser()
ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS)
+4 -3
View File
@@ -14,13 +14,13 @@ MODELS = {
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
"qwen35b": ("Qwen3.6 35B-A3B (RAM)", MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf",
["--mmproj-offload", *_IMG, "--cpu-moe", "-ngl", "30", "-c", "16384", *_Q],
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", *_Q]),
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", "--reasoning-budget", "1024", *_Q]),
# Hybrid attention -> 16k KV is only ~0.3 GB. Q4_K_S: best boxes/entities vs IQ4_XS/Q4_K_M/UD-Q4_K_XL on 8 sample shots.
# Vision: encoder on GPU, FFN of the last 13/32 layers in RAM to make room: shot 36 -> 22 s (CPU encoder was ~19 s/image),
# gen only 30 -> 25 tok/s; 12 is the limit (10 OOMs), 13 leaves margin. Text: everything on GPU.
"qwen4b": ("Qwen3.5 4B (VRAM)", MD / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf", MD / "qwen3.5-4b" / "mmproj-BF16.gguf",
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q],
["-ngl", "99", "-c", "16384", "-ub", "1024", *_Q]),
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]),
}
PORT = 18081
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
@@ -43,8 +43,9 @@ def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
def content(resp, what):
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints)."""
t = resp.get("timings") or {}
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split())
if t: print(f"llm {what}: prompt {t.get('prompt_n', 0)} tok @ {t.get('prompt_per_second', 0):.0f} t/s, "
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s", flush=True)
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s" + (f" (thinking ~{think} words)" if think else ""), flush=True)
return resp["choices"][0]["message"]["content"]
def up(port=PORT):
+41 -10
View File
@@ -12,7 +12,9 @@ SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"to
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
'Se parlato e schermo divergono, riportalo nel summary. Usa solo fatti presenti nel testo. '
'Usa i nomi dei partecipanti solo se compaiono nel testo come nomi propri; non citare mai le etichette "Speaker N": usa forme impersonali ("si conferma", "viene proposto"). Ogni argomento copre almeno 3 minuti di discussione: non creare un argomento per ogni schermata. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Usa i nomi dei partecipanti solo se compaiono nel testo come nomi propri; non citare mai le etichette "Speaker N": usa forme impersonali ("si conferma", "viene proposto"). Ogni argomento copre almeno 3 minuti di discussione: non creare un argomento per ogni schermata. '
'Nel summary riporta ciò che è stato detto, spiegato e deciso, non la navigazione tra le schermate (es. «si apre la console»): al massimo 6 punti per argomento. '
'Non scrivere voci vuote come «nessuna domanda aperta»: lascia la lista vuota. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Glossario dei termini corretti letti dallo schermo (la trascrizione può storpiarli, usa la grafia del glossario): ')
SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr":[str]}. title: titolo breve della riunione (max 8 parole). Massimo 5 punti in tldr, in italiano, forma impersonale, senza etichette "Speaker N". Usa solo fatti presenti.'
SYS_D = ('Hai un argomento di una riunione e alcuni estratti di documentazione aziendale numerati. Rispondi SOLO JSON: {"summary":[{"text":str,"doc":int|null}],"from_docs":[{"text":str,"doc":int}]}. '
@@ -28,9 +30,20 @@ def secs(s):
return int(m[1]) * 60 + int(m[2]) if m else 0
def chat(system, user, max_tokens, retries=2):
body = {"model": llama.current(False), "temperature": 0.2, "max_tokens": max_tokens,
"chat_template_kwargs": {"enable_thinking": False}, "response_format": {"type": "json_object"},
PROG = None # [name, calls done, calls expected] while report.run() is active
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)
THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room
def chat(system, user, max_tokens, retries=2, think=False):
"""think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast."""
body = {"model": llama.current(False), "temperature": 0.2, "max_tokens": max_tokens + (THINK if think else 0),
"chat_template_kwargs": {"enable_thinking": think}, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
for _ in range(retries):
try:
@@ -151,6 +164,7 @@ def _tidy(topics, dur, min_s=TIDY_MIN):
m = dict(a)
m["title"] = (a if ln(a) >= ln(b) else b)["title"]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): m[k] = a[k] + b[k]
for k in ("decisions", "open_questions"): m[k] = _clean(m[k])
m["start_s"], m["end_s"] = min(a["start_s"], b["start_s"]), max(a["end_s"], b["end_s"])
topics[lo:hi + 1] = [m]
for t in topics:
@@ -158,6 +172,18 @@ def _tidy(topics, dur, min_s=TIDY_MIN):
return topics
FILLER = re.compile(r"(?i)^\s*(nessun[aoe]?|non (sono|è) (emers|stat)|n/?a\b|-+$)")
def _clean(xs):
"""Drop model filler ("Nessuna domanda aperta emersa…") and duplicates; merged topics repeated them."""
out = []
for x in xs:
x = str(x).strip()
if x and not FILLER.match(x) and x.lower() not in {o.lower() for o in out}: out.append(x)
return out
def _words(s): return {w for w in re.findall(r"\w+", s.lower()) if len(w) >= 5}
@@ -169,7 +195,7 @@ def _pass_d(t, docs):
if not top: return
user = f"ARGOMENTO: {t['title']}\nSINTESI:\n" + "\n".join(f"- {x['text']}" for x in t["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join(
f"[{n}] {d['title']} ({d['source']})\n{d['body'][:2500]}" for n, d in enumerate(top, 1))
r = chat(SYS_D, user, 2500) or {}
r = chat(SYS_D, user, 2500, think=True) or {}
ref = lambda n: top[n - 1]["i"] if isinstance(n, int) and 1 <= n <= len(top) else None
fix = lambda l: [{"text": str(x["text"]), "doc": ref(x.get("doc"))} for x in l if isinstance(x, dict) and x.get("text")]
s = fix(r.get("summary") or [])
@@ -219,19 +245,23 @@ def run(name, window_words=3000):
items += [(e["t"], f"[{mmss(e['t'])}] [MANO ALZATA] {e['who']}", 0) for e in evs if e["kind"] == "hand"]
items.sort(key=lambda x: x[0])
global PROG
n_chunks = max(1, -(-sum(w for _, _, w in items) // window_words))
PROG = [name, 0, 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 = SYS_A + (", ".join(glossary) or "nessuno")
topics, buf, words, wstart = [], [], 0, 0
def flush(end):
nonlocal buf, words
if not buf: return
d = chat(system, "\n".join(buf), 4000)
d = chat(system, "\n".join(buf), 4000, think=True); _tick(f"argomenti: blocco {PROG[1] + 1} di {n_chunks} fatto")
ts = d.get("topics") if d else None
if not ts:
ts = [{"title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"]}]
for t in ts:
t = {"title": str(t.get("title") or "Argomento"), "summary": list(t.get("summary") or []), "shown": list(t.get("shown") or []),
"decisions": list(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": list(t.get("open_questions") or []),
"decisions": _clean(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": _clean(t.get("open_questions") or []),
"start_s": secs(t.get("start")), "end_s": secs(t.get("end"))}
t["end_s"] = min(max(t["end_s"], t["start_s"] + 1), max(dur, t["start_s"] + 1))
topics.append(t)
@@ -246,12 +276,13 @@ def run(name, window_words=3000):
for a in t["actions"]:
if re.fullmatch(r"Speaker \d+", str(a.get("who", ""))) and a["who"] not in names: a["who"] = ""
docs = _load(name, "docs.json", {"items": [], "people": []})["items"]
PROG[2] = PROG[1] + (len(topics) if docs else 0) + 1
for t in topics:
t["summary"] = [{"text": str(s), "doc": None} for s in t["summary"]]
t["from_docs"] = []
if docs: _pass_d(t, docs)
if docs: _pass_d(t, docs); _tick(f"documentazione per «{t['title'][:50]}»")
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800) or {}
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800, think=True) or {}; _tick("fine")
tldr = [str(x) for x in (ov.get("tldr") or [])][:5]
title = title or str(ov.get("title") or "").strip()
+162 -6
View File
@@ -97,14 +97,15 @@ def prefect_up():
def start_prefect():
if prefect_up(): return
subprocess.Popen(["uv", "run", "--with", "prefect>=3", "prefect", "server", "start", "--host", "127.0.0.1", "--port", "4200"],
# flow.py's env already has Prefect: works offline (the old `uv run --with prefect` re-resolved from PyPI and died without DNS)
subprocess.Popen(["uv", "run", "--script", "flow.py", "--prefect-server"],
cwd=HERE, env=ENV, stdout=open(out / "prefect.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
def backfill():
c = db.connect()
have = {r[0] for r in c.execute("SELECT name FROM recordings")}
for p in sorted([*out.glob("teams_*.webm"), *out.glob("meet_*.wav"), *out.glob("meet_*.mp4")]):
for p in sorted([*out.glob("teams_*.webm"), *[p for p in out.glob("meet_*.*") if p.suffix.lower() in UPLOAD_EXT]]):
if p.stem in have or (p.suffix == ".webm" and time.time() - p.stat().st_mtime < 60): continue
db.upsert_recording(p.stem, source="ext" if p.stem.startswith("teams_") else "meet",
status="done" if (out / p.stem / "report.html").exists() else "queued", bytes=p.stat().st_size)
@@ -176,6 +177,63 @@ def reaper():
if prefect_up(): print("reaper:", e, flush=True)
UPLOAD_EXT = {".mp4", ".mkv", ".mov", ".webm", ".wav", ".m4a", ".mp3"}
def _find(o, k):
"""First value of key k anywhere in a nested JSON object."""
if isinstance(o, dict):
if k in o: return o[k]
o = list(o.values())
if isinstance(o, list):
for v in o:
if (r := _find(v, k)) is not None: return r
def slot():
"""Live llama-server state (/slots): proves a long LLM call is moving even between progress ticks."""
try: s = json.load(NOPROXY.open(f"http://127.0.0.1:{llama.PORT}/slots", timeout=1))
except Exception: return None
s = s[0] if isinstance(s, list) and s else {}
return {k: _find(s, k) for k in ("is_processing", "n_prompt_tokens", "n_prompt_tokens_processed", "n_decoded")}
def last_log(n):
"""Last meaningful line of out/<n>/flow.log: what a started-but-not-yet-tracked run is doing (e.g. uv downloading deps)."""
f = out / n / "flow.log"
try:
with open(f, "rb") as fh: fh.seek(max(0, f.stat().st_size - 4096)); tail = fh.read().decode("utf-8", "replace")
except OSError: return ""
lines = [l.strip() for l in tail.splitlines() if l.strip() and "UV_NATIVE_TLS" not in l]
return lines[-1][-160:] if lines else ""
def prog(n, dur):
"""Step plan, current-step fraction and ETA from out/<n>/progress.json + learned seconds-per-audio-minute."""
p = db.progress(n)
if not p or not p.get("step"): return None
now, mins = time.time(), (dur or 0) / 60
key = lambda s: f"{s}@{llama.current(s == 'shots')}" if s in ("shots", "report") else s
cur, el = p["step"], now - p["step_start"]
est = db.spm(p.get("key") or key(cur)) * mins
if p["total"] and p["done"]: # rate measured from the loop start (t0), not from the step start (model load etc.)
left, frac = (now - (p.get("t0") or p["step_start"])) / p["done"] * (p["total"] - p["done"]), p["done"] / p["total"]
else: left = max(est - el, 0.1 * est); frac = el / (el + left) if el + left else 0
o = db.ORDER; i0 = o.index(p["start"]) if p["start"] in o else 0
took = {s: e - b for s, b, e in p["steps"]}
plan = []
for s in o:
if o.index(s) < i0: plan.append({"s": s, "state": "skip"})
elif s == cur: plan.append({"s": s, "state": "run", "frac": round(frac, 3), "left": round(left), "secs": round(el)})
elif s in took: plan.append({"s": s, "state": "done", "secs": round(took[s])})
else: plan.append({"s": s, "state": "todo", "est": round(db.spm(key(s)) * mins)})
eta = left + sum(x.get("est", 0) for x in plan if x["state"] == "todo") if mins else None
tot = now - p["run_start"]
return {"step": cur, "note": p["note"], "done": p["done"], "total": p["total"], "frac": round(frac, 3), "step_left": round(left),
"eta": None if eta is None else round(eta), "elapsed": round(tot), "pct": round(tot / (tot + eta), 3) if eta else None,
"idle": round(now - p["updated"]), "plan": plan, "llm": slot() if cur in ("shots", "docs", "report", "memory") else None}
def status():
t = time.time(); rs = []
for r in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"):
@@ -183,6 +241,10 @@ def status():
d["receiving_age_s"] = round(t - R[n]["last"]) if n in R else None
d["files"] = [k for k, e in (*FILES, ("report.html", None)) if ((out / n / "report.html") if e is None else (out / f"{n}{e}")).exists()]
j = JOBS.get(n); d["running"] = bool(j and j.poll() is None); d["title"] = title(n)
up = out / n / "upload.json"
if up.exists(): d["upload"] = json.loads(up.read_text(encoding="utf-8")).get("filename")
d["prog"] = prog(n, d["duration_s"]) if d["running"] or d["status"] in db.ORDER else None
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) + bool(BATCH and BATCH.is_alive()),
@@ -260,8 +322,32 @@ th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;lett
.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)}
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}
td button,td select{margin:0 4px 4px 0}#qs{color:var(--mut)}</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><select id=fa title="passo da cui ripartire"><option value=audio>da zero (audio)</option><option value=report>da report</option><option value=render>solo render</option></select><button class=pri id=ra onclick=runAll()>Rielabora tutte</button></div></header>
td button,td select{margin:0 4px 4px 0}#qs{color:var(--mut)}
.pg{padding:14px 16px 12px;background:var(--soft);border:1px solid var(--line);border-radius:12px;margin:0 0 8px}
.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)}
.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}
.bar{height:12px;background:var(--line);border-radius:99px;overflow:hidden}.bar.thin{height:6px;margin-top:10px}
.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}}
.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%}}
.steps{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
.st{font-size:12px;padding:3px 10px;border-radius:99px;background:var(--card);border:1px solid var(--line);color:var(--mut);white-space:nowrap}
.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}}
.sub{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:6px;font-size:12.5px;color:var(--mut)}
.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.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}
#ub{position:sticky;top:12px;z-index:5}#ub .pgh{margin-bottom:10px}
body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14px}
#hint{color:var(--mut);font-size:12.5px}
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}</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><select id=fa title="passo da cui ripartire"><option value=audio>da zero (audio)</option><option value=report>da report</option><option value=render>solo render</option></select><button id=ra onclick=runAll()>Rielabora tutte</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>
<div class=bar><i id=ubar></i></div><div class=sub><span id=utxt></span></div></div></div>
<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"><button class=pri id=ab onclick=ask()>Chiedi</button></div><div id=ar></div></div>
<div class="card t"><table id=t></table></div></main>
@@ -289,17 +375,64 @@ const sel={};
async function redo(n){if(!confirm(`Rielaborare da zero ${n}?`))return;const r=await fetch(`/run?name=${n}&from=audio`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()}
async function runAll(){if(!confirm(`Rielaborare TUTTE le registrazioni da "${fa.value}"? Una alla volta, può richiedere ore.`))return;
const r=await fetch("/run_all?from="+fa.value,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
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 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()}
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"};
const clock=s=>new Date(Date.now()+s*1000).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});
const LT={};
function live(n,p){const l=p.llm;let txt="",act=false;
if(l&&l.is_processing){act=true;const k=n,prev=LT[k],now=Date.now(),d=l.n_decoded||0;
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`;
LT[k]=[now,d]}
const idle=p.idle,cls=act||idle<90?"":idle<300?"warn":"bad";
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>`}
function progPanel(r){const p=r.prog;
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>`;
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>`:"";
const pct=p.pct!=null?Math.round(p.pct*100):null,cur=p.plan.find(x=>x.state=="run");
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("");
const cnt=p.total?`${p.done} di ${p.total}`:"",step=LBL[p.step]||p.step;
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>
<div class="bar${pct==null?" ind":""}"><i style="width:${pct||0}%"></i></div>
<div class=steps>${chips}</div>
<div class="bar thin"><i style="width:${Math.round(p.frac*100)}%"></i></div>
<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()}
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%";
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)}`};
x.upload.onload=()=>{utxt.textContent="File ricevuto: controllo del formato e avvio dell'elaborazione…"};
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()};
x.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
ucancel.onclick=()=>{x.abort();ub.hidden=true};
x.open("POST","/upload?filename="+encodeURIComponent(f.name));x.send(f)}
up.onchange=()=>{if(up.files[0])send(up.files[0]);up.value=""};
addEventListener("dragover",e=>{e.preventDefault();document.body.classList.add("drag")});
addEventListener("dragleave",e=>{if(!e.relatedTarget)document.body.classList.remove("drag")});
addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("drag");const f=e.dataTransfer.files[0];if(f)send(f)});
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.map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.disabled=j.busy}
ra.disabled=j.queue>0;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>";
for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status;
h+=`<tr><td>${r.title?`<b>${E(r.title)}</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}
const nm=r.title||r.upload;
h+=`<tr><td>${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}
<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 class=pri onclick="redo('${r.name}')">Rielabora</button><button onclick="spk('${r.name}')">speakers</button>${r.running?`<button onclick="stopRun('${r.name}')">stop</button>`:""}`;
<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 class=pri onclick="redo('${r.name}')">Rielabora</button><button onclick="spk('${r.name}')">speakers</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(!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);
@@ -342,6 +475,7 @@ class H(BaseHTTPRequestHandler):
else: self._send(b"not found", 404)
def do_POST(self):
u = urlparse(self.path); q = {k: v[0] for k, v in parse_qs(u.query).items()}; name = Path(q.get("name", "x")).name
if u.path == "/upload": return self.upload(q)
data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if u.path == "/chunk":
with open(out / f"{name}.webm", "ab") as f: f.write(data)
@@ -359,6 +493,11 @@ class H(BaseHTTPRequestHandler):
db.upsert_recording(name, ended_at=now(), status="queued")
launch(name, "audio")
self._send("in coda: apri http://127.0.0.1:18765/".encode())
elif u.path == "/delete":
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return self._send(b"not found", 404)
j = JOBS.get(name)
if (j and j.poll() is None) or name in R or name 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 == "/cancel":
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
elif u.path == "/run":
@@ -380,6 +519,23 @@ class H(BaseHTTPRequestHandler):
if launch(name, "render"): self._send(b"salvato, render avviato")
else: self._send("salvato, render dopo il job in corso".encode(), 202)
else: self._send(b"not found", 404)
def upload(self, q):
fn = Path(q.get("filename", "")).name; ext = Path(fn).suffix.lower(); n = int(self.headers.get("Content-Length", 0))
if ext not in UPLOAD_EXT: return self._send(f"formato non supportato: {ext or '?'} (usa {', '.join(sorted(UPLOAD_EXT))})".encode(), 400)
if not n: return self._send("file vuoto".encode(), 400)
name = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S")
dst = out / f"{name}{ext}"; tmp = out / f"{name}{ext}.part"; left = n
with open(tmp, "wb") as f:
while left and (b := self.rfile.read(min(1 << 20, left))): f.write(b); left -= len(b)
if left: tmp.unlink(missing_ok=True); return self._send("upload interrotto".encode(), 400)
tmp.replace(dst)
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(dst)], capture_output=True, text=True)
try: dur = float(r.stdout.strip())
except ValueError: dst.unlink(); return self._send("file non leggibile da ffprobe (né audio né video)".encode(), 400)
(db.out_dir(name) / "upload.json").write_text(json.dumps({"filename": fn}, ensure_ascii=False), encoding="utf-8")
db.upsert_recording(name, source="upload", started_at=now(), status="queued", bytes=n, duration_s=dur)
launch(name, "audio")
self._json({"name": name, "duration_s": dur})
def log_message(self, fmt, *x):
if os.environ.get("LOG_LEVEL", "INFO").upper() == "DEBUG": print(fmt % x, flush=True)
+4 -1
View File
@@ -126,6 +126,7 @@ def run(name, max_frames=60, scene=0.05):
sd = d / "shots"
sd.mkdir(exist_ok=True)
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
db.tick(name, 0, 0, "estrazione dei fotogrammi dal video")
kept = [] # (t, path, hash)
bars = _bars(video, (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [0])[0] or 0)
for t in _times(video, scene, bars):
@@ -143,10 +144,12 @@ def run(name, max_frames=60, scene=0.05):
if i not in keep: k[1].unlink()
kept = [kept[i] for i in keep]
db.tick(name, 0, len(kept), "avvio del modello di visione")
srv = llama.start(log=d / "llama.log") # None if already running
rows = []
try:
for t, p, _ in kept:
for i, (t, p, _) in enumerate(kept):
db.tick(name, i, len(kept), f"schermata {i + 1} di {len(kept)} ({int(t) // 60:02d}:{int(t) % 60:02d})")
r = read_shot(p); _augment(r)
r["view"] = _view(p, r.pop("content_box", None))
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True)
+8 -4
View File
@@ -39,14 +39,16 @@ def _decode(path):
return np.frombuffer(raw, np.float32)
def _cuda(audio, model, glossary):
def _cuda(audio, model, glossary, tick=lambda done, total: None):
import common
m, dev = common.load_model(model)
# ponytail: >~20 hotwords crowd whisper's prompt -> dropped text + repetition loops (seen with 60)
kw = {"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False} if glossary else {}
try:
segs, _ = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
return [(s.start, s.end, s.text) for s in segs], dev
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
out = []
for s in segs: out.append((s.start, s.end, s.text)); tick(s.end, info.duration)
return out, dev
finally:
del m; gc.collect()
@@ -75,9 +77,11 @@ def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path |
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
t0 = time.time()
if device == "npu":
db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)")
segs, used = _npu(audio), "npu"
else:
segs, used = _cuda(audio, model, glossary)
tick = lambda done, total: db.tick(name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio")
segs, used = _cuda(audio, model, glossary, tick)
lines = aggregate(segs)
txt = "\n".join(f"[{t//60:02d}:{t%60:02d}] {x}" for t, x in lines)
for l in txt.splitlines(): _log(l)