Pipeline code copied into app/; llama.py now uses launcher-local llama.cpp (app/bin) and Qwen GGUF (app/models) instead of LM Studio. install.js fetches ffmpeg, 7zip, llama.cpp CUDA 13, sherpa-onnx diarization models, bge-m3 and Qwen3.6-35B-A3B, then pre-builds the uv script environments. start.js serves the GUI on fixed port 18765 (hardcoded in the browser extension). reset.js keeps app/out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
280 lines
17 KiB
Python
280 lines
17 KiB
Python
# /// script
|
|
# requires-python = ">=3.10,<3.13"
|
|
# dependencies = ["numpy"]
|
|
# ///
|
|
"""Recorder + launcher + GUI (no model). Usage: uv run --script server.py [--port 18765]
|
|
Extension POSTs /chunk (10 s webm), /events (Teams call events), /stop. /stop launches flow.py (Prefect) for the recording.
|
|
GUI: http://127.0.0.1:18765/
|
|
"""
|
|
import argparse, json, os, sqlite3, subprocess, time, urllib.request
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse, parse_qs
|
|
import threading
|
|
import db, llama, memory
|
|
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--port", type=int, default=18765)
|
|
a = ap.parse_args()
|
|
HERE = Path(__file__).parent
|
|
out = db.OUT; out.mkdir(exist_ok=True)
|
|
R = {} # name -> {"last": ts of last chunk}
|
|
JOBS = {} # name -> Popen
|
|
PREFECT = "http://127.0.0.1:4200"
|
|
ENV = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
|
|
ENV.update(PREFECT_API_URL=PREFECT + "/api", NO_PROXY="127.0.0.1,localhost")
|
|
NOPROXY = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
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()
|
|
|
|
|
|
def make_pdf(name):
|
|
d = out / name; html = d / "report.html"; pdf = d / "report.pdf"
|
|
if not html.exists(): return None
|
|
if not pdf.exists() or pdf.stat().st_mtime < html.stat().st_mtime:
|
|
tmp = d / "_print.html"
|
|
tmp.write_text(html.read_text(encoding="utf-8").replace("<details", "<details open").replace("</style>", PRINT_CSS + "</style>", 1), encoding="utf-8")
|
|
pdf.unlink(missing_ok=True)
|
|
try:
|
|
r = subprocess.run([str(EDGE), "--headless", "--disable-gpu", "--no-first-run", "--no-pdf-header-footer", f"--user-data-dir={d / '.edge-pdf'}",
|
|
f"--print-to-pdf={pdf}", tmp.as_uri()], capture_output=True, timeout=180)
|
|
finally: tmp.unlink(missing_ok=True)
|
|
if not pdf.exists(): raise RuntimeError(r.stderr.decode(errors="replace")[-500:])
|
|
return pdf
|
|
|
|
|
|
def ask_once(q):
|
|
"""Start models, answer, always stop what we started (serialized: one ask at a time)."""
|
|
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]
|
|
return memory.ask(q)
|
|
finally:
|
|
for p in own: p.terminate()
|
|
|
|
|
|
def now(): return time.strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
def launch(name, start_from, speakers=5):
|
|
"""Spawn flow.py. Returns False if a job for this name is still running."""
|
|
j = JOBS.get(name)
|
|
if j and j.poll() is None: return False
|
|
d = db.out_dir(name)
|
|
JOBS[name] = subprocess.Popen(["uv", "run", "--script", "flow.py", name, "--from", start_from, "--speakers", str(speakers)],
|
|
cwd=HERE, env=ENV, stdout=open(d / "flow.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
|
|
return True
|
|
|
|
|
|
def prefect_up():
|
|
try: NOPROXY.open(PREFECT + "/api/health", timeout=2); return True
|
|
except Exception: return False
|
|
|
|
|
|
def start_prefect():
|
|
if prefect_up(): return
|
|
subprocess.Popen(["uv", "run", "--with", "prefect>=3", "prefect", "server", "start", "--host", "127.0.0.1", "--port", "4200"],
|
|
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")]):
|
|
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)
|
|
have.add(p.stem)
|
|
|
|
|
|
TITLES = {} # name -> (report.json mtime, "title — date")
|
|
|
|
|
|
def title(n):
|
|
f = out / n / "report.json"
|
|
if not f.exists(): return ""
|
|
m = f.stat().st_mtime
|
|
if TITLES.get(n, (0,))[0] != m:
|
|
try: j = json.loads(f.read_text(encoding="utf-8")); TITLES[n] = (m, f"{j.get('meeting_title') or ''} — {j.get('date') or ''}")
|
|
except ValueError: return ""
|
|
return TITLES[n][1]
|
|
|
|
|
|
def busy(): return any(p.poll() is None for p in JOBS.values())
|
|
|
|
|
|
def status():
|
|
t = time.time(); rs = []
|
|
for r in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"):
|
|
n = r["name"]; d = dict(r)
|
|
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)
|
|
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()}
|
|
|
|
|
|
def fts(sql, q):
|
|
c = db.connect()
|
|
try: return c.execute(sql, (q,)).fetchall()
|
|
except sqlite3.OperationalError: return c.execute(sql, ('"' + q.replace('"', '""') + '"',)).fetchall()
|
|
|
|
|
|
def search(q):
|
|
sp = []
|
|
for r in fts("SELECT name, t, speaker, snippet(lines, 3, '[', ']', '…', 12) FROM lines WHERE lines MATCH ? ORDER BY name DESC, t LIMIT 100", q):
|
|
sp.append([r[0], r[1], db.speaker_names(r[0]).get(r[2]) or r[2], r[3]])
|
|
sc = []
|
|
for r in fts("SELECT name, t, title, snippet(shot_text, 3, '[', ']', '…', 12) FROM shot_text WHERE shot_text MATCH ? ORDER BY name DESC, t LIMIT 100", q):
|
|
f = db.connect().execute("SELECT file FROM shots WHERE name=? AND t=?", (r[0], r[1])).fetchone()
|
|
sc.append([r[0], r[1], r[2], r[3], f[0] if f else ""])
|
|
return {"speech": sp, "screen": sc}
|
|
|
|
|
|
def speakers_info(name):
|
|
c = db.connect()
|
|
rows = [dict(r) for r in c.execute("SELECT label, person, source, overlap_s FROM speaker_map WHERE name=?", (name,))]
|
|
if not rows:
|
|
rows = [{"label": r[0], "person": "", "source": "", "overlap_s": None} for r in c.execute("SELECT DISTINCT speaker FROM lines WHERE name=? AND speaker IS NOT NULL ORDER BY speaker", (name,))]
|
|
p = out / name / "diar_segments.json"
|
|
talk = {}
|
|
for s in (json.loads(p.read_text(encoding="utf-8")) if p.exists() else []): talk[s["label"]] = talk.get(s["label"], 0) + s["end"] - s["start"]
|
|
for r in rows:
|
|
r["talk_s"] = round(talk.get(r["label"], 0))
|
|
r["samples"] = [x[0][:160] for x in c.execute("SELECT text FROM lines WHERE name=? AND speaker=? ORDER BY length(text) DESC LIMIT 3", (name, r["label"]))]
|
|
rows.sort(key=lambda r: (len(r["label"]), r["label"]))
|
|
cand = sorted({r["who"] for r in db.events(name, "active", "caption") if r["who"]})
|
|
for e in db.events(name, "present"):
|
|
cand += [p["who"] for p in json.loads(e["text"] or "[]")]
|
|
dp = out / name / "docs.json"
|
|
if dp.exists(): cand += json.loads(dp.read_text(encoding="utf-8")).get("people", [])
|
|
return {"rows": rows, "candidates": sorted(set(cand))}
|
|
|
|
|
|
def add_events(name, items):
|
|
rows = []
|
|
for e in items[:10000]:
|
|
try:
|
|
t, k, wk, w, x = e["t"], e["kind"], e.get("who_key", ""), e.get("who", ""), e.get("text", "")
|
|
except (KeyError, TypeError, AttributeError): continue
|
|
if (isinstance(t, (int, float)) and not isinstance(t, bool) and t >= 0 and k in db.EVENT_KINDS
|
|
and isinstance(wk, str) and isinstance(w, str) and isinstance(x, str)
|
|
and len(wk) <= 200 and len(w) <= 200 and len(x) <= 4000):
|
|
rows.append((t, k, wk, w, x))
|
|
db.add_events(name, rows)
|
|
|
|
|
|
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>
|
|
<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")};
|
|
q.onkeydown=e=>{if(e.key=="Enter")srch()};
|
|
qa.onkeydown=e=>{if(e.key=="Enter")ask()};
|
|
async function ask(){if(!qa.value)return;ar.innerHTML="<small>…avvio modelli / risposta (può richiedere qualche minuto)</small>";
|
|
const r=await fetch("/ask?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return}const j=await r.json();
|
|
ar.innerHTML="<div>"+E(j.answer).replace(/\\[(\\d+)\\]/g,(m,n)=>{const s=j.sources[n-1];return s?`<a href="/report?name=${s.name}#${s.anchor}" target=_blank>[${n}]</a>`:m})+"</div>"+
|
|
j.sources.map(s=>`<div><small>[${s.n}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} ${fmt(s.t)} (${s.kind}): ${E(s.text)}</small></div>`).join("")}
|
|
async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json();
|
|
sr.innerHTML=j.speech.map(r=>`<div>${E(r[0])} ${fmt(r[1])} ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")+j.screen.map(r=>`<div>🖥 <a href="/shot?name=${r[0]}&file=shots/${r[4]}" target=_blank>${E(r[0])} ${fmt(r[1])}</a> ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")}
|
|
async function run(n){const f=document.getElementById("f-"+n).value;const r=await fetch(`/run?name=${n}&from=${f}`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()}
|
|
const open_=new Set();
|
|
async function spk(n){open_.has(n)?open_.delete(n):open_.add(n);tick()}
|
|
async function panel(n){const j=await (await fetch("/speakers?name="+n)).json();
|
|
return `<tr class=sp><td colspan=7><datalist id="cand-${n}">${j.candidates.map(c=>`<option value="${E(c)}">`).join("")}</datalist>`+
|
|
j.rows.map(r=>`<div><b>${E(r.label)}</b> ${fmt(r.talk_s)} <input data-n="${n}" data-l="${E(r.label)}" list="cand-${n}" value="${E(r.person)}"> ${r.source}${r.source=="auto"&&r.overlap_s!=null?" "+Math.round(r.overlap_s)+"s":""}<br><small>${r.samples.map(E).join(" | ")}</small></div>`).join("")+
|
|
`<button onclick="saveSpk('${n}')">salva nomi</button>`}
|
|
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 tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.busy;ab.title=j.busy?"pipeline in corso":"";
|
|
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>`;
|
|
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);
|
|
</script>"""
|
|
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
def _send(self, body=b"", code=200, ctype="text/plain; charset=utf-8", headers=()):
|
|
self.send_response(code)
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.send_header("Access-Control-Allow-Headers", "*")
|
|
self.send_header("Content-Type", ctype)
|
|
for k, v in headers: self.send_header(k, v)
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers(); self.wfile.write(body)
|
|
def _json(self, o): self._send(json.dumps(o, ensure_ascii=False).encode(), ctype="application/json")
|
|
def do_OPTIONS(self): self._send()
|
|
def do_GET(self):
|
|
u = urlparse(self.path); q = {k: v[0] for k, v in parse_qs(u.query).items()}; name = Path(q.get("name", "x")).name
|
|
if u.path == "/": self._send(PAGE.encode(), ctype="text/html; charset=utf-8")
|
|
elif u.path == "/status": self._json(status())
|
|
elif u.path == "/report":
|
|
f = out / name / "report.html"
|
|
self._send(f.read_bytes(), ctype="text/html; charset=utf-8") if f.exists() else self._send(b"not found", 404)
|
|
elif u.path == "/shot":
|
|
f = out / name / "shots" / Path(q.get("file", "")).name
|
|
self._send(f.read_bytes(), ctype="image/jpeg") if f.is_file() else self._send(b"not found", 404)
|
|
elif u.path == "/search": self._json(search(q.get("q", "")))
|
|
elif u.path == "/speakers": self._json(speakers_info(name))
|
|
elif u.path == "/pdf":
|
|
try: f = make_pdf(name)
|
|
except Exception as e: return self._send(f"errore: {e}".encode(), 500)
|
|
if f is None: self._send(b"not found", 404)
|
|
else: self._send(f.read_bytes(), ctype="application/pdf", headers=[("Content-Disposition", f'inline; filename="{name}.pdf"')])
|
|
elif u.path == "/ask":
|
|
if not q.get("q", "").strip(): return self._send("domanda vuota".encode(), 400)
|
|
if busy(): return self._send("pipeline in corso: riprova dopo".encode(), 409)
|
|
try: self._json(ask_once(q["q"]))
|
|
except Exception as e: return self._send(f"errore: {e!r}".encode(), 503)
|
|
else: self._send(b"not found", 404)
|
|
def do_POST(self):
|
|
u = urlparse(self.path); q = {k: v[0] for k, v in parse_qs(u.query).items()}; name = Path(q.get("name", "x")).name
|
|
data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
|
|
if u.path == "/chunk":
|
|
with open(out / f"{name}.webm", "ab") as f: f.write(data)
|
|
if name not in R: db.upsert_recording(name, source="ext", started_at=now(), status="recording")
|
|
R.setdefault(name, {})["last"] = time.time()
|
|
db.connect().execute("UPDATE recordings SET chunks=chunks+1, bytes=bytes+?, updated_at=datetime('now') WHERE name=?", (len(data), name))
|
|
self._send()
|
|
elif u.path == "/events":
|
|
try: items = json.loads(data)
|
|
except ValueError: return self._send(b"bad json", 400)
|
|
if not isinstance(items, list): return self._send(b"bad json", 400)
|
|
add_events(name, items); self._send()
|
|
elif u.path == "/stop":
|
|
R.pop(name, None)
|
|
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 == "/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 == "/speaker_map":
|
|
try: m = json.loads(data)
|
|
except ValueError: return self._send(b"bad json", 400)
|
|
for label, person in m.items(): db.set_speaker_map(name, label, str(person).strip(), "manual")
|
|
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
|
|
|
|
|
|
db.connect(); backfill(); start_prefect()
|
|
print(f"listening http://127.0.0.1:{a.port}/", flush=True)
|
|
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
|