"""SQLite index of meetings (out/meetings.db) + shared helpers.""" import json, re, sqlite3, subprocess, time from pathlib import Path # Everything lives under out/ next to this file: the DB and per-meeting folders. HERE = Path(__file__).parent OUT = HERE / "out" DB = OUT / "meetings.db" GLOBAL = OUT / "_global" # llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs, edge profile GLOBAL.mkdir(parents=True, exist_ok=True) # SQLite schema, applied on every connect(). FTS5 tables back full-text search; # unicode61 with remove_diacritics 2 so accented and unaccented words match. # speaker_map.source: "manual" entries are never overwritten by automatic matches. # memory.vec: bge-m3 float32 embedding bytes (decoded in memory.py). 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); """ # Pipeline statuses written to recordings.status, in run order. STATUSES = ["recording", "queued", "audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory", "done", "error"] # Event kinds accepted in call_events (Teams web-call signals). EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "caption", "chat", "hand"} # Open a connection and apply the schema. Each caller opens its own connection. def connect() -> sqlite3.Connection: OUT.mkdir(exist_ok=True) # Autocommit (isolation_level=None) so BEGIN/COMMIT below are explicit; wait up to 30 s on locks. c = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False) # WAL: the GUI can read while the flow writes. c.execute("PRAGMA journal_mode=WAL") c.row_factory = sqlite3.Row # Idempotent: every CREATE uses IF NOT EXISTS. c.executescript(SCHEMA) return c # Insert or update a recordings row; only the kwargs given are written. def upsert_recording(name: str, **f): c = connect() cols = ["name", *f] # Empty kwargs -> "name=name" no-op, keeps the ON CONFLICT clause valid SQL. 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()]) # Upsert status (and error) for a meeting; updated_at is SQLite UTC time. 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)) # Replace all transcript lines of a meeting; rows are (t, speaker, text). 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") # Replace shots; shot_text is the FTS mirror of shots and must change with it. 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))) # FTS body: extracted text plus LLM summary. 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") # Replace topics; each row also keeps the full topic dict as JSON. 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") # Replace memory rows for a meeting (rows already carry vec bytes, see SCHEMA). 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") # Per-meeting folder out//, created on demand. def out_dir(name) -> Path: d = OUT / name d.mkdir(parents=True, exist_ok=True) return d # Per-meeting logs folder (e.g. embed.log). def logs(name) -> Path: d = out_dir(name) / "logs" d.mkdir(exist_ok=True) return d def meta(name) -> dict: """out//meta.json: {"title": manual title, "upload": original filename}; absent keys = not set.""" return _jload(OUT / name / "meta.json", {}) def set_meta(name, **kw): m = {**meta(name), **kw} # Falsy values (None, "") are dropped rather than stored. _jsave(out_dir(name) / "meta.json", {k: v for k, v in m.items() if v}) # ---- progress + ETA (flow writes out//progress.json, server reads it) ---- ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses # Flow step name -> GUI status it maps to (render and title roll into memory). FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying", "shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory", "title": "memory"} # Learned speeds, merged over SPM at runtime. STATS = GLOBAL / "step_stats.json" # seconds of work per minute of audio, measured 2026-11-02 on RTX 500 Ada 4 GB + Core Ultra 7 155H (40-min call); # replaced by a moving average of real runs as soon as one finishes (keys "" or "@") SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30, "docs": 2, "report@qwen35b": 21, "report@qwen4b": 7, "report": 15, "memory": 1} # Read JSON; missing or corrupt file -> default. def _jload(p, default): try: return json.loads(p.read_text(encoding="utf-8")) except (OSError, ValueError): return default # Write JSON via a temp file then rename, so readers never see a partial file. def _jsave(p, o): tmp = p.with_suffix(".tmp"); tmp.write_text(json.dumps(o), encoding="utf-8") try: tmp.replace(p) except OSError: pass # reader had it open: next tick writes again # Seconds of work per audio minute for a step; a measured value beats the default. def spm(key): return {**SPM, **_jload(STATS, {})}.get(key) or SPM.get(key.split("@")[0], 5) def delete_recording(name): """Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out//.""" import shutil c = connect() for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"): c.execute(f"DELETE FROM {t} WHERE name=?", (name,)) shutil.rmtree(OUT / name, ignore_errors=True) def progress(name): return _jload(OUT / name / "progress.json", None) # Fresh progress.json for a run; 'start' is the first step to execute (via FROM). def progress_start(name, start_from): now = time.time() _jsave(out_dir(name) / "progress.json", {"run_start": now, "start": FROM.get(start_from, "audio"), "step": None, "key": None, "step_start": now, "done": 0, "total": 0, "note": "", "updated": now, "steps": []}) def step(name, status, key=None): """Close the previous step (learn its speed), open `status` ("done" closes the run).""" set_status(name, status) p = progress(name) if not p: return now = time.time() if p["step"]: p["steps"].append([p["step"], p["step_start"], now]) row = connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() mins = (row[0] or 0) / 60 if row else 0 if mins > 1 and now - p["step_start"] > 5: # skip no-op steps # Learn speed (seconds per audio minute); exponential average with the previous value. st = _jload(STATS, {}); k = p["key"] or p["step"]; v = (now - p["step_start"]) / mins st[k] = round(v if k not in st else 0.5 * st[k] + 0.5 * v, 2); _jsave(STATS, st) # 'done' clears step so the GUI shows the run as finished. p.update(step=None if status == "done" else status, key=key or status, step_start=now, done=0, total=0, note="", updated=now) _jsave(OUT / name / "progress.json", p) def tick(name, done, total, note=""): """In-step progress; also the heartbeat the GUI uses to show the run is alive.""" p = progress(name) if not p: return now = time.time() if done == 0 and total: p["t0"] = now # loop starts now: rate excludes model load / frame extraction before it p.update(done=done, total=total, note=note, updated=now) _jsave(OUT / name / "progress.json", p) def media(name): """(audio source, video source) in out//: source. (the CLI recorder may write source.wav + source.mp4); .wav/.m4a/.mp3 have no video.""" # First existing candidate wins (order = preference). def first(*exts): for e in exts: p = OUT / name / f"source{e}" if p.exists(): return p return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov") def duration(path) -> float: """Seconds. MediaRecorder webm has no container duration (N/A): fall back to a copy-demux pass (~1 s/h).""" # Fast path: container duration from ffprobe (empty output when missing). p = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)], capture_output=True, text=True) try: return float(p.stdout.strip()) except ValueError: pass # Slow path: decode the whole stream with -c copy; ffmpeg prints time= progress to stderr. r = subprocess.run(["ffmpeg", "-v", "error", "-stats", "-i", str(path), "-map", "0", "-c", "copy", "-f", "null", "-"], capture_output=True, text=True) # Take the last time=HH:MM:SS.ss value (end of stream). m = re.findall(r"time=(\d+):(\d\d):(\d\d(?:\.\d+)?)", r.stderr) if not m: raise ValueError(((p.stderr or r.stderr).strip() or "nessuna durata")[-300:]) h, mi, s = m[-1] return int(h) * 3600 + int(mi) * 60 + float(s) 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=?" # Optional kind filter; ORDER BY t gives timeline order. 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: # Only real names: an empty or NULL person keeps the raw speaker label. 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,))} # Upsert speaker label -> person, with its source (auto/manual) and overlap seconds. 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 " # Manual names win; automatic matches never overwrite them. "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() # Groups: "Last, First" plus an optional trailing "(...)" suffix, which is dropped. m = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw) if not m: return raw # Title-case only ALL-CAPS words; mixed-case words are kept as written. return " ".join(w.title() if w.isupper() else w for w in f"{m[2]} {m[1]}".split())