Apply ruff lint and rename cryptic identifiers to readable names

This commit is contained in:
Stefano Zini
2026-11-05 09:09:20 +01:00
parent 19de4654ff
commit ead33657c7
24 changed files with 4459 additions and 1856 deletions
+293 -113
View File
@@ -1,12 +1,20 @@
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
import json, re, sqlite3, subprocess, time
import contextlib
import json
import re
import sqlite3
import subprocess
import 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 = (
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;
@@ -30,7 +38,20 @@ CREATE TABLE IF NOT EXISTS memory(name TEXT, idx INTEGER, kind TEXT, t REAL, mee
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"]
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"}
@@ -39,89 +60,131 @@ EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "captio
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)
conn = 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
conn.execute("PRAGMA journal_mode=WAL")
conn.row_factory = sqlite3.Row
# Idempotent: every CREATE uses IF NOT EXISTS.
c.executescript(SCHEMA)
return c
conn.executescript(SCHEMA)
return conn
# Insert or update a recordings row; only the kwargs given are written.
def upsert_recording(name: str, **f):
c = connect()
cols = ["name", *f]
def upsert_recording(name: str, **fields):
conn = connect()
cols = ["name", *fields]
# 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()])
sets = ",".join(f"{column}=excluded.{column}" for column in fields) or "name=name"
conn.execute(
f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) "
f"ON CONFLICT(name) DO UPDATE SET {sets}",
[name, *fields.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))
conn = connect()
conn.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")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM lines WHERE name=?", (name,))
conn.executemany(
"INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)",
[(name, time_s, speaker, text) for time_s, speaker, text in rows],
)
conn.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)))
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM shots WHERE name=?", (name,))
conn.execute("DELETE FROM shot_text WHERE name=?", (name,))
for shot in rows:
conn.execute(
"INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)",
(
name,
shot["t"],
shot.get("t_end"),
shot["file"],
shot.get("kind"),
shot.get("title"),
shot.get("app"),
shot.get("summary"),
shot.get("text"),
json.dumps(shot.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")
conn.execute(
"INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)",
(
name,
shot["t"],
shot.get("title") or "",
f"{shot.get('text') or ''}\n{shot.get('summary') or ''}",
),
)
conn.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")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM topics WHERE name=?", (name,))
conn.executemany(
"INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)",
[
(
name,
index,
topic["title"],
topic.get("start_s"),
topic.get("end_s"),
json.dumps(topic, ensure_ascii=False),
)
for index, topic in enumerate(topics)
],
)
conn.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")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM memory WHERE name=?", (name,))
conn.executemany(
"INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)",
rows,
)
conn.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
folder = OUT / name
folder.mkdir(parents=True, exist_ok=True)
return folder
# Per-meeting logs folder (e.g. embed.log).
def logs(name) -> Path:
d = out_dir(name) / "logs"
d.mkdir(exist_ok=True)
return d
folder = out_dir(name) / "logs"
folder.mkdir(exist_ok=True)
return folder
def meta(name) -> dict:
@@ -129,36 +192,71 @@ def meta(name) -> dict:
return _jload(OUT / name / "meta.json", {})
def set_meta(name, **kw):
m = {**meta(name), **kw}
def set_meta(name, **fields):
merged = {**meta(name), **fields}
# Falsy values (None, "") are dropped rather than stored.
_jsave(out_dir(name) / "meta.json", {k: v for k, v in m.items() if v})
_jsave(out_dir(name) / "meta.json", {key: value for key, value in merged.items() if value})
# ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ----
ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses
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"}
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>")
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}
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
def _jload(path, default):
try:
return json.loads(path.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
def _jsave(path, data):
tmp_path = path.with_suffix(".tmp")
tmp_path.write_text(json.dumps(data), encoding="utf-8")
# reader had it open: next tick writes again
with contextlib.suppress(OSError):
tmp_path.replace(path)
# Seconds of work per audio minute for a step; a measured value beats the default.
@@ -169,9 +267,19 @@ def spm(key):
def delete_recording(name):
"""Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out/<name>/."""
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,))
conn = connect()
for table in (
"recordings",
"lines",
"shots",
"shot_text",
"topics",
"call_events",
"speaker_map",
"memory",
):
conn.execute(f"DELETE FROM {table} WHERE name=?", (name,))
shutil.rmtree(OUT / name, ignore_errors=True)
@@ -182,82 +290,149 @@ def progress(name):
# 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": []})
_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
state = progress(name)
if not state:
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()
if state["step"]:
state["steps"].append([state["step"], state["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
if mins > 1 and now - state["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)
stats = _jload(STATS, {})
stat_key = state["key"] or state["step"]
speed = (now - state["step_start"]) / mins
stats[stat_key] = round(
speed if stat_key not in stats else 0.5 * stats[stat_key] + 0.5 * speed, 2
)
_jsave(STATS, stats)
# '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)
state.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", state)
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
state = progress(name)
if not state:
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)
if done == 0 and total:
state["t0"] = now # loop starts now: rate excludes model load / frame extraction before it
state.update(done=done, total=total, note=note, updated=now)
_jsave(OUT / name / "progress.json", state)
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."""
"""(audio source, video source) in out/<name>/: source.<suffix> (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")
for suffix in exts:
candidate = OUT / name / f"source{suffix}"
if candidate.exists():
return candidate
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
probe = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
capture_output=True,
text=True,
)
try:
return float(probe.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)
result = 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)
times = re.findall(r"time=(\d+):(\d\d):(\d\d(?:\.\d+)?)", result.stderr)
if not times:
raise ValueError(((probe.stderr or result.stderr).strip() or "nessuna durata")[-300:])
hours, minutes, seconds = times[-1]
return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
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])
connect().executemany(
"INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
[(name, *row) for row in rows],
)
def events(name, *kinds):
q = "SELECT * FROM call_events WHERE name=?"
query = "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()
if kinds:
query += f" AND kind IN ({','.join('?' * len(kinds))})"
return connect().execute(query + " 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,))}
return {
row["label"]: row["person"]
for row 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.
@@ -266,14 +441,19 @@ def set_speaker_map(name, label, person, source, overlap_s=None):
"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))
"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'."""
"""Port of norm() in suffix/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
match = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw)
if not match:
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())
return " ".join(
word.title() if word.isupper() else word for word in f"{match[2]} {match[1]}".split()
)