Add explanatory comments across codebase
This commit is contained in:
@@ -2,12 +2,17 @@
|
||||
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,
|
||||
@@ -24,27 +29,36 @@ CREATE TABLE IF NOT EXISTS speaker_map(name TEXT, label TEXT, person TEXT, sourc
|
||||
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')) "
|
||||
@@ -52,6 +66,7 @@ def set_status(name: str, status: str, error: str | None = None):
|
||||
(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")
|
||||
@@ -60,6 +75,7 @@ def replace_lines(name, 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")
|
||||
@@ -69,11 +85,13 @@ def replace_shots(name, 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")
|
||||
@@ -83,6 +101,7 @@ def replace_topics(name, 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")
|
||||
@@ -91,12 +110,14 @@ def replace_memory(name, rows):
|
||||
c.execute("COMMIT")
|
||||
|
||||
|
||||
# Per-meeting folder out/<name>/, 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)
|
||||
@@ -110,13 +131,16 @@ def meta(name) -> dict:
|
||||
|
||||
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/<name>/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 "<step>" or "<step>@<model>")
|
||||
@@ -124,17 +148,20 @@ SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@q
|
||||
"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)
|
||||
|
||||
@@ -152,6 +179,7 @@ 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,
|
||||
@@ -169,8 +197,10 @@ def step(name, status, key=None):
|
||||
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)
|
||||
|
||||
@@ -187,6 +217,7 @@ def tick(name, done, total, note=""):
|
||||
|
||||
def media(name):
|
||||
"""(audio source, video source) in out/<name>/: source.<ext> (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}"
|
||||
@@ -196,12 +227,15 @@ def media(name):
|
||||
|
||||
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]
|
||||
@@ -215,25 +249,31 @@ def add_events(name, 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())
|
||||
|
||||
Reference in New Issue
Block a user