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
+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()
|
||||
|
||||
Reference in New Issue
Block a user