Add Pinokio launcher for Teams meeting report pipeline

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>
This commit is contained in:
pinokio
2026-10-30 21:29:33 +01:00
co-authored by Claude Opus 5.5
commit 4ff3e6fe14
31 changed files with 2366 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
# Teams Whisper
Local pipeline that records a Microsoft Teams call and turns it into a meeting report:
audio cleanup (ffmpeg) → transcription (faster-whisper CUDA, or OpenVINO NPU) → speaker diarization (sherpa-onnx) → speaker names from Teams events → screen content extraction (Qwen3.6-35B-A3B VLM via llama.cpp) → related Confluence/Jira docs (`twg`, optional) → topic report (HTML/PDF) → cross-meeting memory (bge-m3 embeddings).
Orchestrated by Prefect; everything runs locally. Windows + NVIDIA GPU (fits 4 GB VRAM: MoE experts run on CPU).
## 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.
## Use
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.
Alternative without the extension (desktop Teams, system loopback + mic): `cd app && uv run meet.py [--screen]`, Ctrl+C to stop.
Data lives in `app/out` (recordings, reports, `meetings.db`). **Reset** deletes models/binaries only, never `app/out`.
Other CLI tools (from `app/`):
- `uv run --script flow.py <name> --from report` — rerun a meeting from a step (`audio transcribe diarize speakers shots docs report memory render`)
- `uv run --script flow.py <name> --bench-npu` — benchmark NPU vs CUDA and remember the faster one
- `uv run --script memory.py --reindex` — rebuild cross-meeting memory
- `uv run --script review.py <name>` — report quality gate
## API
Base URL `http://127.0.0.1:18765`.
| Method | Path | Params |
|---|---|---|
| GET | `/status` | all recordings + pipeline status |
| GET | `/report` | `name` → report HTML |
| GET | `/pdf` | `name` → report PDF |
| GET | `/search` | `q` → full-text search over transcripts/topics |
| GET | `/ask` | `q` → answer from cross-meeting memory, with sources |
| POST | `/chunk` | `name`, body = webm chunk (append) |
| 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 | `/speaker_map` | `name`, body = `{"Speaker 1": "Mario Rossi"}` → re-render |
### curl
```bash
curl http://127.0.0.1:18765/status
curl "http://127.0.0.1:18765/ask?q=cosa%20abbiamo%20deciso%20sul%20rilascio"
curl -X POST "http://127.0.0.1:18765/run?name=teams_2026-10-28T13-04-04&from=report"
curl -X POST "http://127.0.0.1:18765/speaker_map?name=teams_2026-10-28T13-04-04" -d '{"Speaker 1":"Mario Rossi"}'
```
### Python
```python
import json, urllib.request, urllib.parse
B = "http://127.0.0.1:18765"
status = json.load(urllib.request.urlopen(f"{B}/status"))
ans = json.load(urllib.request.urlopen(f"{B}/ask?q=" + urllib.parse.quote("decisioni sul rilascio")))
urllib.request.urlopen(urllib.request.Request(f"{B}/run?name=teams_2026-10-28T13-04-04&from=report", method="POST"))
```
### JavaScript
```javascript
const B = "http://127.0.0.1:18765"
const status = await (await fetch(`${B}/status`)).json()
const ans = await (await fetch(`${B}/ask?q=${encodeURIComponent("decisioni sul rilascio")}`)).json()
await fetch(`${B}/run?name=teams_2026-10-28T13-04-04&from=report`, { method: "POST" })
```
## Notes
- Ports 18765 (GUI) and 4200 (Prefect) are fixed: the extension's `host_permissions` hardcode 18765.
- `docs.py` uses `twg` and the company proxy; without `twg` the step is skipped.
- PDF export uses Microsoft Edge headless.
+17
View File
@@ -0,0 +1,17 @@
"""Cheap non-AI audio cleanup: mono 16k, highpass, loudnorm -> out/<name>/audio.opus."""
import subprocess
import db
def run(name):
src = db.media(name)[0]
if src is None: raise FileNotFoundError(f"no audio source for {name}")
dst = db.out_dir(name) / "audio.opus"
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000",
"-af", "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11", "-c:a", "libopus", "-b:a", "24k", str(dst)],
capture_output=True, text=True)
if r.returncode: raise RuntimeError(r.stderr[-500:])
d = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(dst)],
capture_output=True, text=True, check=True).stdout.strip()
db.upsert_recording(name, duration_s=float(d))
return dst
+19
View File
@@ -0,0 +1,19 @@
import glob, os, site
import numpy as np
# pip nvidia-* wheels ship cublas/cudnn DLLs; ctranslate2 needs them on PATH (Windows)
for sp in site.getsitepackages():
for b in glob.glob(os.path.join(sp, "nvidia", "*", "bin")):
os.add_dll_directory(b); os.environ["PATH"] = b + os.pathsep + os.environ["PATH"]
from faster_whisper import WhisperModel
def load_model(name):
"""CUDA if it really works (probe one decode), else CPU int8."""
try:
m = WhisperModel(name, device="cuda", compute_type="float16")
list(m.transcribe(np.zeros(16000, np.float32))[0])
return m, "cuda"
except Exception as e:
print("cuda failed, using cpu:", e, flush=True)
return WhisperModel(name, device="cpu", compute_type="int8"), "cpu"
+134
View File
@@ -0,0 +1,134 @@
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
import json, re, sqlite3
from pathlib import Path
HERE = Path(__file__).parent
OUT = HERE / "out"
DB = OUT / "meetings.db"
SCHEMA = """
CREATE TABLE IF NOT EXISTS recordings(
name TEXT PRIMARY KEY, source TEXT, started_at TEXT, ended_at TEXT,
chunks INTEGER DEFAULT 0, bytes INTEGER DEFAULT 0, duration_s REAL, speakers INTEGER,
status TEXT, error TEXT, flow_run_id TEXT, updated_at TEXT,
transcribe_device TEXT, transcribe_s REAL);
CREATE VIRTUAL TABLE IF NOT EXISTS lines USING fts5(name UNINDEXED, t UNINDEXED, speaker, text, tokenize='unicode61 remove_diacritics 2');
CREATE TABLE IF NOT EXISTS shots(name TEXT, t REAL, t_end REAL, file TEXT, kind TEXT, title TEXT, app TEXT, caption TEXT, text TEXT, entities TEXT, PRIMARY KEY(name, t));
CREATE VIRTUAL TABLE IF NOT EXISTS shot_text USING fts5(name UNINDEXED, t UNINDEXED, title, text, tokenize='unicode61 remove_diacritics 2');
CREATE TABLE IF NOT EXISTS topics(name TEXT, idx INTEGER, title TEXT, start_s REAL, end_s REAL, json TEXT, PRIMARY KEY(name, idx));
CREATE TABLE IF NOT EXISTS call_events(name TEXT, t REAL, kind TEXT, who_key TEXT, who TEXT, text TEXT);
CREATE INDEX IF NOT EXISTS call_events_name ON call_events(name, kind, t);
CREATE TABLE IF NOT EXISTS speaker_map(name TEXT, label TEXT, person TEXT, source TEXT, overlap_s REAL, PRIMARY KEY(name, label));
CREATE TABLE IF NOT EXISTS memory(name TEXT, idx INTEGER, kind TEXT, t REAL, meeting TEXT, date TEXT, topic TEXT, anchor TEXT, text TEXT, vec BLOB);
CREATE INDEX IF NOT EXISTS memory_name ON memory(name);
"""
STATUSES = ["recording", "queued", "audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory", "done", "error"]
EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "caption", "chat", "hand"}
def connect() -> sqlite3.Connection:
OUT.mkdir(exist_ok=True)
c = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False)
c.execute("PRAGMA journal_mode=WAL")
c.row_factory = sqlite3.Row
c.executescript(SCHEMA)
return c
def upsert_recording(name: str, **f):
c = connect()
cols = ["name", *f]
sets = ",".join(f"{k}=excluded.{k}" for k in f) or "name=name"
c.execute(f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) "
f"ON CONFLICT(name) DO UPDATE SET {sets}", [name, *f.values()])
def set_status(name: str, status: str, error: str | None = None):
c = connect()
c.execute("INSERT INTO recordings(name,status,error,updated_at) VALUES(?,?,?,datetime('now')) "
"ON CONFLICT(name) DO UPDATE SET status=excluded.status,error=excluded.error,updated_at=excluded.updated_at",
(name, status, error))
def replace_lines(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM lines WHERE name=?", (name,))
c.executemany("INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)", [(name, t, s, x) for t, s, x in rows])
c.execute("COMMIT")
def replace_shots(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM shots WHERE name=?", (name,))
c.execute("DELETE FROM shot_text WHERE name=?", (name,))
for r in rows:
c.execute("INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)",
(name, r["t"], r.get("t_end"), r["file"], r.get("kind"), r.get("title"), r.get("app"),
r.get("summary"), r.get("text"), json.dumps(r.get("entities") or {}, ensure_ascii=False)))
c.execute("INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)",
(name, r["t"], r.get("title") or "", f"{r.get('text') or ''}\n{r.get('summary') or ''}"))
c.execute("COMMIT")
def replace_topics(name, topics):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM topics WHERE name=?", (name,))
c.executemany("INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)",
[(name, i, t["title"], t.get("start_s"), t.get("end_s"), json.dumps(t, ensure_ascii=False)) for i, t in enumerate(topics)])
c.execute("COMMIT")
def replace_memory(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM memory WHERE name=?", (name,))
c.executemany("INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)", rows)
c.execute("COMMIT")
def out_dir(name) -> Path:
d = OUT / name
d.mkdir(parents=True, exist_ok=True)
return d
def media(name):
def first(*exts):
for e in exts:
p = OUT / f"{name}{e}"
if p.exists(): return p
return first(".webm", ".wav"), first(".webm", ".mp4")
def add_events(name, rows):
connect().executemany("INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
[(name, *r) for r in rows])
def events(name, *kinds):
q = "SELECT * FROM call_events WHERE name=?"
if kinds: q += f" AND kind IN ({','.join('?' * len(kinds))})"
return connect().execute(q + " ORDER BY t", (name, *kinds)).fetchall()
def speaker_names(name) -> dict:
return {r["label"]: r["person"] for r in connect().execute(
"SELECT label,person FROM speaker_map WHERE name=? AND person<>'' AND person IS NOT NULL", (name,))}
def set_speaker_map(name, label, person, source, overlap_s=None):
connect().execute(
"INSERT INTO speaker_map(name,label,person,source,overlap_s) VALUES(?,?,?,?,?) "
"ON CONFLICT(name,label) DO UPDATE SET person=excluded.person,source=excluded.source,overlap_s=excluded.overlap_s "
"WHERE speaker_map.source != 'manual' OR excluded.source = 'manual'", (name, label, person, source, overlap_s))
def norm_name(raw: str) -> str:
"""Port of norm() in ext/teams.js: 'Rossi, MARIO (IG/S-32)' -> 'Mario Rossi'."""
raw = (raw or "").strip()
m = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw)
if not m: return raw
return " ".join(w.title() if w.isupper() else w for w in f"{m[2]} {m[1]}".split())
+49
View File
@@ -0,0 +1,49 @@
"""Label who speaks (CPU, sherpa-onnx): run(name) -> out/<name>.spk.txt, diar_segments.json, DB lines."""
import json, re, subprocess
from pathlib import Path
import numpy as np
import db
M = Path(__file__).parent / "models"
def run(name, speakers=5, threshold=0.85):
import sherpa_onnx
src = db.out_dir(name) / "audio.opus"
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))
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)
lines = []
for l in (db.OUT / f"{name}.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3]))
out, order = [], {}
for i, (t, text) in enumerate(lines):
t1 = lines[i + 1][0] if i + 1 < len(lines) else t + 5
ov = {}
for s, e, sp in segs:
o = min(e, t1) - max(s, t)
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
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):
order.setdefault(s[2], len(order) + 1)
(db.OUT / f"{name}.spk.txt").write_text("\n".join(
f"[{t//60:02d}:{t%60:02d}] " + (f"Speaker {order[sp]}: " if sp is not None else "") + text for t, sp, text in out), encoding="utf-8")
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8")
db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out])
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None}))
print("saved", db.OUT / f"{name}.spk.txt")
+106
View File
@@ -0,0 +1,106 @@
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow."""
import json, os, re, shutil, subprocess
import db, report
TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
PROXY = "http://zproxy.idg.audi.vwg:9400"
SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.'
SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).'
KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$")
PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
def _twg(*args, timeout=120):
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
for attempt in range(2):
r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON
except ValueError: out = None
else: out = r.stdout if r.returncode == 0 else None
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
env = {**env, "HTTPS_PROXY": PROXY, "HTTP_PROXY": PROXY}
def _run(name):
if not os.path.exists(TWG): raise FileNotFoundError("twg not found")
d = db.out_dir(name)
meta = [json.loads(e["text"]) for e in db.events(name, "meta")]
title = (meta[-1].get("title") or "") if meta else ""
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else []
from shots import CONTENT_KINDS
screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30]
txt = (db.OUT / f"{name}.txt").read_text(encoding="utf-8") if (db.OUT / f"{name}.txt").exists() else ""
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}"
queries = [title] if title else []
queries += [q for q in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4] if isinstance(q, str)]
queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1]
cand = {}
for q in queries:
for app, lim in (("confluence", 6), ("jira", 4)):
for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []:
u = it.get("url")
if not u or u in cand: continue
jk = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", u); cid = re.search(r"/pages/(\d+)", u)
cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None,
"title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False}
items = list(cand.values())
blob = [txt] + [s.get("text") or "" for s in shots]
keys = [k for k in dict.fromkeys(m for b in blob for m in report.TICKET.findall(b)) if KEY.match(k)]
keys += [k for k in (e["key"] for e in items) if k and k not in keys]
mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)})
known = {}
if keys[:20 + 6]:
r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for it in (r.get("data") or {}).get("items") or []:
if it.get("ok") and it.get("data"):
x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "")
for e in items:
if e["key"] in known: e["title"], e["status"] = known[e["key"]]
have = {e["key"] for e in items if e["key"]}
for k in keys:
if k in known and k in mentioned and k not in have:
items.append({"source": "jira", "key": k, "id": None, "title": known[k][0], "url": f"{report.JIRA_BROWSE}/{k}", "status": known[k][1], "snippet": "", "mentioned": True})
for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known)
scores = {}
rel = [e for e in items if not e["mentioned"]]
if rel:
u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel))
for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []:
try: scores[int(s["i"])] = int(s["score"])
except (KeyError, TypeError, ValueError): pass
for i, e in enumerate(rel): e["score"] = scores.get(i, 0)
for e in items:
e.setdefault("score", 3 if e["mentioned"] else 0)
keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"])
conf = [e for e in keep if e["source"] == "confluence"][:8]
jira = [e for e in keep if e["source"] == "jira" and not e["mentioned"]][:6] + [e for e in keep if e["mentioned"]]
keep = conf + jira
for e in keep:
if e["source"] == "confluence" and e["id"]:
b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or ""
lines = b.splitlines()
if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:]
e["body"] = "\n".join(lines)[:6000]
else: e["body"] = f"{e['key']} {e['title']} ({e['status']})"
for i, e in enumerate(keep): e["i"] = i
people = []
for e in keep:
for m in PEOPLE.finditer(e["body"]):
n = db.norm_name(m[1])
if " " in n and n not in people: people.append(n)
return {"queries": queries, "items": keep, "people": people, "error": None}
def run(name):
try: out = _run(name)
except Exception as e:
print("docs failed:", repr(e), flush=True)
out = {"queries": [], "items": [], "people": [], "error": repr(e)[:300]}
(db.out_dir(name) / "docs.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
+10
View File
@@ -0,0 +1,10 @@
{
"manifest_version": 3,
"name": "Teams Whisper Recorder",
"version": "1.1",
"description": "Record Teams tab audio+video (+mic) and transcribe with local whisper server",
"permissions": ["tabCapture", "offscreen", "activeTab", "tabs"],
"host_permissions": ["http://127.0.0.1:18765/*"],
"content_scripts": [{ "matches": ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], "js": ["teams.js"], "run_at": "document_idle" }],
"action": { "default_popup": "popup.html" }
}
+2
View File
@@ -0,0 +1,2 @@
<body>Allow the microphone, then close this tab.
<script src="mic.js"></script>
+3
View File
@@ -0,0 +1,3 @@
navigator.mediaDevices.getUserMedia({ audio: true })
.then(s => { s.getTracks().forEach(t => t.stop()); document.body.append(" granted."); })
.catch(e => document.body.append(" " + e));
+1
View File
@@ -0,0 +1 @@
<script src="offscreen.js"></script>
+57
View File
@@ -0,0 +1,57 @@
const API = "http://127.0.0.1:18765";
let rec, ctx, tab, mic, q = Promise.resolve(), name;
// state: idle | recording | transcribing | done | error ; popup polls it
const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" };
chrome.runtime.onMessage.addListener((m, _s, send) => {
if (m.to !== "off") return;
if (m.cmd === "status") send(S);
if (m.cmd === "start") start(m.id, m.tabId).then(() => send({ ok: true }), e => { S.state = "error"; S.text = String(e); send({ err: String(e) }); });
if (m.cmd === "events") { for (const e of m.events) if (e.ts >= S.t0) S.ev.push({ t: (e.ts - S.t0) / 1000, kind: e.kind, who_key: e.who_key, who: e.who, text: e.text }); }
if (m.cmd === "stop") { rec.stop(); send({ ok: true }); }
return true;
});
async function flushEv() {
if (!S.ev.length) return;
const b = S.ev.splice(0);
try {
const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });
if (!r.ok) throw 0;
S.evSent += b.length;
} catch { S.failed++; }
}
async function start(id, tabId) {
name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } };
tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src });
ctx = new AudioContext();
const dest = ctx.createMediaStreamDestination();
const t = ctx.createMediaStreamSource(tab);
t.connect(dest);
t.connect(ctx.destination); // tabCapture mutes the tab; play it back
try { // needs one-time grant via mic.html
mic = await navigator.mediaDevices.getUserMedia({ audio: true });
ctx.createMediaStreamSource(mic).connect(dest);
} catch { mic = null; }
const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]);
rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
rec.ondataavailable = e => {
q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv);
};
rec.onstop = async () => {
S.state = "transcribing"; S.t1 = Date.now();
try {
await q;
await flushEv();
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop()));
ctx.close();
const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" });
S.text = await r.text(); S.state = r.ok ? "done" : "error";
} catch (e) { S.text = "server down or failed: " + e; S.state = "error"; }
rec = null;
};
Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId });
rec.start(10000);
}
+5
View File
@@ -0,0 +1,5 @@
<body style="width:380px;font:13px sans-serif">
<button id="go">Start</button> <a href="mic.html" target="_blank">grant mic (once)</a>
<div id="st"></div>
<pre id="txt" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre>
<script src="popup.js"></script>
+46
View File
@@ -0,0 +1,46 @@
const $ = id => document.getElementById(id);
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg });
const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
let S = { state: "idle" }, lastErr = "";
function render() {
const go = $("go"), st = $("st");
go.disabled = S.state === "transcribing";
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start";
st.textContent = {
idle: "idle - open a Teams tab and press Start",
recording: `REC ${mmss(Date.now() - S.t0)} | ${S.chunks} chunks uploaded${S.failed ? ` | ${S.failed} FAILED (server down?)` : ""} | mic ${S.mic ? "on" : "OFF (grant it)"} | eventi call: ${S.evSent || 0}`,
transcribing: `invio alla pipeline...`,
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
error: "ERROR (see below)",
}[S.state];
if (S.text) $("txt").textContent = S.text;
}
async function poll() {
if (await chrome.offscreen.hasDocument()) S = (await off({ cmd: "status" })) || S; else S = lastErr ? { state: "error", text: lastErr } : { state: "idle" };
render();
}
$("go").onclick = async () => {
if (S.state === "recording") {
if (S.tabId != null) await chrome.tabs.sendMessage(S.tabId, { cmd: "cap-stop" }).catch(() => {});
await new Promise(r => setTimeout(r, 300));
await off({ cmd: "stop" }); return poll();
}
lastErr = "";
try {
const [t] = await chrome.tabs.query({ active: true, currentWindow: true });
if (t.url?.startsWith("chrome-extension:")) throw new Error("This is the extension's own page. Switch to the Teams tab, then click the icon.");
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id });
if (!(await chrome.offscreen.hasDocument()))
await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" });
const r = await off({ cmd: "start", id, tabId: t.id });
if (r?.err) throw new Error(r.err);
chrome.tabs.sendMessage(t.id, { cmd: "cap-start" }).catch(() => {});
} catch (e) { lastErr = String(e); }
render(); poll();
};
poll(); setInterval(poll, 1000);
+108
View File
@@ -0,0 +1,108 @@
// Content script on Teams web: logs active speaker, shares, captions, chat, hands, presence while recording.
// Events go via the offscreen document (it has host_permissions for 127.0.0.1). Never clicks or types in the call.
const SEL = {
duration: '[data-tid="call-duration"]',
nametag: '[data-tid="participant-info-nametag"]',
info: '[data-tid="participant-info"]',
speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]',
self: '[data-tid="myself-video"]',
shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/,
caption: null, captionAuthor: null, captionText: null, // discovery step (see plan 3b)
chatMsg: null, chatAuthor: null, chatText: null, // discovery step
hand: null, // discovery step
};
let buf = [], timers = [], seenCap = new WeakSet(), seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
const norm = raw => {
raw = (raw || "").trim();
const m = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!m) return raw;
return `${m[2]} ${m[1]}`.split(/\s+/).map(w => (w.length > 1 && w === w.toUpperCase() ? w[0] + w.slice(1).toLowerCase() : w)).join(" ");
};
const tileOf = el => { while (el && !el.querySelector(SEL.nametag)) el = el.parentElement; return el; };
const keyOf = tile => {
for (let e = tile; e; e = e.parentElement) if ((e.dataset?.tid || "").includes("@")) return e.dataset.tid;
return tile.querySelector(SEL.nametag)?.textContent.trim() || "";
};
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; };
const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text });
const guard = f => () => { try { f(); } catch { } };
const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean);
function meta() {
const title = document.title.replace(/^[^|]*\|\s*/, "").replace(/\s*\|\s*Microsoft Teams$/, "");
if (title === lastTitle) return;
lastTitle = title;
emit("meta", "", "", JSON.stringify({ title, call_elapsed: document.querySelector(SEL.duration)?.textContent.trim() || "", url: location.href }));
}
function present() {
const seen = new Map();
for (const t of tiles()) seen.set(keyOf(t), { key: keyOf(t), who: t.closest(SEL.self) ? selfName() : nameOf(t) });
emit("present", "", "", JSON.stringify([...seen.values()]));
}
function active() {
for (const el of document.querySelectorAll(SEL.speaking)) {
const t = tileOf(el); if (!t) continue;
if (t.closest(SEL.self) || t.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(t), nameOf(t));
}
}
function share() {
const names = tiles().map(nameOf);
let cur = "";
for (const el of document.querySelectorAll("[aria-label]")) {
const m = el.getAttribute("aria-label").match(SEL.shareAria);
if (m) { cur = names.find(n => n && m[2].startsWith(n)) || m[2]; break; }
}
if (cur === lastShare) return;
if (lastShare) emit("share_stop", "", lastShare);
if (cur) emit("share_start", "", cur);
lastShare = cur;
}
function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) {
if (seenCap.has(el)) continue; seenCap.add(el);
const text = el.querySelector(SEL.captionText)?.textContent.trim();
if (text) emit("caption", "", norm(el.querySelector(SEL.captionAuthor)?.textContent), text);
}
if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el);
const text = el.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(el.querySelector(SEL.chatAuthor)?.textContent), text);
}
if (SEL.hand) {
const now = new Set();
for (const el of document.querySelectorAll(SEL.hand)) {
const t = tileOf(el); if (!t) continue;
const k = keyOf(t); now.add(k);
if (!raised.has(k)) emit("hand", k, nameOf(t));
}
raised = now;
}
}
function stop() {
timers.forEach(clearInterval); timers = [];
send();
if (lastShare) { emit("share_stop", "", lastShare); lastShare = ""; }
send();
}
function start() {
stop();
buf = []; seenCap = new WeakSet(); seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
meta(); present();
timers = [
setInterval(guard(() => { meta(); active(); }), 500),
setInterval(guard(() => { share(); messages(); }), 1000),
setInterval(guard(present), 30000),
setInterval(guard(send), 5000),
];
}
chrome.runtime.onMessage.addListener(m => {
if (m.cmd === "cap-start") start();
if (m.cmd === "cap-stop") stop();
});
+141
View File
@@ -0,0 +1,141 @@
# /// 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"]
# ///
"""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"
import argparse, sys
from pathlib import Path
from prefect import flow, task
from prefect.runtime import flow_run
from prefect.task_runners import ThreadPoolTaskRunner
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
HERE = Path(__file__).parent
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
def step_status(name, s):
db.set_status(name, s)
@task(name="audio")
def t_audio(name): step_status(name, "audio"); audio.run(name)
@task(name="transcribe")
def t_transcribe(name, model, device, status=True):
if status: step_status(name, "transcribing")
transcribe.run(name, model=model, device=device)
@task(name="diarize")
def t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speakers=n)
@task(name="speakers")
def t_speakers(name): step_status(name, "identifying"); speakers.run(name)
@task(name="shots", retries=1, retry_delay_seconds=10)
def t_shots(name, status=True):
if status: step_status(name, "shots")
shots.run(name)
@task(name="docs", retries=1, retry_delay_seconds=10)
def t_docs(name): step_status(name, "docs"); docs.run(name)
@task(name="report", retries=1, retry_delay_seconds=10)
def t_report(name): step_status(name, "report"); report.run(name)
@task(name="memory")
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"
try:
p = llama.start(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()
self.p = None
def default_device():
try:
d = (db.OUT / "transcribe_device.txt").read_text().strip()
return d if d in ("cuda", "npu") else "cuda"
except OSError:
return "cuda"
@flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3))
def meeting(name: str, start_from: str = "audio", speakers: int = 5, model: str = "large-v3-turbo", device: str | None = None):
device = device or default_device()
go = lambda s: STEPS.index(s) >= STEPS.index(start_from)
L = Llama(name)
try:
db.upsert_recording(name, flow_run_id=str(flow_run.id))
if start_from == "render":
memory.run(name, link=False)
else:
if go("audio"): t_audio(name)
spk_chain = lambda: [t_diarize(name, speakers), t_speakers(name)] if go("diarize") else ([t_speakers(name)] if go("speakers") else None)
if device == "npu" and go("transcribe") and go("shots"):
db.set_status(name, "transcribing")
L.ensure()
f_t = t_transcribe.submit(name, model, "npu", False)
f_s = t_shots.submit(name, False)
try:
f_t.result()
except Exception as e:
if "NPU failed" not in repr(e): raise
f_s.result(); L.close()
print("NPU failed, transcribed on cuda")
t_transcribe(name, model, "cuda")
spk_chain(); L.ensure(); f_s = None
else:
spk_chain()
if f_s is not None: f_s.result()
else:
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)
if go("report"): t_report(name)
t_memory(name)
db.set_status(name, "done")
except Exception as e:
db.set_status(name, "error", repr(e)[:500])
raise
finally:
L.close()
def bench(name):
d = db.out_dir(name)
try: npu_s = transcribe.run(name, device="npu", out_path=d / "bench_npu.txt")
except Exception as e: print("npu error:", e); npu_s = None
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt")
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
(db.OUT / "transcribe_device.txt").write_text(dev)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
ap = argparse.ArgumentParser()
ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS)
ap.add_argument("--speakers", type=int, default=5); ap.add_argument("--device", choices=["cuda", "npu"])
ap.add_argument("--bench-npu", action="store_true")
a = ap.parse_args()
if a.bench_npu: bench(a.name)
else: meeting(a.name, a.start, a.speakers, device=a.device)
+31
View File
@@ -0,0 +1,31 @@
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"
PORT = 18081
EMBED, EMBED_PORT = Path(__file__).parent / "models" / "bge-m3-Q8_0.gguf", 18082
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
def up(port=PORT):
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True
except Exception: return False
def _spawn(args, port, log):
if up(port): return None
p = subprocess.Popen([str(SERVER), *args, "--port", str(port)], stdout=open(log, "w"), stderr=subprocess.STDOUT)
for _ in range(600):
if up(port): return p
assert p.poll() is None, f"llama-server died, see {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_embed(log="embed.log"):
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
+76
View File
@@ -0,0 +1,76 @@
# /// script
# requires-python = ">=3.10,<3.13"
# dependencies = ["pyaudiowpatch", "numpy"]
# ///
"""Record Teams (system loopback) + your mic, Ctrl+C to stop, then run the flow (flow.py).
Usage: uv run meet.py [--screen] [--name meet_...]
Any Teams (desktop or web) works: loopback captures whatever plays on default speakers.
"""
import argparse, subprocess, sys, time, wave, threading
from pathlib import Path
import numpy as np
import pyaudiowpatch as pa
ap = argparse.ArgumentParser()
ap.add_argument("--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)")
ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
ap.add_argument("--seconds", type=float, help="auto-stop after N seconds")
a = ap.parse_args()
out = Path(__file__).parent / "out"; out.mkdir(exist_ok=True)
SR = 16000
def to16k(x, ch, sr):
x = x.reshape(-1, ch).mean(axis=1)
n = int(len(x) * SR / sr)
return np.interp(np.linspace(0, len(x) - 1, n), np.arange(len(x)), x).astype(np.float32)
def record():
p = pa.PyAudio()
lb = p.get_default_wasapi_loopback()
mic = p.get_device_info_by_index(p.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"])
bufs = {"sys": [], "mic": []}
streams = []
for key, d in (("sys", lb), ("mic", mic)):
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"])
def cb(data, f, t, s, key=key): bufs[key].append(data); return (None, pa.paContinue)
st = p.open(format=pa.paInt16, channels=ch, rate=sr, input=True,
input_device_index=d["index"], frames_per_buffer=1024, stream_callback=cb)
streams.append((key, ch, sr, st))
print(f"loopback: {lb['name']}\nmic: {mic['name']}")
ff = None
if a.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(out / f"{a.name}.mp4")], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("Recording... Ctrl+C to stop")
try:
t0 = time.time()
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5)
except KeyboardInterrupt: pass
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait()
p.terminate()
mix = []
for key, ch, sr, st in streams:
raw = np.frombuffer(b"".join(bufs[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw): mix.append(to16k(raw[: len(raw) // ch * ch], ch, sr))
n = max(len(m) for m in mix)
y = sum(np.pad(m, (0, n - len(m))) for m in mix)
y = np.clip(y, -1, 1)
path = out / f"{a.name}.wav"
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((y * 32767).astype(np.int16).tobytes())
return path
def finish(path):
import os
import db
now = time.strftime("%Y-%m-%d %H:%M:%S")
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued")
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
env.update(PREFECT_API_URL="http://127.0.0.1:4200/api", NO_PROXY="127.0.0.1,localhost")
subprocess.run(["uv", "run", "--script", "flow.py", a.name], cwd=Path(__file__).parent, env=env)
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
finish(record())
+134
View File
@@ -0,0 +1,134 @@
# /// script
# requires-python = ">=3.10,<3.13"
# dependencies = ["numpy", "markdown"]
# ///
"""Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db.
uv run --script memory.py --reindex"""
import contextlib, json, re, sys, urllib.request
import numpy as np
import db, llama, report
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.')
SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi SOLO JSON: {"answer":str}. Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.'
STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
@contextlib.contextmanager
def embedder(log):
p = llama.start_embed(log=log)
try: yield
finally:
if p is not None: p.terminate()
def embed(texts):
out = []
for i in range(0, len(texts), 32):
body = {"input": [x[:2000] for x in texts[i:i + 32]], "model": "bge-m3"}
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])]
v = np.array(out, dtype=np.float32)
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
def _stamp(n):
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n)
return m[0] if m else ""
def _rows(pred):
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k.
rows = [r for r in db.connect().execute("SELECT * FROM memory") if pred(r)]
if not rows: return [], None
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1)
def _txt(x): return x["text"] if isinstance(x, dict) else str(x)
def _topic_text(t, title=True):
parts = ([t["title"]] if title else []) + [_txt(x) for x in t.get("summary", [])] + list(t.get("decisions", [])) + list(t.get("open_questions", []))
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p)
def index(name):
from markdown.extensions.toc import slugify
rep = report._load(name, "report.json", None)
if rep is None: return
rep, _ = report.named(name, rep)
items = []
for i, t in enumerate(rep["topics"], 1):
base = (name, i, t["start_s"], rep["meeting_title"], rep["date"], t["title"], slugify(report._head(i, t), "-"))
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])]
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])]
its += [("open_question", x) for x in t.get("open_questions", [])]
items += [(base, k, x) for k, x in its if x]
if not items: db.replace_memory(name, []); return
V = embed([f"{b[5]}: {x}" for b, _, x in items])
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)])
print(f"memory: indexed {len(items)} items")
def _prev_line(n, r): return f"[{n}] {r['date']} «{r['meeting']}» — {r['topic']} ({r['kind']}): {r['text']}"
def _link(name):
rep = report._load(name, "report.json", None)
if rep is None: return
named_rep, _ = report.named(name, rep)
cur = _stamp(name)
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur)
for t in rep["topics"]: t["previous"] = []
if rows:
Q = embed([_topic_text(t) for t in named_rep["topics"]])
S = Q @ M.T
for t, nt, s in zip(rep["topics"], named_rep["topics"], S):
top = [j for j in np.argsort(-s)[:K_TOPIC] if s[j] >= MEM_MIN]
if not top: continue
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", []))
user = (f"ARGOMENTO: {nt['title']}\nSINTESI: {' '.join(_txt(x) for x in nt.get('summary', []))}\nDECISIONI: {'; '.join(nt.get('decisions', []))}\n"
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n"
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1)))
r = report.chat(SYS_M, user, 1500) or {}
for l in (r.get("links") or [])[:4]:
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip()
except (KeyError, TypeError, ValueError): continue
if 1 <= ref <= len(top) and st in STATUSES and tx:
p = rows[top[ref - 1]]
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"],
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]})
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
def run(name, link=True):
"""Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow."""
try:
with embedder(db.out_dir(name) / "embed.log"):
if link:
try: _link(name)
except Exception as e: print("memory link skipped:", repr(e))
index(name)
except Exception as e: print("memory index skipped:", repr(e))
report.render(name)
def ask(q):
rows, M = _rows(lambda r: True)
if not rows: return {"answer": "Nessuna riunione indicizzata.", "sources": []}
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK]
rs = [rows[j] for j in top]
r = report.chat(SYS_ASK, f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1)), 1500) or {}
return {"answer": str(r.get("answer") or "Risposta non disponibile."),
"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]}
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
if "--reindex" in sys.argv:
with embedder(db.OUT / "embed.log"):
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
+403
View File
@@ -0,0 +1,403 @@
"""Topic summaries (local llama-server) + report.md / report.html rendering."""
import base64, difflib, json, re, unicodedata, urllib.request
import db, llama
from shots import CONTENT_KINDS
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
LINE = re.compile(r"^\[(\d+):(\d+)\] (?:(Speaker \d+): )?(.*)$")
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
'Se parlato e schermo divergono, riportalo nel summary. Usa solo fatti presenti nel testo. '
'Usa i nomi dei partecipanti solo se compaiono nel testo come nomi propri; non citare mai le etichette "Speaker N": usa forme impersonali ("si conferma", "viene proposto"). Ogni argomento copre almeno 3 minuti di discussione: non creare un argomento per ogni schermata. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Glossario dei termini corretti letti dallo schermo (la trascrizione può storpiarli, usa la grafia del glossario): ')
SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr":[str]}. title: titolo breve della riunione (max 8 parole). Massimo 5 punti in tldr, in italiano, forma impersonale, senza etichette "Speaker N". Usa solo fatti presenti.'
SYS_D = ('Hai un argomento di una riunione e alcuni estratti di documentazione aziendale numerati. Rispondi SOLO JSON: {"summary":[{"text":str,"doc":int|null}],"from_docs":[{"text":str,"doc":int}]}. '
'"summary": riscrivi i punti della sintesi mantenendo tutti i fatti della riunione; puoi completarli o correggerli con la documentazione indicando in "doc" il numero dell\'estratto usato (null se il punto viene solo dalla riunione). '
'Se riunione e documentazione divergono, riporta entrambe ("in riunione …; secondo la documentazione …"). "from_docs": massimo 3 fatti della documentazione pertinenti all\'argomento e non detti in riunione. Non citare etichette "Speaker N". Non inventare. Scrivi in italiano.')
CLUSTER, TIDY_MIN, DOC_MIN = 0.82, 120, 3
GUI = "http://127.0.0.1:18765"
def mmss(s): s = int(s); return f"{s // 60:02d}:{s % 60:02d}"
def secs(s):
m = re.match(r"(\d+):(\d+)", str(s))
return int(m[1]) * 60 + int(m[2]) if m else 0
def chat(system, user, max_tokens, retries=2):
body = {"model": str(llama.MODEL), "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):
try:
try:
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
except urllib.error.HTTPError as e:
if e.code != 400: raise
body.pop("response_format", None)
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
t = json.load(r)["choices"][0]["message"]["content"]
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
if isinstance(d, dict): return d
except (ValueError, KeyError): pass
return None
def _transcript(name):
p = db.OUT / f"{name}.spk.txt"
if not p.exists(): p = db.OUT / f"{name}.txt"
rows = []
for l in p.read_text(encoding="utf-8").splitlines() if p.exists() else []:
m = LINE.match(l)
if m: rows.append((int(m[1]) * 60 + int(m[2]), m[3], m[4]))
return rows
def _load(name, f, default):
p = db.out_dir(name) / f
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else default
def _shares(evs, dur):
out, open_ = [], {}
for e in evs:
if e["kind"] == "share_start": open_[e["who"]] = e["t"]
elif e["kind"] == "share_stop" and e["who"] in open_: out.append({"who": e["who"], "start": open_.pop(e["who"]), "end": e["t"]})
out += [{"who": w, "start": s, "end": dur} for w, s in open_.items()]
return sorted(out, key=lambda x: x["start"])
def _subst(s, names):
return re.sub(r"\bSpeaker (\d+)\b", lambda m: names.get(m[0]) or m[0], s) if isinstance(s, str) else s
def _deep(o, f):
if isinstance(o, str): return f(o)
if isinstance(o, list): return [_deep(x, f) for x in o]
if isinstance(o, dict): return {k: _deep(v, f) for k, v in o.items()}
return o
def _merge(topics):
out = []
for t in topics:
if out and out[-1]["title"].lower() == t["title"].lower():
p = out[-1]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): p[k] = p[k] + t[k]
p["end_s"] = t["end_s"]
else: out.append(t)
return out
def _key(n): return " ".join(sorted(unicodedata.normalize("NFKD", n).encode("ascii", "ignore").decode().lower().split()))
def _sim(a, b): return difflib.SequenceMatcher(None, _key(a), _key(b)).ratio()
def canon(counts, known, video=False, thr=CLUSTER):
"""raw name -> canonical spelling (known list first, else most frequent of a similarity cluster); dropped names have no entry."""
out, clusters = {}, []
for raw, c in sorted(counts.items(), key=lambda x: -x[1]):
if " " not in raw or len(raw) <= 4 or "..." in raw or "…" in raw: continue
best = max(((_sim(raw, k), k) for k in known), default=(0, None))
if best[0] >= .75: out[raw] = best[1]; continue
cl = next((x for x in clusters if _sim(raw, x[0]) >= thr), None)
if cl: cl[1] += c; cl[2].append(raw)
else: clusters.append([raw, c, [raw]])
for rep, tot, mem in clusters:
if video and tot < 2: continue
for m in mem: out[m] = rep
return out
def _canon_att(att, cmap):
out = {}
for a in att.values():
c = cmap.get(a["who"])
if not c: continue
x = out.setdefault(c, {"who": c, "first_t": a["first_t"], "last_t": a["last_t"]})
x["first_t"], x["last_t"] = min(x["first_t"], a["first_t"]), max(x["last_t"], a["last_t"])
return out
def _canon_shares(shares, cmap):
ss = sorted(({**s, "who": cmap[s["who"]]} for s in shares if s["who"] in cmap), key=lambda s: s["start"])
while True:
out = []
for s in ss:
if out and out[-1]["who"] == s["who"] and s["start"] - out[-1]["end"] <= 60: out[-1]["end"] = max(out[-1]["end"], s["end"])
else: out.append(dict(s))
kept = [s for s in out if s["end"] - s["start"] >= 20]
if len(kept) == len(ss): return kept
ss = kept
def _tidy(topics, dur, min_s=TIDY_MIN):
"""Sort, de-overlap, merge topics shorter than min_s into a neighbour, keep only screen facts timed inside the topic."""
topics.sort(key=lambda t: t["start_s"])
prev = 0
for t in topics: t["start_s"] = max(t["start_s"], prev); t["end_s"] = max(t["end_s"], t["start_s"] + 1); prev = t["end_s"]
ln = lambda t: t["end_s"] - t["start_s"]
while len(topics) > 1:
i = next((i for i, t in enumerate(topics) if ln(t) < min_s), None)
if i is None: break
j = i - 1 if i else 1
lo, hi = min(i, j), max(i, j)
a, b = topics[lo], topics[hi]
m = dict(a)
m["title"] = (a if ln(a) >= ln(b) else b)["title"]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): m[k] = a[k] + b[k]
m["start_s"], m["end_s"] = min(a["start_s"], b["start_s"]), max(a["end_s"], b["end_s"])
topics[lo:hi + 1] = [m]
for t in topics:
t["shown"] = [x for x in t["shown"] if (m := re.search(r"(\d\d):(\d\d)", str(x))) and t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30]
return topics
def _words(s): return {w for w in re.findall(r"\w+", s.lower()) if len(w) >= 5}
def _pass_d(t, docs):
"""Complete/correct a topic's summary with the best-matching docs; sets t['summary'] and t['from_docs'] as {text, doc} dicts."""
w = _words(" ".join([t["title"], *(x["text"] for x in t["summary"]), *t["shown"]]))
top = sorted(((len(w & _words(d["title"] + " " + d["body"])), d) for d in docs), key=lambda x: -x[0])
top = [d for n, d in top[:3] if n >= DOC_MIN]
if not top: return
user = f"ARGOMENTO: {t['title']}\nSINTESI:\n" + "\n".join(f"- {x['text']}" for x in t["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join(
f"[{n}] {d['title']} ({d['source']})\n{d['body'][:2500]}" for n, d in enumerate(top, 1))
r = chat(SYS_D, user, 2500) or {}
ref = lambda n: top[n - 1]["i"] if isinstance(n, int) and 1 <= n <= len(top) else None
fix = lambda l: [{"text": str(x["text"]), "doc": ref(x.get("doc"))} for x in l if isinstance(x, dict) and x.get("text")]
s = fix(r.get("summary") or [])
if s: t["summary"] = s
t["from_docs"] = [x for x in fix(r.get("from_docs") or [])[:3] if x["doc"] is not None]
def run(name, window_words=3000):
rec = db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
tx = _transcript(name)
dur = (rec and rec[0]) or (tx[-1][0] + 5 if tx else 0)
shots = _load(name, "shots.json", []); glossary = _load(name, "glossary.json", [])
crop_ok = any((s.get("view") or "").startswith("view_") for s in shots) # when crops exist, frames without one show no shared content
usable = lambda s: s["kind"] in CONTENT_KINDS and (not crop_ok or (s.get("view") or "").startswith("view_"))
evs = db.events(name, "meta", "present", "share_start", "share_stop", "chat", "hand")
names = db.speaker_names(name)
meta = [json.loads(e["text"]) for e in evs if e["kind"] == "meta"]
title = (meta[-1].get("title") or "") if meta else ""
shares = _shares(evs, dur)
att, src, counts = {}, set(), {}
for e in evs:
if e["kind"] != "present": continue
for p in json.loads(e["text"] or "[]"):
a = att.setdefault(p["who"], {"who": p["who"], "first_t": e["t"], "last_t": e["t"]})
a["last_t"] = max(a["last_t"], e["t"])
src.add("video" if e["who_key"] == "video" else "teams")
counts[p["who"]] = counts.get(p["who"], 0) + 1
attendees_source = "teams" if "teams" in src else "video" if src else "none"
for s in shots:
if s.get("presenter"): n = db.norm_name(s["presenter"]); counts[n] = counts.get(n, 0) + 1
for s in shares: counts[s["who"]] = counts.get(s["who"], 0) + 1
known = list(dict.fromkeys(_load(name, "docs.json", {"people": []}).get("people", []) +
[p["who"] for e in evs if e["kind"] == "present" and e["who_key"] != "video" for p in json.loads(e["text"] or "[]")]))
cmap = canon(counts, known, video=attendees_source == "video")
att, shares = _canon_att(att, cmap), _canon_shares(shares, cmap)
chats = [{"t": e["t"], "who": e["who"], "text": e["text"]} for e in evs if e["kind"] == "chat"]
# timeline items: (t, line)
items = [(t, f"[{mmss(t)}] " + (f"{names.get(sp, sp)}: " if sp else "") + x, len(x.split())) for t, sp, x in tx]
prev_text = None
for s in filter(usable, shots):
sh = next((x["who"] for x in shares if x["start"] <= s["t"] < x["end"]), None)
l = f"[{mmss(s['t'])}] [SCHERMO {s['kind']}{', condiviso da ' + sh if sh else ''}] {s.get('title') or ''}: {s.get('summary') or ''}"
if s.get("text") and s["text"] != prev_text: l += "\n testo: " + s["text"].replace("\n", " / ")[:600]
prev_text = s.get("text"); items.append((s["t"], l, len(l.split())))
items += [(c["t"], f"[{mmss(c['t'])}] [CHAT] {c['who']}: {c['text']}", 0) for c in chats]
items += [(e["t"], f"[{mmss(e['t'])}] [MANO ALZATA] {e['who']}", 0) for e in evs if e["kind"] == "hand"]
items.sort(key=lambda x: x[0])
system = SYS_A + (", ".join(glossary) or "nessuno")
topics, buf, words, wstart = [], [], 0, 0
def flush(end):
nonlocal buf, words
if not buf: return
d = chat(system, "\n".join(buf), 4000)
ts = d.get("topics") if d else None
if not ts:
ts = [{"title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"]}]
for t in ts:
t = {"title": str(t.get("title") or "Argomento"), "summary": list(t.get("summary") or []), "shown": list(t.get("shown") or []),
"decisions": list(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": list(t.get("open_questions") or []),
"start_s": secs(t.get("start")), "end_s": secs(t.get("end"))}
t["end_s"] = min(max(t["end_s"], t["start_s"] + 1), max(dur, t["start_s"] + 1))
topics.append(t)
buf, words = [], 0
for t, l, w in items:
if not buf: wstart = t
buf.append(l); words += w
if words >= window_words: flush(t)
flush(items[-1][0] if items else 0)
topics = _tidy(topics, dur)
for t in topics:
for a in t["actions"]:
if re.fullmatch(r"Speaker \d+", str(a.get("who", ""))) and a["who"] not in names: a["who"] = ""
docs = _load(name, "docs.json", {"items": [], "people": []})["items"]
for t in topics:
t["summary"] = [{"text": str(s), "doc": None} for s in t["summary"]]
t["from_docs"] = []
if docs: _pass_d(t, docs)
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800) or {}
tldr = [str(x) for x in (ov.get("tldr") or [])][:5]
title = title or str(ov.get("title") or "").strip()
good = [s for s in shots if s.get("lead") and usable(s) and len(s.get("text") or "") >= 40]
for t in topics: t["shots"] = []
for s in good:
if not topics: break
tp = next((t for t in topics if t["start_s"] <= s["t"] <= t["end_s"]), None) or min(topics, key=lambda t: abs(t["start_s"] - s["t"]))
tp["shots"].append(s)
for t in topics:
best = sorted(t["shots"], key=lambda s: -len(s.get("text") or ""))[:2]
t["shots"] = sorted(best, key=lambda s: s["t"])
cshots = [s for s in shots if usable(s)]
refs = {"tickets": {}, "urls": {}, "systems": {}, "emails": {}, "numbers": {}}
sysn = {}
for s in cshots:
e = s.get("entities") or {}
for k in ("urls", "emails", "numbers"):
for v in e.get(k, []): refs[k].setdefault(v, s["t"])
for v in e.get("systems", []): sysn.setdefault(v.lower(), (v, set()))[1].add(s["file"])
alltx = " ".join(x for _, _, x in tx).lower()
for low, (v, files) in sysn.items():
if len(v) >= 3 and (len(files) >= 2 or low in alltx):
refs["systems"][v] = min(s["t"] for s in cshots if s["file"] in files)
for t, _, x in tx:
for k in TICKET.findall(x): refs["tickets"].setdefault(k, t)
references = {"tickets": [{"key": k, "first_t": t} for k, t in refs["tickets"].items()],
"urls": [{"url": k, "first_t": t} for k, t in refs["urls"].items()],
"systems": [{"name": k, "first_t": t} for k, t in refs["systems"].items()],
"emails": [{"email": k, "first_t": t} for k, t in refs["emails"].items()],
"numbers": [{"value": k, "t": t} for k, t in refs["numbers"].items()]}
screen = []
for s in shots:
if not s.get("lead") or not usable(s): continue
r = {k: s.get(k) for k in ("t", "t_end", "kind", "title", "summary")}
if screen and (screen[-1]["title"] or "").lower() == (r["title"] or "").lower(): screen[-1]["t_end"] = r["t_end"]
else: screen.append(r)
m = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name)
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": title,
"tldr": tldr, "attendees": list(att.values()), "attendees_source": attendees_source, "known_spelling": bool(known),
"name_map": cmap, "shares": shares, "chat": chats, "references": references, "screen": screen, "topics": topics}
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_topics(name, topics)
def _head(i, t): return f"{i}. {t['title']} ({mmss(t['start_s'])}–{mmss(t['end_s'])})"
def named(name, rep):
nm = rep.get("name_map", {})
names = {l: nm.get(p, p) for l, p in db.speaker_names(name).items()}
return _deep(rep, lambda s: re.sub(r"\bSpeaker \d+\b", "un partecipante", _subst(s, names))), names
def render(name):
import markdown
from markdown.extensions.toc import slugify
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
docs = _load(name, "docs.json", None)
items = {x["i"]: x for x in (docs or {}).get("items", [])}
rep, names = named(name, rep)
segs = _load(name, "diar_segments.json", [])
link = lambda s: TICKET.sub(lambda m: f"[{m[0]}]({JIRA_BROWSE}/{m[0]})", s)
q = lambda s: re.sub(r'[\[\]"]', "", s or "")
md = [f"# {rep['meeting_title'] or 'Riunione'} — {rep['date']}", "", f"**Durata:** {int(rep['duration_s'] // 60)} min", "", "## In breve", ""]
md += [f"- {x}" for x in rep["tldr"]] + [""]
# participants
talk = {}
for s in segs:
p = names.get(s["label"])
if p: talk[p] = talk.get(p, 0) + s["end"] - s["start"]
video = rep["attendees_source"] == "video"
if video:
people = sorted({a["who"] for a in rep["attendees"]})
if talk or people: md += ["## Partecipanti", ""]
if talk: md += ["| Partecipante | Parlato |", "|---|---|"] + [f"| {p} | {int(v // 60)} min |" for p, v in talk.items()] + [""]
if people:
md += ["*Nomi letti dai fotogrammi (ortografia verificata sulla documentazione): verificare.*" if rep.get("known_spelling") else "*Nomi letti dai fotogrammi: verificare.*", "", ", ".join(people), ""]
else:
rows = {p: [v, None] for p, v in talk.items()}
for a in rep["attendees"]:
k = next((p for p in rows if p.lower() == a["who"].lower()), a["who"])
rows.setdefault(k, [0, None])[1] = f"{mmss(a['first_t'])}–{mmss(a['last_t'])}"
if rows:
md += ["## Partecipanti", "", "| Partecipante | Parlato | Presente |", "|---|---|---|"]
md += [f"| {p} | {f'{int(v[0] // 60)} min' if v[0] else '—'} | {v[1] or '—'} |" for p, v in rows.items()] + [""]
if rep["shares"]:
md += ["## Condivisioni schermo", ""] + [f"- {mmss(s['start'])}–{mmss(s['end'])} {s['who']}" for s in rep["shares"]] + [""]
heads = []
md += ["## Argomenti", ""]
for i, t in enumerate(rep["topics"], 1):
h = _head(i, t)
heads.append(h)
md.append(f"{i}. [{t['title']}](#{slugify(h, '-')})")
md.append("")
def cite(x):
x = x if isinstance(x, dict) else {"text": x, "doc": None}
c = f' [📄]({items[x["doc"]]["url"]} "{q(items[x["doc"]]["title"])}")' if x.get("doc") in items else ""
return f"- {x['text']}{c}"
for h, t in zip(heads, rep["topics"]):
md += [f"## {h}", "", "### Sintesi", ""] + [cite(x) for x in t["summary"]] + [""]
fd = [x for x in t.get("from_docs", []) if x.get("doc") in items]
if fd: md += ["### Dalla documentazione", ""] + [f"- 📄 {x['text']} — [{q(items[x['doc']]['title'])}]({items[x['doc']]['url']})" for x in fd] + [""]
pv = t.get("previous") or []
if pv: md += ["### Dalle riunioni precedenti", ""] + [f"- **{x['status']}** — {x['text']} — [{q(x.get('meeting') or x['name'])} {x['date']}, {q(x['topic'])} {mmss(x['t'])}]({GUI}/report?name={x['name']}#{x['anchor']})" for x in pv] + [""]
if t["shown"]: md += ["### Mostrato a schermo", ""] + [f"- {link(x)}" for x in t["shown"]] + [""]
if t["decisions"]: md += ["### Decisioni", ""] + [f"- {x}" for x in t["decisions"]] + [""]
if t["open_questions"]: md += ["### Domande aperte", ""] + [f"- {x}" for x in t["open_questions"]] + [""]
if t["actions"]:
md += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"]
md += [f"| {a.get('who', '')} | {a.get('what', '')} | {a.get('when', '')} |" for a in t["actions"]] + [""]
for s in t["shots"]:
alt = re.sub(r"[\[\]()]", "", s.get("title") or "")
sh = next((x["who"] for x in rep["shares"] if x["start"] <= s["t"] < x["end"]), None)
cap = f"{mmss(s['t'])} — " + (f"condiviso da {sh} — " if sh else "") + f"{s.get('title') or ''} — {s.get('summary') or ''}"
md += [f"![{alt}](shots/{s.get('view') or s['file']})", "", f"*{cap}*", ""]
if items:
md += ["## Documentazione correlata", ""]
for x in items.values():
md.append((f"- 🎫 [{q(x['key'])} — {q(x['title'])}]({x['url']}) — {x['status'] or ''}" if x["source"] == "jira" else f"- 📄 [{q(x['title'])}]({x['url']}) — Confluence")
+ (" — citato in riunione" if x.get("mentioned") else ""))
md.append("")
if rep["chat"]:
md += ["## Chat", ""] + [f"[{mmss(c['t'])}] **{c['who']}:** {c['text']} " for c in rep["chat"]] + [""]
r = rep["references"]
tk = ([f"[{x['key']}]({x['url']}) — {q(x['title'])}" for x in items.values() if x["source"] == "jira" and x.get("mentioned")] if docs is not None
else [f"[{x['key']}]({JIRA_BROWSE}/{x['key']}) — {mmss(x['first_t'])}" for x in r["tickets"]])
sy = [f"{x['name']} — {mmss(x['first_t'])}" for x in r["systems"]]
if tk or sy:
md += ["## Riferimenti", ""]
for k, v in (("Ticket", tk), ("Sistemi", sy)):
if v: md += [f"**{k}**", ""] + [f"- {x}" for x in v] + [""]
if rep["screen"]:
md += [f'<details markdown="1"><summary>Cronologia schermo ({len(rep["screen"])} schermate)</summary>', "",
"## Cronologia schermo", "", "| Da | A | Tipo | Titolo | Sintesi |", "|---|---|---|---|---|"]
cell = lambda x: (x or "").replace("|", "/").replace("\n", " ")
md += [f"| {mmss(s['t'])} | {mmss(s['t_end'] or 0)} | {s['kind']} | {cell(s['title'])} | {cell(s['summary'])} |" for s in rep["screen"]]
md += ["", "</details>", ""]
text = "\n".join(md)
(d / "report.md").write_text(text, encoding="utf-8")
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")
+117
View File
@@ -0,0 +1,117 @@
# /// script
# dependencies = []
# ///
"""Quality gate for meeting reports. uv run --script review.py <name> [<name>...]; exit 1 if any fails. No network/LLM."""
import base64, json, re, struct, sys
import db
from report import TICKET, _key, _sim
from shots import CONTENT_KINDS
ENG = {"the", "and", "of", "with", "is", "shows", "showing", "screenshot", "meeting", "displays"}
ITA = {"il", "la", "di", "che", "con", "della", "viene", "mostra", "sono", "per"}
def english(s):
w = re.findall(r"[a-zà-ú]+", str(s).lower())
e, i = sum(x in ENG for x in w), sum(x in ITA for x in w)
return e >= 3 and e > i
def jpeg_w(p):
b = p.read_bytes(); i = 2
while i < len(b):
if b[i] != 0xFF: i += 1; continue
m = b[i + 1]
if m in (0xC0, 0xC1, 0xC2): return struct.unpack(">H", b[i + 7:i + 9])[0]
i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
return 0
def review(name):
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
md = (d / "report.md").read_text(encoding="utf-8")
html = (d / "report.html").read_text(encoding="utf-8")
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
docs = json.loads((d / "docs.json").read_text(encoding="utf-8")) if (d / "docs.json").exists() else None
items = (docs or {}).get("items", [])
fails = []
F = lambda code, detail: fails.append(f"FAIL {code} {str(detail)[:200]}")
for m in re.finditer(r"\bSpeaker \d+\b", md): F("R1", md[max(0, m.start() - 40):m.end() + 40].replace("\n", " "))
T, dur = rep["topics"], rep["duration_s"]
if not max(3, dur / 900) <= len(T) <= max(4, dur / 150): F("R2", f"{len(T)} topics for {dur / 60:.0f} min")
for t in T[:-1]:
if t["end_s"] - t["start_s"] < 120: F("R2", f"short topic {t['title']} {t['end_s'] - t['start_s']}s")
for t in T:
for x in t["shown"]:
m = re.search(r"(\d\d):(\d\d)", x)
if not m or not t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30: F("R3", f"{t['title']}: {x}")
byfile = {}
for s in shots: byfile[s["file"]] = byfile[s.get("view") or s["file"]] = s
for sec in re.split(r"\n(?=## )", md):
imgs = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", sec)
if len(imgs) > 2: F("R4", f">2 images in {sec[:40]!r}")
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", md)
for f in used:
if byfile.get(f, {}).get("kind") not in CONTENT_KINDS: F("R4", f"{f} kind {byfile.get(f, {}).get('kind')}")
if any((s.get("view") or "").startswith("view_") for s in shots):
for f in used:
if not f.startswith("view_"): F("R4", f"uncropped image {f}")
texts = list(rep["tldr"])
for t in T:
texts += [x["text"] if isinstance(x, dict) else x for x in t["summary"]] + [x["text"] for x in t.get("from_docs", [])]
texts += [s.get("summary") or "" for s in t["shots"]]
for x in texts:
if english(x): F("R5", x)
sec = re.search(r"## Partecipanti\n(.*?)(?=\n## )", md, re.S)
people = []
for l in (sec[1].splitlines() if sec else []):
if l.startswith("|"):
c = l.split("|")[1].strip()
if c not in ("Partecipante", "") and not c.startswith("-"): people.append(c)
elif l.strip() and not l.startswith("*"): people += [x.strip() for x in l.split(",")]
for p in people:
if re.fullmatch(r"[A-Z]{1,3}", p) or "..." in p or "…" in p: F("R6", f"initials/truncated {p}")
for i, a in enumerate(people):
for b in people[i + 1:]:
if _sim(a, b) >= 0.82: F("R6", f"{a} ~ {b}")
S = rep["shares"]
for s in S:
if s["end"] - s["start"] < 20: F("R7", f"short share {s}")
for a, b in zip(S, S[1:]):
if a["who"] == b["who"] and b["start"] - a["end"] <= 60: F("R7", f"mergeable {a['who']} {a['end']}->{b['start']}")
rs = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", md, re.S)
ok = ({x["key"] for x in items if x["source"] == "jira" and x.get("mentioned")} if docs is not None
else {x["key"] for x in rep["references"]["tickets"]})
for k in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", rs[1] if rs else ""):
if k not in ok: F("R8", f"ticket {k}")
if "Numeri a schermo" in md or "**Email**" in md: F("R8", "numbers/email lists present")
if items:
if "## Documentazione correlata" not in md: F("R9", "missing Documentazione correlata")
urls = {x["url"] for x in items}
for u in re.findall(r"\[📄\]\(([^ )]+)", md):
if u not in urls: F("R9", f"citation url not in docs {u}")
if 'src="shots/' in html: F("R10", "unembedded image")
for b in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html):
if len(base64.b64decode(b)) <= 5000: F("R10", "tiny image")
if "## Trascrizione" in md: F("R11", "transcript present")
for f in set(used):
if f.startswith("view_") and jpeg_w(d / "shots" / f) < 600: F("R12", f"{f} narrow {jpeg_w(d / 'shots' / f)}px")
print("\n".join(f"[{name}] {x}" for x in fails))
print(f"{name}: " + ("PASS" if not fails else f"{len(fails)} failures"))
return not fails
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
sys.exit(0 if all([review(n) for n in sys.argv[1:]]) else 1)
+279
View File
@@ -0,0 +1,279 @@
# /// 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=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[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()
+170
View File
@@ -0,0 +1,170 @@
"""Screen content extraction: scene-change keyframes -> local VLM reads each into structured JSON."""
import base64, collections, json, re, subprocess, urllib.error, urllib.request
import db, llama
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
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.')
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.-]+")
def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode()
body = {"model": str(llama.MODEL), "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"}
req = urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"})
return json.load(_open(req, timeout=900))["choices"][0]["message"]["content"]
def read_shot(path):
json_mode = True
for _ in range(2):
try:
try: t = _ask(path, json_mode)
except urllib.error.HTTPError as e:
if e.code != 400 or not json_mode: raise
json_mode = False; t = _ask(path, False)
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
if isinstance(d, dict): return {**EMPTY, **d}
except (ValueError, KeyError): pass
return dict(EMPTY)
def _dedupe(xs):
seen, out = set(), []
for x in xs:
x = str(x).strip()
if x and x.lower() not in seen: seen.add(x.lower()); out.append(x)
return out
def _augment(d):
ent = d.get("entities") if isinstance(d.get("entities"), dict) else {}
blob = f"{d.get('text') or ''} {d.get('summary') or ''}"
for k in ("systems", "tickets", "urls", "numbers", "terms"): ent[k] = list(ent.get(k) or [])
ent["tickets"] += TICKET.findall(blob)
ent["urls"] += URL.findall(blob)
ent["emails"] = EMAIL.findall(blob)
d["entities"] = {k: _dedupe(v) for k, v in ent.items()}
d["people"] = _dedupe(d.get("people") or [])
def _bars(video, dur):
"""ffmpeg crop filter trimming black side bars, or None. dur: seconds (webm has no container duration)."""
w = int(subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", str(video)],
capture_output=True, text=True).stdout.strip() or 0)
r = subprocess.run(["ffmpeg", "-ss", str(dur / 2), "-i", str(video), "-vf", "cropdetect=24:16:0", "-frames:v", "60", "-f", "null", "-"],
capture_output=True, text=True)
m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr)
if not m or not w or int(m[-1][0]) < 0.5 * w: return None
return "crop=" + ":".join(m[-1])
def _view(path, box):
"""Crop the shared content out of a keyframe; returns the file name to display."""
from PIL import Image
if not CROP_BOX or not isinstance(box, list) or len(box) != 4 or not all(isinstance(v, (int, float)) for v in box): return path.name
im = Image.open(path); W, H = im.size
sx, sy = (1, 1) if max(box) > 1000 else (W / 1000, H / 1000)
x1, x2 = sorted((box[0] * sx, box[2] * sx)); y1, y2 = sorted((box[1] * sy, box[3] * sy))
x1, x2 = max(0, x1 - W * .01), min(W, x2 + W * .01); y1, y2 = max(0, y1 - H * .01), min(H, y2 + H * .01)
if x2 - x1 < .25 * W or y2 - y1 < .25 * H: return path.name
out = path.with_name(f"view_{path.stem}.jpg")
im.crop((int(x1), int(y1), int(x2), int(y2))).convert("RGB").save(out, quality=90)
return out.name
def _times(video, scene, bars=None):
r = subprocess.run(["ffmpeg", "-i", str(video), "-vf",
(bars + "," if bars else "") + f"fps=2,scale=640:-2,select='gt(scene,{scene})+isnan(prev_selected_t)+gte(t-prev_selected_t,60)',showinfo",
"-f", "null", "-"], capture_output=True, text=True)
return [float(m) for m in re.findall(r"pts_time:([\d.]+)", r.stderr)]
def run(name, max_frames=60, scene=0.05):
import imagehash
from PIL import Image
d = db.out_dir(name)
video = db.media(name)[1]
if video is None:
db.replace_shots(name, [])
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]")
return
sd = d / "shots"
sd.mkdir(exist_ok=True)
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
kept = [] # (t, path, hash)
bars = _bars(video, (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [0])[0] or 0)
for t in _times(video, scene, bars):
p = sd / f"shot_{int(t)//60:02d}m{int(t)%60:02d}s.jpg"
if any(k[1] == p for k in kept): continue # same second as a kept frame
subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(t), "-i", str(video), "-frames:v", "1",
*(["-vf", bars] if bars else []), "-q:v", "3", str(p)], check=True)
if not p.exists(): continue
h = imagehash.phash(Image.open(p))
if kept and h - kept[-1][2] <= 8: p.unlink(); continue
kept.append((t, p, h))
if len(kept) > max_frames:
keep = sorted({round(i * (len(kept) - 1) / (max_frames - 1)) for i in range(max_frames)})
for i, k in enumerate(kept):
if i not in keep: k[1].unlink()
kept = [kept[i] for i in keep]
srv = llama.start(log=d / "llama.log") # None if already running
rows = []
try:
for t, p, _ in kept:
r = read_shot(p); _augment(r)
r["view"] = _view(p, r.pop("content_box", None))
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True)
finally:
if srv: srv.terminate()
dur = (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [None])[0]
if dur is None: dur = rows[-1]["t"] + 60 if rows else 0
prev = None
for i, r in enumerate(rows):
r["t_end"] = rows[i + 1]["t"] if i + 1 < len(rows) else dur
key = (r["kind"], (r["title"] or "").lower()) if r["title"] else None
r["lead"] = not (key and key == prev)
prev = key
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_shots(name, rows)
cnt = collections.Counter()
for r in rows:
e = r["entities"]
for x in set(x for k in ("systems", "terms", "tickets") for x in e.get(k, []) if 3 <= len(x) <= 40): cnt[x] += 1
(d / "glossary.json").write_text(json.dumps([w for w, _ in cnt.most_common(150)], ensure_ascii=False), encoding="utf-8")
c = db.connect()
if c.execute("SELECT count(*) FROM call_events WHERE name=? AND kind='present' AND who_key<>'video'", (name,)).fetchone()[0] == 0:
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
ev = []
for r in rows:
ppl = [n for n in (db.norm_name(x) for x in r["people"]) if " " in n and len(n) > 4]
if ppl: ev.append((r["t"], "present", "video", "", json.dumps([{"key": "video", "who": n} for n in ppl], ensure_ascii=False)))
last = None
for r in rows:
pr = db.norm_name(r["presenter"]) if r["presenter"] else None
if pr != last:
if last: ev.append((r["t"], "share_stop", "video", last, ""))
if pr: ev.append((r["t"], "share_start", "video", pr, ""))
last = pr
if last: ev.append((dur, "share_stop", "video", last, ""))
titles = collections.Counter(r["meeting_title"] for r in rows if r["meeting_title"])
if titles: ev.append((0, "meta", "video", "", json.dumps({"title": titles.most_common(1)[0][0], "call_elapsed": "", "url": ""}, ensure_ascii=False)))
db.add_events(name, ev)
+28
View File
@@ -0,0 +1,28 @@
"""Map diarization labels to names seen in Teams call events."""
import json
import db
def run(name):
p = db.out_dir(name) / "diar_segments.json"
ev = db.events(name, "active", "caption")
if not p.exists() or not ev: return
segs = json.loads(p.read_text(encoding="utf-8"))
iv = []
for e in ev:
if not e["who"]: continue
a, b = (e["t"], e["t"] + 0.5) if e["kind"] == "active" else (e["t"] - 2, e["t"] + 2)
iv.append((a, b, e["who"]))
tot = {}
for s in segs:
d = tot.setdefault(s["label"], {})
for a, b, who in iv:
o = min(b, s["end"]) - max(a, s["start"])
if o > 0: d[who] = d.get(who, 0) + o
for label in {s["label"] for s in segs}:
d = tot.get(label, {})
if not d:
db.set_speaker_map(name, label, "", "auto", 0); continue
person = max(d, key=d.get); ov = d[person]
ok = ov >= 5 and ov / sum(d.values()) >= 0.4
db.set_speaker_map(name, label, person if ok else "", "auto", ov)
+91
View File
@@ -0,0 +1,91 @@
"""Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu)."""
import gc, json, subprocess, time
from pathlib import Path
import numpy as np
import db
HERE = Path(__file__).parent
NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
def _log(msg):
try:
from prefect import get_run_logger
get_run_logger().info(msg)
except Exception:
print(msg, flush=True)
def aggregate(segs):
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run."""
lines, buf, start, end = [], [], 0, 0
def flush():
if buf:
lines.append((int(start), " ".join(buf))); buf.clear()
for s, e, t in segs:
t = t.strip()
if not t: continue
if buf and s - end > 1: flush()
if not buf: start = s
buf.append(t); end = e
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
flush()
return lines
def _decode(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
return np.frombuffer(raw, np.float32)
def _cuda(audio, model, glossary):
import common
m, dev = common.load_model(model)
# ponytail: >~20 hotwords crowd whisper's prompt -> dropped text + repetition loops (seen with 60)
kw = {"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False} if glossary else {}
try:
segs, _ = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
return [(s.start, s.end, s.text) for s in segs], dev
finally:
del m; gc.collect()
def _npu(audio):
try:
import openvino_genai as ov
if not NPU_MODEL_DIR.exists():
from huggingface_hub import snapshot_download
try:
snapshot_download("OpenVINO/whisper-large-v3-turbo-fp16-ov", local_dir=NPU_MODEL_DIR)
except Exception:
subprocess.run(["optimum-cli", "export", "openvino", "--model", "openai/whisper-large-v3-turbo",
"--weight-format", "fp16", str(NPU_MODEL_DIR)], check=True)
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True)
if not res.chunks: raise RuntimeError("no chunks returned")
return [(c.start_ts, c.end_ts, c.text) for c in res.chunks]
except Exception as e:
raise RuntimeError(f"NPU failed: {e!r}")
def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path | None = None):
audio = db.out_dir(name) / "audio.opus"
gl = db.out_dir(name) / "glossary.json"
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
t0 = time.time()
if device == "npu":
segs, used = _npu(audio), "npu"
else:
segs, used = _cuda(audio, model, glossary)
lines = aggregate(segs)
txt = "\n".join(f"[{t//60:02d}:{t%60:02d}] {x}" for t, x in lines)
for l in txt.splitlines(): _log(l)
secs = time.time() - t0
if out_path is not None:
out_path.write_text(txt, encoding="utf-8")
return secs
(db.OUT / f"{name}.txt").write_text(txt, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs)
return secs
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
run: [{
method: "fs.open",
params: {
path: "app/ext"
}
}]
}
+104
View File
@@ -0,0 +1,104 @@
module.exports = {
requires: {
bundle: "ai"
},
run: [
{
method: "shell.run",
params: {
message: "conda install -y -c conda-forge ffmpeg 7zip"
}
},
// llama.cpp server (CUDA 13) for the Qwen VLM + bge-m3 embeddings
{
method: "fs.download",
params: {
uri: [
"https://github.com/ggml-org/llama.cpp/releases/download/b11889/llama-b11889-bin-win-cuda-13.4-x64.zip",
"https://github.com/ggml-org/llama.cpp/releases/download/b11889/cudart-llama-bin-win-cuda-13.4-x64.zip"
],
dir: "app/bin"
}
},
{
method: "shell.run",
params: {
path: "app/bin",
message: [
"7z x -y llama-b11889-bin-win-cuda-13.4-x64.zip",
"7z x -y cudart-llama-bin-win-cuda-13.4-x64.zip"
]
}
},
{
method: "fs.rm",
params: {
path: "app/bin/llama-b11889-bin-win-cuda-13.4-x64.zip"
}
},
{
method: "fs.rm",
params: {
path: "app/bin/cudart-llama-bin-win-cuda-13.4-x64.zip"
}
},
// speaker diarization (sherpa-onnx)
{
method: "fs.download",
params: {
uri: "https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx",
path: "app/models/emb.onnx"
}
},
{
method: "fs.download",
params: {
uri: "https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/sherpa-onnx-pyannote-segmentation-3-0.tar.bz2",
path: "app/models/seg.tar.bz2"
}
},
{
method: "shell.run",
params: {
path: "app/models",
message: "tar -xjf seg.tar.bz2"
}
},
// embeddings for cross-meeting memory
{
method: "hf.download",
params: {
path: "app",
_: ["gpustack/bge-m3-GGUF", "bge-m3-Q8_0.gguf"],
"local-dir": "models"
}
},
// LLM + vision projector (~23 GB)
{
method: "hf.download",
params: {
path: "app",
_: ["unsloth/Qwen3.6-35B-A3B-GGUF", "mmproj-BF16.gguf", "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"],
"local-dir": "models"
}
},
// pre-build the uv script environments (whisper, prefect, sherpa-onnx, openvino, ...)
{
method: "shell.run",
params: {
path: "app",
message: [
"uv sync --script flow.py",
"uv sync --script server.py",
"uv sync --script memory.py"
]
}
},
{
method: "notify",
params: {
html: "Installation finished! Click 'Start', then load the browser extension from the 'Extension' tab."
}
}
]
}
+97
View File
@@ -0,0 +1,97 @@
module.exports = {
version: "7.0",
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 running = {
install: info.running("install.js"),
start: info.running("start.js"),
update: info.running("update.js"),
reset: info.running("reset.js")
}
if (running.install) {
return [{
default: true,
icon: "fa-solid fa-plug",
text: "Installing",
href: "install.js",
}]
} else if (installed) {
if (running.start) {
let local = info.local("start.js")
if (local && local.url) {
return [{
default: true,
icon: "fa-solid fa-rocket",
text: "Open Web UI",
href: local.url,
}, {
icon: "fa-solid fa-diagram-project",
text: "Prefect",
href: "http://127.0.0.1:4200",
}, {
icon: "fa-solid fa-puzzle-piece",
text: "Extension",
href: "ext.js",
}, {
icon: 'fa-solid fa-terminal',
text: "Terminal",
href: "start.js",
}]
} else {
return [{
default: true,
icon: 'fa-solid fa-terminal',
text: "Terminal",
href: "start.js",
}]
}
} else if (running.update) {
return [{
default: true,
icon: 'fa-solid fa-terminal',
text: "Updating",
href: "update.js",
}]
} else if (running.reset) {
return [{
default: true,
icon: 'fa-solid fa-terminal',
text: "Resetting",
href: "reset.js",
}]
} else {
return [{
default: true,
icon: "fa-solid fa-power-off",
text: "Start",
href: "start.js",
}, {
icon: "fa-solid fa-puzzle-piece",
text: "Extension",
href: "ext.js",
}, {
icon: "fa-solid fa-plug",
text: "Update",
href: "update.js",
}, {
icon: "fa-solid fa-plug",
text: "Install",
href: "install.js",
}, {
icon: "fa-regular fa-circle-xmark",
text: "Reset",
href: "reset.js",
}]
}
} else {
return [{
default: true,
icon: "fa-solid fa-plug",
text: "Install",
href: "install.js",
}]
}
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"title": "Teams Whisper",
"description": "Record Teams calls and turn them into meeting reports, fully local",
"platform": "win32",
"gpu": "nvidia"
}
+14
View File
@@ -0,0 +1,14 @@
module.exports = {
// keeps app/out (your meetings, reports, meetings.db)
run: [{
method: "fs.rm",
params: {
path: "app/bin"
}
}, {
method: "fs.rm",
params: {
path: "app/models"
}
}]
}
+23
View File
@@ -0,0 +1,23 @@
module.exports = {
daemon: true,
run: [
{
method: "shell.run",
params: {
path: "app",
// port stays 18765: the browser extension's host_permissions hardcode it
message: "uv run --script server.py",
on: [{
event: "/(http:\\/\\/[0-9.:]+)/",
done: true
}]
}
},
{
method: "local.set",
params: {
url: "{{input.event[1]}}"
}
}
]
}
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
run: [{
method: "shell.run",
params: {
message: "git pull"
}
}]
}