460 lines
16 KiB
Python
460 lines
16 KiB
Python
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
|
|
|
|
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.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.
|
|
conn = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False)
|
|
# WAL: the GUI can read while the flow writes.
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.row_factory = sqlite3.Row
|
|
# Idempotent: every CREATE uses IF NOT EXISTS.
|
|
conn.executescript(SCHEMA)
|
|
return conn
|
|
|
|
|
|
# Insert or update a recordings row; only the kwargs given are written.
|
|
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"{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):
|
|
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):
|
|
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):
|
|
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.
|
|
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):
|
|
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):
|
|
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:
|
|
folder = OUT / name
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
return folder
|
|
|
|
|
|
# Per-meeting logs folder (e.g. embed.log).
|
|
def logs(name) -> Path:
|
|
folder = out_dir(name) / "logs"
|
|
folder.mkdir(exist_ok=True)
|
|
return folder
|
|
|
|
|
|
def meta(name) -> dict:
|
|
"""out/<name>/meta.json: {"title": manual title, "upload": original filename}; absent keys = not set."""
|
|
return _jload(OUT / name / "meta.json", {})
|
|
|
|
|
|
def set_meta(name, **fields):
|
|
merged = {**meta(name), **fields}
|
|
# Falsy values (None, "") are dropped rather than stored.
|
|
_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
|
|
# 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>")
|
|
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(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(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.
|
|
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/<name>/."""
|
|
import shutil
|
|
|
|
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)
|
|
|
|
|
|
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)
|
|
state = progress(name)
|
|
if not state:
|
|
return
|
|
now = time.time()
|
|
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 - state["step_start"] > 5: # skip no-op steps
|
|
# Learn speed (seconds per audio minute); exponential average with the previous value.
|
|
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.
|
|
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."""
|
|
state = progress(name)
|
|
if not state:
|
|
return
|
|
now = time.time()
|
|
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.<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 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).
|
|
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.
|
|
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).
|
|
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, *row) for row in rows],
|
|
)
|
|
|
|
|
|
def events(name, *kinds):
|
|
query = "SELECT * FROM call_events WHERE name=?"
|
|
# Optional kind filter; ORDER BY t gives timeline order.
|
|
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 {
|
|
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.
|
|
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 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.
|
|
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(
|
|
word.title() if word.isupper() else word for word in f"{match[2]} {match[1]}".split()
|
|
)
|