From a64d3fb275a4b84e6618cb93f2cd5de6946808dc Mon Sep 17 00:00:00 2001 From: pinokio Date: Mon, 2 Nov 2026 15:20:19 +0100 Subject: [PATCH] Hardware-aware install, per-step LLM profiles, tuned llama.cpp for 4 GB VRAM Benchmarked on RTX 500 Ada 4 GB (~3.2 GB usable on Windows) + Core Ultra 7 155H. - install.js: log GPU/VRAM/RAM, abort without NVIDIA >= 4 GB VRAM; always install Qwen3.5-4B Q4_K_S, Qwen3.6-35B-A3B only with >= 48 GB RAM. - llama.py: model registry with vision (shots) and text (report/ask) profiles; KV q8, image tokens 1024-1536. - 35B: vision encoder on GPU, -ngl 30 (shot 142 -> ~50 s); text: -ub 2048. - 4B: vision encoder on GPU, FFN of layers 19-31 in RAM (shot 36 -> 22 s); text fully on GPU (~30 tok/s, report 4.5 min). - Per-step choice in out/llm.txt: default 4B for shots, biggest for report. - flow.py: restart llama in text profile after shots (no mmproj for report). - shots.py: prompt v3 (inline template + defined fields, Italian summary rules) and bounded json_schema; stops 4B loops, title 1/38 -> 36/38. - server.py: shots/report model selects, POST /cancel + stop button, reaper thread that honours Prefect "Cancel" and closes runs whose process died. - diarize.py: cut same-speaker paragraphs every 60 s (one 11-min paragraph truncated every report at 28:52); 8 threads; CUDA provider with CPU fallback via sherpa-onnx cuda12.cudnn9 wheel (CUDA path not yet verified). Co-Authored-By: Claude Opus 5.5 --- README.md | 17 +++++++ app/diarize.py | 30 ++++++----- app/flow.py | 22 ++++++--- app/llama.py | 47 +++++++++++++++--- app/report.py | 20 ++++++-- app/server.py | 132 ++++++++++++++++++++++++++++++++++++++++++++----- app/shots.py | 34 ++++++++++--- install.js | 29 ++++++++++- pinokio.js | 2 +- start.js | 2 + 10 files changed, 285 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 3d35056..46db0c6 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,21 @@ audio cleanup (ffmpeg) → transcription (faster-whisper CUDA, or OpenVINO NPU) Orchestrated by Prefect; everything runs locally. Windows + NVIDIA GPU (fits 4 GB VRAM: MoE experts run on CPU). +## Requirements + +| | Minimum | Recommended | +|---|---|---| +| OS | Windows 10/11 x64 | | +| GPU | NVIDIA, 4 GB VRAM, driver R580+ (CUDA 13) | 8–12 GB VRAM | +| RAM | 32 GB: installs only Qwen3.5 4B (fully in VRAM) | 48+ GB: also Qwen3.6 35B-A3B (MoE experts in RAM); pick the LLM in the Web UI header | +| CPU | x64, 6–8 cores (runs the MoE experts) | more cores = faster reports | +| Disk | ~10 GB free (32 GB RAM) / ~35 GB (48+ GB RAM), SSD | NVMe | +| Browser | Chrome or Edge (extension); Edge for PDF export | | + +Install logs the detected GPU/VRAM/RAM and aborts without an NVIDIA GPU with 4+ GB VRAM. + +Optional: Intel NPU (Core Ultra) for OpenVINO Whisper; `twg` + company proxy for the docs step. Not supported: AMD/Intel-only GPUs, macOS, Linux. + ## Install Click **Install**. It downloads ffmpeg, llama.cpp (CUDA 13), the diarization models, bge-m3 and the Qwen GGUF (~23 GB) into `app/bin` and `app/models`, and pre-builds the `uv` script environments. @@ -15,6 +30,7 @@ Click **Install**. It downloads ffmpeg, llama.cpp (CUDA 13), the diarization mod 1. Click **Start**: GUI on http://127.0.0.1:18765/, Prefect dashboard on http://127.0.0.1:4200. 2. Click **Extension** to open `app/ext`, then in Chrome/Edge: `chrome://extensions` → Developer mode → **Load unpacked** → select that folder (once). 3. In a Teams web call, click the extension icon → record. On stop, the pipeline runs and the report appears in the GUI. +4. **Rielabora** on a row reruns that meeting from scratch; **Rielabora tutte** (top right of the GUI) reruns every recording sequentially: *da zero* (full pipeline), *da report* (new summaries), *solo render* (restyle reports only). Alternative without the extension (desktop Teams, system loopback + mic): `cd app && uv run meet.py [--screen]`, Ctrl+C to stop. @@ -42,6 +58,7 @@ Base URL `http://127.0.0.1:18765`. | POST | `/events` | `name`, body = JSON array of Teams call events | | POST | `/stop` | `name` → finalize recording, start pipeline | | POST | `/run` | `name`, `from`, `speakers` → rerun pipeline | +| POST | `/run_all` | `from` → rerun every recording one at a time, oldest first (GUI: **Rielabora tutte**) | | POST | `/speaker_map` | `name`, body = `{"Speaker 1": "Mario Rossi"}` → re-render | ### curl diff --git a/app/diarize.py b/app/diarize.py index fa6e3c9..0d37b4d 100644 --- a/app/diarize.py +++ b/app/diarize.py @@ -1,10 +1,11 @@ -"""Label who speaks (CPU, sherpa-onnx): run(name) -> out/.spk.txt, diar_segments.json, DB lines.""" -import json, re, subprocess +"""Label who speaks (sherpa-onnx, CUDA with CPU fallback): run(name) -> out/.spk.txt, diar_segments.json, DB lines.""" +import json, re, subprocess, time from pathlib import Path import numpy as np -import db +import common, db # common: puts the pip nvidia-* CUDA DLLs on PATH M = Path(__file__).parent / "models" +THREADS = 8 # CPU fallback; sherpa-onnx default is 1 thread: a 40-min call took >10 min def run(name, speakers=5, threshold=0.85): @@ -13,14 +14,19 @@ def run(name, speakers=5, threshold=0.85): raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"], capture_output=True, check=True).stdout audio = np.frombuffer(raw, np.float32) - sd = sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig( - segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig( - pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx"))), - embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx")), - clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold), - min_duration_on=0.3, min_duration_off=0.5)) + def diarizer(provider): + return sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig( + segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig( + pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")), + num_threads=THREADS, provider=provider), + embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS, provider=provider), + clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold), + min_duration_on=0.3, min_duration_off=0.5)) + t0 = time.time() + try: sd, used = diarizer("cuda"), "cuda" # CUDA build: sherpa-onnx==...+cuda12.cudnn9 (flow.py deps) + except Exception as e: print("diarize: CUDA unavailable, using CPU:", e, flush=True); sd, used = diarizer("cpu"), "cpu" segs = [(s.start, s.end, s.speaker) for s in sd.process(audio).sort_by_start_time()] - print(len(segs), "segments,", len({s[2] for s in segs}), "speakers", flush=True) + print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({used}, {time.time() - t0:.0f} s)", flush=True) lines = [] for l in (db.OUT / f"{name}.txt").read_text(encoding="utf-8").splitlines(): @@ -35,7 +41,9 @@ def run(name, speakers=5, threshold=0.85): if o > 0: ov[sp] = ov.get(sp, 0) + o sp = max(ov, key=ov.get) if ov else None if sp is not None: order.setdefault(sp, len(order) + 1) - if out and out[-1][1] == sp: out[-1][2] += " " + text # same speaker continues: one paragraph + # same speaker continues: one paragraph, but cut every 60 s so the timestamps stay usable (one 11-min paragraph + # stamped 28:52 made every model end the report there) + if out and out[-1][1] == sp and t - out[-1][0] < 60: out[-1][2] += " " + text else: out.append([t, sp, text]) # labels by first appearance in the text; clusters never seen in text get the following numbers for s in sorted(segs): diff --git a/app/flow.py b/app/flow.py index d9ddb55..6e35f40 100644 --- a/app/flow.py +++ b/app/flow.py @@ -1,12 +1,16 @@ # /// script # requires-python = ">=3.10,<3.13" -# dependencies = ["prefect>=3", "faster-whisper", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"] +# dependencies = ["prefect>=3", "faster-whisper", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "nvidia-cuda-runtime-cu12", "nvidia-cufft-cu12", "sherpa-onnx==2.0.1+cuda12.cudnn9", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"] +# [tool.uv] +# find-links = ["https://k2-fsa.github.io/sherpa/onnx/cuda.html"] # sherpa-onnx CUDA wheels (diarization on GPU, CPU fallback in diarize.py) # /// """Meeting pipeline. uv run --script flow.py [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]""" import os os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api") os.environ["NO_PROXY"] = "127.0.0.1,localhost" os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false" +os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper()) +os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI import argparse, sys from pathlib import Path from prefect import flow, task @@ -52,19 +56,21 @@ def t_memory(name): step_status(name, "memory"); memory.run(name) class Llama: - """Start llama-server once, terminate in close() only if we started it.""" - def __init__(self, name): self.name, self.p = name, None - def ensure(self): - log = db.out_dir(self.name) / "llama.log" + """Start llama-server in vision (shots) or text (report) profile; switching restarts it. Terminate in close() only if we started it.""" + def __init__(self, name): self.name, self.p, self.vision = name, None, None + def ensure(self, vision=True): + if self.p and self.vision != vision: self.close() + self.vision = vision + log = db.out_dir(self.name) / ("llama.log" if vision else "llama_text.log") try: - p = llama.start(log=log) + p = llama.start(vision=vision, log=log) except Exception: if log.exists() and "out of memory" in log.read_text(errors="replace"): raise RuntimeError("GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'") raise self.p = self.p or p def close(self): - if self.p and self.p.poll() is None: self.p.terminate() + if self.p and self.p.poll() is None: self.p.terminate(); self.p.wait() # wait: port must be free before a profile switch self.p = None @@ -108,8 +114,8 @@ 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() 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") diff --git a/app/llama.py b/app/llama.py index 8f1c9f3..7cb6dda 100644 --- a/app/llama.py +++ b/app/llama.py @@ -1,13 +1,45 @@ import subprocess, time, urllib.request from pathlib import Path -SERVER = Path(__file__).parent / "bin" / "llama-server.exe" -MD = Path(__file__).parent / "models" -MODEL, MMPROJ = MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf" +HERE = Path(__file__).parent +SERVER = HERE / "bin" / "llama-server.exe" +MD = HERE / "models" +CHOICE = HERE / "out" / "llm.txt" # GUI header: " " +# Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02. +_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop +_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster +# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch)) +MODELS = { + # MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention + # 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]), + # 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]), +} PORT = 18081 -EMBED, EMBED_PORT = Path(__file__).parent / "models" / "bge-m3-Q8_0.gguf", 18082 +EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082 _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost +def available(): return [k for k, m in MODELS.items() if m[1].exists()] + +def current(vision=True): + """Model for shots (vision) or report/ask (text): GUI choice if on disk, else 4B for shots (VRAM-only, near-35B shots) + and the biggest model for reports (4B reports lose structure on long transcripts).""" + ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""] + k = ks[0] if vision else ks[-1] # a single key (old format) applies to both + av = available() + if k in av: return k + if vision and "qwen4b" in av: return "qwen4b" + return (av or ["qwen4b"])[0] + +def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}") + def up(port=PORT): try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True except Exception: return False @@ -21,9 +53,10 @@ def _spawn(args, port, log): time.sleep(2) raise TimeoutError("llama-server not ready") -def start(model=MODEL, mmproj=MMPROJ, port=PORT, log="llama.log"): - """Start llama-server (attention on GPU, MoE experts on CPU: fits 4 GB). None if already running.""" - return _spawn(["-m", str(model), "--mmproj", str(mmproj), "-ngl", "99", "--cpu-moe", "-c", "16384", "--jinja"], port, log) +def start(vision=True, port=PORT, log="llama.log"): + """Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running.""" + _, model, mmproj, vargs, targs = MODELS[current(vision)] + return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log) def start_embed(log="embed.log"): """bge-m3 embeddings on CPU (never competes with the GPU model). None if already running.""" diff --git a/app/report.py b/app/report.py index aa7af49..d4ee5e4 100644 --- a/app/report.py +++ b/app/report.py @@ -29,7 +29,7 @@ def secs(s): def chat(system, user, max_tokens, retries=2): - body = {"model": str(llama.MODEL), "temperature": 0.2, "max_tokens": max_tokens, + body = {"model": llama.current(False), "temperature": 0.2, "max_tokens": max_tokens, "chat_template_kwargs": {"enable_thinking": False}, "response_format": {"type": "json_object"}, "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]} for _ in range(retries): @@ -399,5 +399,19 @@ def render(name): body = markdown.markdown(text, extensions=["tables", "toc", "md_in_html"]) body = re.sub(r'src="shots/([^"]+)"', lambda m: 'src="data:image/jpeg;base64,' + base64.b64encode((d / "shots" / m[1]).read_bytes()).decode() + '"', body) h1 = re.sub(r"[#]+ ", "", md[0]) - css = "body{max-width:1000px;margin:auto;font:15px system-ui;padding:20px} img{width:100%;border:1px solid #ccc} table{border-collapse:collapse} td,th{border:1px solid #ccc;padding:4px 8px} details{margin-top:20px}" - (d / "report.html").write_text(f'{h1}\n{body}', encoding="utf-8") + css = """:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442} +@media screen and (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757}} +*{box-sizing:border-box}body{max-width:860px;margin:auto;padding:56px 24px 96px;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif} +h1,h2{font-family:ui-serif,Georgia,"Times New Roman",serif;font-weight:500;line-height:1.25;letter-spacing:-.01em} +h1{font-size:2.2em;margin:0 0 .2em}h1+p{color:var(--mut);margin-top:0} +h2{font-size:1.5em;margin:2em 0 .6em;padding-top:1em;border-top:1px solid var(--line)} +h3{font-size:.78em;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--mut);margin:1.8em 0 .4em} +a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline} +ul,ol{padding-left:1.4em}li{margin:.3em 0}li::marker{color:var(--acc)} +#in-breve{border-top:0}#in-breve+ul{background:var(--soft);border-left:3px solid var(--acc);border-radius:10px;padding:16px 20px 16px 2.4em} +table{border-collapse:separate;border-spacing:0;width:100%;background:var(--card);border:1px solid var(--line);border-radius:12px;overflow:hidden;font-size:.92em} +td,th{padding:9px 14px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tr:last-child td{border-bottom:0}th{background:var(--soft);font-weight:600} +img{width:100%;border:1px solid var(--line);border-radius:12px;margin-top:.8em}p>em{color:var(--mut);font-size:.88em} +details{margin-top:2.4em;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 18px}summary{cursor:pointer;color:var(--acc);font-weight:500} +code{background:var(--soft);border-radius:5px;padding:.1em .35em;font-size:.9em}""" + (d / "report.html").write_text(f'{h1}\n{body}', encoding="utf-8") diff --git a/app/server.py b/app/server.py index cd7f816..feb4df9 100644 --- a/app/server.py +++ b/app/server.py @@ -28,6 +28,9 @@ FILES = (("txt", ".txt"), ("spk.txt", ".spk.txt")) EDGE = Path(os.path.expandvars(r"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe")) PRINT_CSS = "@media print{body{max-width:none;padding:0}img,tr{break-inside:avoid}h2,h3{break-after:avoid}}" LOCK = threading.Lock() +STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"] +QUEUE = [] # names waiting for the batch re-run, oldest first +BATCH = None # batch thread def make_pdf(name): @@ -50,7 +53,7 @@ def ask_once(q): with LOCK: own = [] try: - own = [p for p in (llama.start_embed(log=out / "embed.log"), llama.start(log=out / "llama.log")) if p is not None] + own = [p for p in (llama.start_embed(log=out / "embed.log"), llama.start(vision=False, log=out / "llama.log")) if p is not None] return memory.ask(q) finally: for p in own: p.terminate() @@ -69,6 +72,24 @@ def launch(name, start_from, speakers=5): return True +def batch(start_from): + """Re-run every queued recording one at a time (one GPU), oldest first so memory links point backwards.""" + while QUEUE: + n = QUEUE.pop(0) + j = JOBS.get(n) + if j: j.wait() + launch(n, start_from); JOBS[n].wait() + + +def run_all(start_from): + global BATCH + if BATCH and BATCH.is_alive(): return False + QUEUE[:] = [r[0] for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name")] + for n in QUEUE: db.set_status(n, "queued") + BATCH = threading.Thread(target=batch, args=(start_from,), daemon=True); BATCH.start() + return True + + def prefect_up(): try: NOPROXY.open(PREFECT + "/api/health", timeout=2); return True except Exception: return False @@ -103,7 +124,56 @@ def title(n): return TITLES[n][1] -def busy(): return any(p.poll() is None for p in JOBS.values()) +def busy(): return bool(BATCH and BATCH.is_alive()) or any(p.poll() is None for p in JOBS.values()) + + +def flow_pids(name=None): + """PIDs of the top `uv run --script flow.py ` processes (also flows started before a server restart).""" + r = subprocess.run(["powershell", "-NoProfile", "-c", "Get-CimInstance Win32_Process -Filter \"Name='uv.exe'\" | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"], + capture_output=True, text=True) + return {int(l.split()[0]): l for l in r.stdout.splitlines() if "flow.py" in l and (name is None or f" {name} " in l + " ")} + + +def prefect_state(run_id, typ, msg): + body = json.dumps({"state": {"type": typ, "name": typ.title(), "message": msg}, "force": True}).encode() + try: NOPROXY.open(urllib.request.Request(f"{PREFECT}/api/flow_runs/{run_id}/set_state", body, {"Content-Type": "application/json"}), timeout=5) + except Exception as e: print("prefect set_state failed:", e, flush=True) + + +def cancel(name, reason="cancelled from web UI"): + """Kill the flow's process tree (uv -> python -> llama-server) and close its Prefect run.""" + if name in QUEUE: QUEUE.remove(name) + j = JOBS.get(name) + pids = {j.pid} if j and j.poll() is None else set() + for pid in pids | set(flow_pids(name)): subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) + r = db.connect().execute("SELECT flow_run_id FROM recordings WHERE name=?", (name,)).fetchone() + if r and r[0]: prefect_state(r[0], "CANCELLED", reason) + db.set_status(name, "cancelled", reason) + return bool(pids) + + +def reaper(): + """Prefect cannot stop flows it did not launch: honour 'Cancel' from its UI and close runs whose process died.""" + while True: + time.sleep(5) + try: + body = json.dumps({"flow_runs": {"state": {"type": {"any_": ["RUNNING", "PENDING", "CANCELLING"]}}}}).encode() + runs = json.load(NOPROXY.open(urllib.request.Request(f"{PREFECT}/api/flow_runs/filter", body, {"Content-Type": "application/json"}), timeout=5)) + if not runs: continue + by_id = {r[1]: r[0] for r in db.connect().execute("SELECT name, flow_run_id FROM recordings WHERE flow_run_id IS NOT NULL")} + live = flow_pids() + for fr in runs: + name = by_id.get(fr["id"]) + if fr["state_type"] == "CANCELLING": + if name: cancel(name, "cancelled from Prefect UI") + else: prefect_state(fr["id"], "CANCELLED", "cancelled from Prefect UI") + # unknown id: a just-started flow may not have written flow_run_id yet -> only reap when no flow runs at all + elif (name and not any(f" {name} " in l + " " for l in live.values())) or (not name and not live): + prefect_state(fr["id"], "CRASHED", "flow process is gone (killed or crashed)") + if name and db.connect().execute("SELECT status FROM recordings WHERE name=?", (name,)).fetchone()[0] not in ("done", "error", "cancelled"): + db.set_status(name, "error", "flow process is gone (killed or crashed)") + except Exception as e: + if prefect_up(): print("reaper:", e, flush=True) def status(): @@ -115,7 +185,8 @@ def status(): j = JOBS.get(n); d["running"] = bool(j and j.poll() is None); d["title"] = title(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()} + return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE) + bool(BATCH and BATCH.is_alive()), + "llm": [llama.current(True), llama.current(False)], "llms": [[k, llama.MODELS[k][0]] for k in llama.available()]} def fts(sql, q): @@ -169,11 +240,31 @@ def add_events(name, items): PAGE = """Meetings - -

Meetings

-

+ +

Riunioni

+
+
+