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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4ff3e6fe14
commit
a64d3fb275
@@ -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
|
||||
|
||||
+19
-11
@@ -1,10 +1,11 @@
|
||||
"""Label who speaks (CPU, sherpa-onnx): run(name) -> out/<name>.spk.txt, diar_segments.json, DB lines."""
|
||||
import json, re, subprocess
|
||||
"""Label who speaks (sherpa-onnx, CUDA with CPU fallback): run(name) -> out/<name>.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):
|
||||
|
||||
+14
-8
@@ -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 <name> [--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")
|
||||
|
||||
+40
-7
@@ -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: "<shots model> <report model>"
|
||||
# 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."""
|
||||
|
||||
+17
-3
@@ -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'<!doctype html><meta charset="utf-8"><title>{h1}</title><style>{css}</style>\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'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{h1}</title><style>{css}</style>\n{body}', encoding="utf-8")
|
||||
|
||||
+121
-11
@@ -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 <name>` 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 = """<!doctype html><meta charset=utf-8><title>Meetings</title>
|
||||
<style>body{font:14px system-ui;margin:20px;background:#111;color:#ddd}table{border-collapse:collapse;width:100%}td,th{padding:6px 10px;border-bottom:1px solid #333;text-align:left;vertical-align:top}
|
||||
.b{padding:2px 8px;border-radius:9px;background:#555}.recording{background:#c33}.queued{background:#668}.audio,.transcribing,.diarizing,.identifying,.shots,.docs,.report,.memory{background:#c80}.done{background:#2a5}.error{background:#833}
|
||||
a{color:#7af;cursor:pointer;margin-right:8px}button,select,input{margin-right:4px}#q{width:300px}small{color:#999}.sp{background:#1a1a1a}</style>
|
||||
<h2>Meetings</h2><p><input id=q placeholder="search speech + screen"><button onclick=srch()>search</button></p><div id=sr></div>
|
||||
<p><input id=qa placeholder="chiedi alle riunioni" style="width:300px"><button id=ab onclick=ask()>chiedi</button></p><div id=ar></div><table id=t></table>
|
||||
<style>
|
||||
:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442;--acc2:#b05535;--on:#fff;
|
||||
--red:#f6e0dc;--redf:#a33a2a;--amb:#f7ecd6;--ambf:#8a5a12;--grn:#e2eedf;--grnf:#3d6b35;--gry:#ebe9e1;--gryf:#5e5d57}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757;--acc2:#e58a6c;--on:#1f1e1d;
|
||||
--red:#4a2b26;--redf:#f0a597;--amb:#4a3d24;--ambf:#ecc77f;--grn:#2d3f2a;--grnf:#a8d39c;--gry:#3a3a35;--gryf:#c2c0b6}}
|
||||
*{box-sizing:border-box}body{font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;margin:0;padding:32px 24px 64px;background:var(--bg);color:var(--fg)}
|
||||
main{max-width:1200px;margin:auto}header{display:flex;align-items:end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px}
|
||||
h1{font:500 30px/1.2 ui-serif,Georgia,"Times New Roman",serif;letter-spacing:-.01em;margin:0}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:16px}
|
||||
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.row+.row{margin-top:10px}.row input{flex:1;min-width:220px}
|
||||
input,select,button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:6px 10px}
|
||||
input:focus,select:focus{outline:2px solid var(--acc);outline-offset:-1px}
|
||||
button{cursor:pointer;background:var(--soft)}button:hover{border-color:var(--mut)}button:disabled{opacity:.5;cursor:default}
|
||||
button.pri{background:var(--acc);border-color:var(--acc);color:var(--on)}button.pri:hover{background:var(--acc2)}
|
||||
#sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px}
|
||||
table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tr:last-child td{border-bottom:0}
|
||||
th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;letter-spacing:.05em}.card.t{padding:4px 8px;overflow-x:auto}
|
||||
.b{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:500;background:var(--gry);color:var(--gryf)}
|
||||
.recording,.error,.cancelled{background:var(--red);color:var(--redf)}.audio,.transcribing,.diarizing,.identifying,.shots,.docs,.report,.memory{background:var(--amb);color:var(--ambf)}.done{background:var(--grn);color:var(--grnf)}
|
||||
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>
|
||||
<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>
|
||||
<script>
|
||||
const E=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]));
|
||||
const fmt=s=>{s=Math.round(s);return String(Math.floor(s/60)).padStart(2,"0")+":"+String(s%60).padStart(2,"0")};
|
||||
@@ -195,13 +286,20 @@ j.rows.map(r=>`<div><b>${E(r.label)}</b> ${fmt(r.talk_s)} <input data-n="${n}" d
|
||||
async function saveSpk(n){const m={};document.querySelectorAll(`input[data-n="${n}"]`).forEach(i=>m[i.dataset.l]=i.value);
|
||||
const r=await fetch("/speaker_map?name="+n,{method:"POST",body:JSON.stringify(m)});alert(await r.text())}
|
||||
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 stopRun(n){if(!confirm(`Fermare ${n}?`))return;await fetch("/cancel?name="+n,{method:"POST"});tick()}
|
||||
async function setLlm(){const r=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
|
||||
async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.busy;ab.title=j.busy?"pipeline in corso":"";
|
||||
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}
|
||||
<td>${r.files.includes("report.html")?`<a href="/report?name=${r.name}" target=_blank>report</a><a href="/pdf?name=${r.name}" target=_blank>pdf</a>`:""}${r.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${r.flow_run_id}" target=_blank>prefect</a>`:""}
|
||||
<td><select id="f-${r.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(s=>`<option>${s}`).join("")}</select><button onclick="run('${r.name}')">run</button><button onclick="spk('${r.name}')">speakers</button>`;
|
||||
<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>`:""}`;
|
||||
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);
|
||||
@@ -261,9 +359,20 @@ 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 == "/cancel":
|
||||
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
|
||||
elif u.path == "/run":
|
||||
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 5))
|
||||
self._send(b"" if ok else "già in esecuzione".encode(), 200 if ok else 409)
|
||||
elif u.path == "/run_all":
|
||||
f = q.get("from", "audio")
|
||||
if f not in STEPS: return self._send(b"bad step", 400)
|
||||
self._send(b"") if run_all(f) else self._send("rielaborazione già in corso".encode(), 409)
|
||||
elif u.path == "/llm":
|
||||
ks = [q.get("shots"), q.get("report")]
|
||||
if not all(k in llama.available() for k in ks): return self._send(b"modello non installato", 400)
|
||||
if busy(): return self._send("pipeline in corso: cambia modello dopo".encode(), 409)
|
||||
llama.choose(*ks); self._send()
|
||||
elif u.path == "/speaker_map":
|
||||
try: m = json.loads(data)
|
||||
except ValueError: return self._send(b"bad json", 400)
|
||||
@@ -271,9 +380,10 @@ 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 log_message(self, *x): pass
|
||||
def log_message(self, fmt, *x):
|
||||
if os.environ.get("LOG_LEVEL", "INFO").upper() == "DEBUG": print(fmt % x, flush=True)
|
||||
|
||||
|
||||
db.connect(); backfill(); start_prefect()
|
||||
db.connect(); backfill(); start_prefect(); threading.Thread(target=reaper, daemon=True).start()
|
||||
print(f"listening http://127.0.0.1:{a.port}/", flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
|
||||
|
||||
+27
-7
@@ -7,11 +7,31 @@ _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # cor
|
||||
EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None}
|
||||
CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"}
|
||||
CROP_BOX = True
|
||||
PROMPT = ('/no_think Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"slide|code|terminal|browser|document|spreadsheet|diagram|dashboard|ticket|chat|video_tiles|other","title":str|null,"app":str|null,"summary":str,"text":str,"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}. '
|
||||
'summary: written in ITALIAN (never English), max 40 words, what is shown and why it matters. text: the important visible text copied verbatim (headings, bullet points, table rows, code lines, error messages, form values), max 1500 characters, line breaks kept; skip Teams UI chrome. '
|
||||
'Consider ONLY the shared screen content: ignore browser bookmarks bar, tab titles, OS taskbar, Teams toolbar, video tiles and captions for systems/terms/urls/numbers. '
|
||||
'systems: product/tool/service names; tickets: issue keys like ABC-123; numbers: business figures with their label; terms: technical words useful as a glossary. people: full names (first and last) on video tiles/name tags, never initials; presenter: name in a "Contenuto condiviso da"/"Content shared by" label; meeting_title only if visible. '
|
||||
'content_box: bounding box of the shared screen content (the presenter\'s screen, slide or application window, excluding Teams toolbar, video tiles and caption area) in 0-1000 coordinates relative to this image, null if nothing is shared. Use [] or null when absent. Never invent.')
|
||||
KINDS = ["slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket", "chat", "video_tiles", "other"]
|
||||
_S, _N, _L = {"type": "string", "maxLength": 300}, {"type": ["string", "null"], "maxLength": 200}, {"type": "array", "items": {"type": "string", "maxLength": 120}, "maxItems": 25}
|
||||
# json_schema -> llama.cpp grammar: valid JSON + valid kind every time (small models broke JSON / looped to max_tokens)
|
||||
SCHEMA = {"type": "object", "additionalProperties": False,
|
||||
"required": ["kind", "title", "app", "summary", "text", "entities", "people", "presenter", "meeting_title", "content_box"],
|
||||
"properties": {"kind": {"enum": KINDS}, "title": _N, "app": _N, "summary": _S, "text": {"type": "string", "maxLength": 1500}, # bounds stop the 4B looping on table rows
|
||||
"entities": {"type": "object", "additionalProperties": False, "required": ["systems", "tickets", "urls", "numbers", "terms"],
|
||||
"properties": {k: _L for k in ("systems", "tickets", "urls", "numbers", "terms")}},
|
||||
"people": _L, "presenter": _N, "meeting_title": _N,
|
||||
"content_box": {"anyOf": [{"type": "array", "items": {"type": "integer"}, "minItems": 4, "maxItems": 4}, {"type": "null"}]}}}
|
||||
# v3: v1's inline JSON template (the model never sees the grammar: v2 without it -> kind=video_tiles, title=null) + every field defined
|
||||
# (v1 left title undefined), summary rules in Italian (v1 'ITALIAN' got echoed). Text before image: image-first measured worse.
|
||||
PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"' + '|'.join(KINDS) + '","title":str|null,"app":str|null,"summary":str,"text":str,'
|
||||
'"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}\n'
|
||||
'Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles and captions, except for people/presenter/meeting_title.\n'
|
||||
'- kind: type of the shared content; video_tiles ONLY if no screen is shared (just participant videos), chat for a chat panel.\n'
|
||||
'- title: the visible heading of the shared content: slide title, page/document title, active browser tab title or window title (e.g. "Sprint Review Q3 - Backlog"). null only if no title is readable.\n'
|
||||
'- app: application or website shown (e.g. "Confluence", "Grafana", "Excel").\n'
|
||||
'- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori) e perché conta. Inizia direttamente con il contenuto.\n'
|
||||
'- text: important visible text copied verbatim (headings, bullets, table rows with values, code lines, errors, form values), max 1500 characters, keep line breaks.\n'
|
||||
'- entities.systems: every product/tool/service/platform name visible (e.g. GitLab, Grafana, Azure, PostgreSQL); tickets: issue keys like ABC-123; urls; numbers: business figures with their label; terms: technical words useful for a glossary.\n'
|
||||
'- people: full names (first and last) on video tiles/name tags, never initials. presenter: name in a "Contenuto condiviso da"/"Content shared by" label. meeting_title: the Teams meeting name (Teams window title bar or meeting header, never the title of the shared content); null if not visible.\n'
|
||||
'- content_box: bounding box of the shared screen area (excluding Teams toolbar, video tiles, captions) in 0-1000 coordinates of this image; null if nothing is shared.\n'
|
||||
'Never invent: use null or [] when absent.')
|
||||
|
||||
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
|
||||
URL = re.compile(r"""https?://[^\s)\]>"']+""")
|
||||
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
|
||||
@@ -19,11 +39,11 @@ EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
|
||||
|
||||
def _ask(path, json_mode=True):
|
||||
img = base64.b64encode(path.read_bytes()).decode()
|
||||
body = {"model": str(llama.MODEL), "max_tokens": 1200, "temperature": 0.1,
|
||||
body = {"model": llama.current(True), "max_tokens": 1200, "temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]}
|
||||
if json_mode: body["response_format"] = {"type": "json_object"}
|
||||
if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"}
|
||||
req = urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
return json.load(_open(req, timeout=900))["choices"][0]["message"]["content"]
|
||||
|
||||
|
||||
+27
-2
@@ -3,6 +3,21 @@ module.exports = {
|
||||
bundle: "ai"
|
||||
},
|
||||
run: [
|
||||
{
|
||||
method: "log",
|
||||
params: {
|
||||
raw: "Hardware: {{gpu_model}} · {{vram}} GB VRAM · {{ram}} GB RAM"
|
||||
}
|
||||
},
|
||||
// floor: NVIDIA with 4 GB VRAM (llama.cpp CUDA build + whisper on GPU)
|
||||
{
|
||||
when: "{{gpu !== 'nvidia' || vram < 4}}",
|
||||
method: "notify",
|
||||
params: {
|
||||
html: "Teams Whisper needs an NVIDIA GPU with at least 4 GB VRAM (found: {{gpu_model}}, {{vram}} GB)."
|
||||
},
|
||||
next: null
|
||||
},
|
||||
{
|
||||
method: "shell.run",
|
||||
params: {
|
||||
@@ -73,8 +88,18 @@ module.exports = {
|
||||
"local-dir": "models"
|
||||
}
|
||||
},
|
||||
// LLM + vision projector (~23 GB)
|
||||
// small VLM (Qwen3.5 4B, ~3.3 GB), all layers in 4 GB VRAM: always installed, enough for 32 GB RAM machines
|
||||
{
|
||||
method: "hf.download",
|
||||
params: {
|
||||
path: "app",
|
||||
_: ["unsloth/Qwen3.5-4B-GGUF", "mmproj-BF16.gguf", "Qwen3.5-4B-Q4_K_S.gguf"],
|
||||
"local-dir": "models/qwen3.5-4b"
|
||||
}
|
||||
},
|
||||
// big MoE LLM + vision projector (~23 GB, experts in RAM): only with 48+ GB RAM
|
||||
{
|
||||
when: "{{ram >= 48}}",
|
||||
method: "hf.download",
|
||||
params: {
|
||||
path: "app",
|
||||
@@ -97,7 +122,7 @@ module.exports = {
|
||||
{
|
||||
method: "notify",
|
||||
params: {
|
||||
html: "Installation finished! Click 'Start', then load the browser extension from the 'Extension' tab."
|
||||
html: "Installation finished ({{ram >= 48 ? 'Qwen3.6 35B + Qwen3.5 4B: pick one in the Web UI header' : 'Qwen3.5 4B'}}). Click 'Start', then load the browser extension from the 'Extension' tab."
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ module.exports = {
|
||||
title: "Teams Whisper",
|
||||
description: "Record Teams calls and turn them into meeting reports, fully local",
|
||||
menu: async (kernel, info) => {
|
||||
let installed = info.exists("app/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf")
|
||||
let installed = info.exists("app/models/qwen3.5-4b/Qwen3.5-4B-Q4_K_S.gguf")
|
||||
let running = {
|
||||
install: info.running("install.js"),
|
||||
start: info.running("start.js"),
|
||||
|
||||
@@ -5,6 +5,8 @@ module.exports = {
|
||||
method: "shell.run",
|
||||
params: {
|
||||
path: "app",
|
||||
// LOG_LEVEL: INFO (default) or DEBUG (adds HTTP request lines + Prefect debug output)
|
||||
env: { LOG_LEVEL: "INFO" },
|
||||
// port stays 18765: the browser extension's host_permissions hardcode it
|
||||
message: "uv run --script server.py",
|
||||
on: [{
|
||||
|
||||
Reference in New Issue
Block a user