From cbe111bc344e03bfda3f90bad65cab238c0c04f2 Mon Sep 17 00:00:00 2001 From: Stefano Zini Date: Mon, 2 Nov 2026 17:23:40 +0100 Subject: [PATCH] GUI: upload, live progress + ETA, delete; report thinking; docs twg fix Co-Authored-By: Claude Opus 5.5 --- app/db.py | 78 ++++++++++++++++++++- app/diarize.py | 2 + app/docs.py | 4 ++ app/flow.py | 11 ++- app/llama.py | 7 +- app/report.py | 51 +++++++++++--- app/server.py | 168 ++++++++++++++++++++++++++++++++++++++++++++-- app/shots.py | 5 +- app/transcribe.py | 12 ++-- 9 files changed, 309 insertions(+), 29 deletions(-) diff --git a/app/db.py b/app/db.py index fc9c43b..7c86ebf 100644 --- a/app/db.py +++ b/app/db.py @@ -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//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 "" or "@") +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// and out/.* 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): diff --git a/app/diarize.py b/app/diarize.py index 5e5cb65..cefe437 100644 --- a/app/diarize.py +++ b/app/diarize.py @@ -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) diff --git a/app/docs.py b/app/docs.py index ea5b6b1..77b8a51 100644 --- a/app/docs.py +++ b/app/docs.py @@ -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: "" + 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} diff --git a/app/flow.py b/app/flow.py index 6254c72..e0468e2 100644 --- a/app/flow.py +++ b/app/flow.py @@ -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) diff --git a/app/llama.py b/app/llama.py index 8ee508a..c30c231 100644 --- a/app/llama.py +++ b/app/llama.py @@ -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): diff --git a/app/report.py b/app/report.py index fda762b..7bb036f 100644 --- a/app/report.py +++ b/app/report.py @@ -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() diff --git a/app/server.py b/app/server.py index feb4df9..9579d96 100644 --- a/app/server.py +++ b/app/server.py @@ -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//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//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)} -

Riunioni

+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)} +

Riunioni

+
+
Trascina qui un video o un audio di una riunione per elaborarlo.
+
@@ -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: ${d} token${tps?` · ${tps.toFixed(1)} token/s`:""}`} +else txt=`Il modello sta leggendo il contesto: ${l.n_prompt_tokens_processed||0} 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 ${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}
`} +function progPanel(r){const p=r.prog; +if(!p&&r.running)return `
…  Avvio della pipeline — preparazione dell'ambiente Python (la prima volta scarica le dipendenze: qualche minuto)
${E(r.boot||"in avvio…")}
`; +if(!p)return r.status=="queued"?`
In codaparte appena finisce l'elaborazione in corso
`:""; +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"?`${LBL[x.s]}`:x.state=="done"?`✓ ${LBL[x.s]} · ${dur(x.secs)}`:x.state=="run"?`● ${LBL[x.s]} · ${Math.round(x.frac*100)}%`:`${LBL[x.s]} · ~${dur(x.est)}`).join(""); +const cnt=p.total?`${p.done} di ${p.total}`:"",step=LBL[p.step]||p.step; +return `
+
${pct!=null?pct+"%":"…"}  ${step} — ${E(p.note||HOW[p.step]||"")} +${p.eta!=null?`fine prevista ~${clock(p.eta)} · mancano ${dur(p.eta)} · `:""}trascorso ${dur(p.elapsed)}
+
+
${chips}
+
+
${step}: ${cnt?cnt+" · ":""}${Math.round(p.frac*100)}%${cur?`questo passo: ancora ~${dur(cur.left)} (in corso da ${dur(cur.secs)})`:""}
+${live(r.name,p)}
`} +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])=>`