Files
teams-whisper/app/server.py
T

1313 lines
53 KiB
Python

# /// 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
import contextlib
import json
import mimetypes
import os
import re
import sqlite3
import subprocess
import tempfile
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
# Sibling modules: db (SQLite, paths), llama (model servers), memory (Q&A).
import db
import llama
import memory
# CLI: the GUI/extension port.
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--port", type=int, default=18765)
args = arg_parser.parse_args()
# app/ folder: flow.py, ui/, and the modules live here.
HERE = Path(__file__).parent
# Meeting folders root; created at startup.
out_root = db.OUT
out_root.mkdir(exist_ok=True)
# Process-wide state shared by request threads and the queue runner.
RECEIVING = {} # name -> {"last": ts of last chunk}
JOBS = {} # name -> Popen
CROP = {} # name -> % of running crop
PREFECT = "http://127.0.0.1:4200"
# Child env: our env minus Python home vars that confuse nested uv runs.
ENV = {
key: value
for key, value in os.environ.items()
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
}
ENV.update(PREFECT_API_URL=PREFECT + "/api", NO_PROXY="127.0.0.1,localhost")
# Proxy-free opener for local HTTP calls (Prefect, llama-server).
NOPROXY = urllib.request.build_opener(urllib.request.ProxyHandler({}))
# Edge path; %ProgramFiles(x86)% expanded by Windows env.
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}}"
)
# Serializes ask_once: one llama start/stop at a time.
LOCK = threading.Lock()
# Allowed resume points for /run and /run_all.
STEPS = [
"audio",
"transcribe",
"diarize",
"speakers",
"shots",
"docs",
"report",
"memory",
"render",
"title",
]
# Pending runs (name, start_from, speakers), drained FIFO by pump().
QUEUE = [] # (name, start_from, speakers) waiting for the single runner, oldest first
BATCH = None # runner thread, None when idle
QLOCK = threading.Lock()
# Render report.html to report.pdf via headless Edge.
def make_pdf(name):
meeting_dir = out_root / name
html = meeting_dir / "report.html"
pdf = meeting_dir / "report.pdf"
if not html.exists():
return None
# Re-render only when the HTML is newer than the PDF.
if not pdf.exists() or pdf.stat().st_mtime < html.stat().st_mtime:
print_html = meeting_dir / "_print.html"
# Print copy: expand <details>, add print CSS; original report untouched.
print_html.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:
with (
tempfile.TemporaryDirectory(prefix="edge-pdf-", ignore_cleanup_errors=True) as prof
): # throwaway profile: nothing left in the meeting folder, parallel calls can't collide
edge_result = subprocess.run(
[
str(EDGE),
"--headless",
"--disable-gpu",
"--no-first-run",
"--no-pdf-header-footer",
f"--user-data-dir={prof}",
f"--print-to-pdf={pdf}",
print_html.as_uri(),
],
capture_output=True,
timeout=180,
)
finally:
print_html.unlink(missing_ok=True)
if not pdf.exists():
raise RuntimeError(edge_result.stderr.decode(errors="replace")[-500:])
return pdf
def ask_events(query):
"""Start models, yield memory.ask_stream events, always stop what we started (serialized: one ask at a time)."""
with LOCK:
started = []
try:
# Embed (CPU) and chat LLM start first; both are stopped in finally.
started = [
proc
for proc in (
llama.start_embed(log=db.GLOBAL / "embed.log"),
llama.start(vision=False, log=db.GLOBAL / "llama.log"),
)
if proc is not None
]
yield from memory.ask_stream(query)
finally:
for proc in started:
proc.terminate()
def ask_once(query):
"""Whole answer as {"answer", "sources"} (the non-streaming /ask)."""
events = list(ask_events(query))
return {
"answer": "".join(event["t"] for event in events if "t" in event).strip()
or "Risposta non disponibile.",
"sources": events[0]["sources"],
}
def now():
return time.strftime("%Y-%m-%d %H:%M:%S")
def launch(name, start_from, speakers=0):
"""Queue a flow run. One flow at a time (one GPU): the rest wait. False if `name` is already running or queued."""
global BATCH
with QLOCK:
job = JOBS.get(name)
if (job and job.poll() is None) or any(queued_item[0] == name for queued_item in QUEUE):
return False
QUEUE.append((name, start_from, speakers))
db.set_status(name, "queued")
if BATCH is None:
BATCH = threading.Thread(target=pump, daemon=True)
BATCH.start()
return True
def pump():
"""Drain QUEUE serially, oldest first so memory links point backwards."""
global BATCH
while True:
with QLOCK:
if not QUEUE:
BATCH = None
return
name, start_from, speakers = QUEUE.pop(0)
# One flow process per meeting: uv resolves deps, then runs flow.py.
JOBS[name] = subprocess.Popen(
[
"uv",
"run",
"--script",
"flow.py",
name,
"--from",
start_from,
"--speakers",
str(speakers),
],
cwd=HERE,
env=ENV,
stdout=open(db.logs(name) / "flow.log", "ab"), # noqa: SIM115
stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP,
)
# Block until this flow ends, then the next queued run starts.
JOBS[name].wait()
# Queue all meetings with media (not recording) to re-run from start_from.
def run_all(start_from):
if BATCH is not None:
return False
for row in db.connect().execute(
"SELECT name FROM recordings WHERE status!='recording' ORDER BY name"
):
if db.media(row[0])[0]:
launch(row[0], start_from) # no source video (drop_video): no re-elaboration
return True
# Health check of Prefect API; any error counts as down.
def prefect_up():
try:
NOPROXY.open(PREFECT + "/api/health", timeout=2)
return True
except Exception:
return False
# Start Prefect detached (logs to prefect.log) unless its health check passes.
def start_prefect():
if prefect_up():
return
# flow.py's env already has Prefect: works offline (the old `uv run --with prefect` re-resolved from PyPI and died without DNS)
subprocess.Popen(
["uv", "run", "--script", "flow.py", "--prefect-server"],
cwd=HERE,
env=ENV,
stdout=open(db.GLOBAL / "prefect.log", "ab"), # noqa: SIM115
stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP,
)
# Rebuild DB rows for meetings that exist only on disk.
def backfill():
conn = db.connect()
have = {row[0] for row in conn.execute("SELECT name FROM recordings")}
# Register meetings with media on disk that the DB lacks.
for path in sorted(out_root.glob("*/source.*")):
meeting = path.parent.name
# Skip rows already known, unsupported extensions, and .webm still growing (mtime < 60 s).
if (
meeting in have
or path.suffix.lower() not in UPLOAD_EXT
or (path.suffix == ".webm" and time.time() - path.stat().st_mtime < 60)
):
continue
db.upsert_recording(
meeting,
source="ext" if meeting.startswith("teams_") else "meet",
status="done" if (path.parent / "report.html").exists() else "queued",
bytes=path.stat().st_size,
)
have.add(meeting)
TITLES = {} # name -> (report.json mtime, "title — date")
def title(name):
report_file = out_root / name / "report.json"
if not report_file.exists():
return db.meta(name).get("title", "")
mtime = report_file.stat().st_mtime
if TITLES.get(name, (0,))[0] != mtime:
try:
report = json.loads(report_file.read_text(encoding="utf-8"))
TITLES[name] = (
mtime,
f"{report.get('meeting_title') or ''} — {report.get('date') or ''}",
)
except ValueError:
return ""
return TITLES[name][1]
# True while a run is queued or a flow process is alive (GPU in use).
def busy():
return bool(QUEUE) or any(proc.poll() is None for proc in JOBS.values())
def ask_blocked():
return (
busy() and llama.current(False) not in llama.REMOTE
) # cloud text model: no GPU contention, embed is CPU
def set_title(name, new_title):
"""Manual meeting title (out/<name>/meta.json, wins over Teams/LLM titles); empty clears it. Patches report.json and re-renders."""
new_title = " ".join(new_title.split())[:200]
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone():
return False
db.set_meta(name, title=new_title)
report_json = out_root / name / "report.json"
if report_json.exists() and new_title:
report = json.loads(report_json.read_text(encoding="utf-8"))
report["meeting_title"] = new_title
report_json.write_text(json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")
launch(name, "render")
return True
def flow_pids(name=None):
"""PIDs of the top `uv run --script flow.py <name>` processes (also flows started before a server restart)."""
# PowerShell CIM gives full CommandLine; tasklist and wmic cannot.
result = subprocess.run(
[
"powershell",
"-NoProfile",
"-c",
'Get-CimInstance Win32_Process -Filter "Name=\'uv.exe\'" | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }',
],
capture_output=True,
text=True,
)
# Whole-word match: " flow.py " and " <name> " so names are not substrings.
return {
int(line.split()[0]): line
for line in result.stdout.splitlines()
if "flow.py" in line and (name is None or f" {name} " in line + " ")
}
def prefect_state(run_id, state_type, message):
# Prefect REST: force-set state on a flow run.
body = json.dumps(
{
"state": {"type": state_type, "name": state_type.title(), "message": message},
"force": True,
}
).encode()
try:
NOPROXY.open(
urllib.request.Request(
f"{PREFECT}/api/flow_runs/{run_id}/set_state",
body,
{"Content-Type": "application/json"},
),
timeout=5,
)
except Exception as error:
print("prefect set_state failed:", error, flush=True)
def cancel(name, reason="cancelled from web UI"):
"""Kill the flow's process tree (uv -> python -> llama-server) and close its Prefect run."""
# Drop queued, not yet started, runs for this meeting.
with QLOCK:
QUEUE[:] = [queued_item for queued_item in QUEUE if queued_item[0] != name]
job = JOBS.get(name)
pids = {job.pid} if job and job.poll() is None else set()
# /T kills children (uv -> python -> llama-server), /F forces it.
for process_id in pids | set(flow_pids(name)):
subprocess.run(["taskkill", "/PID", str(process_id), "/T", "/F"], capture_output=True)
row = (
db.connect().execute("SELECT flow_run_id FROM recordings WHERE name=?", (name,)).fetchone()
)
if row and row[0]:
prefect_state(row[0], "CANCELLED", reason)
db.set_status(name, "cancelled", reason)
return bool(pids)
def drop_video(name):
"""Delete only the video/source file after the report: audio.opus, transcript, shots, report stay. Returns (MB freed, error)."""
row = db.connect().execute("SELECT status FROM recordings WHERE name=?", (name,)).fetchone()
job = JOBS.get(name)
# Only a finished report with no active run can drop its video.
if (
not row
or row["status"] != "done"
or name in RECEIVING
or (job and job.poll() is None)
or any(queued_item[0] == name for queued_item in QUEUE)
):
return 0, "solo a report finito e senza run attivi"
# Without audio.opus the source is the only input left: keep it.
if not (out_root / name / "audio.opus").exists():
return 0, "manca audio.opus: video non eliminato"
source_files = list((out_root / name).glob("source.*"))
if not source_files:
return 0, "nessun file sorgente"
total_bytes = sum(source_file.stat().st_size for source_file in source_files)
for source_file in source_files:
source_file.unlink()
return round(total_bytes / 1e6, 1), None
def merge(names):
"""Join webm parts of one call (restarted recording): stream copy in start order, events shifted by the cumulative length.
Returns (merged_name, None) or (None, error). Originals stay; delete them from the GUI once the merged report is fine."""
conn = db.connect()
rows = [
conn.execute(
"SELECT name, started_at, ended_at, chunks, bytes, status FROM recordings WHERE name=?",
(name,),
).fetchone()
for name in names
]
if len(names) < 2 or None in rows:
return None, "servono almeno 2 registrazioni esistenti"
# Refuse while any part is recording or running.
if any(
row["status"] == "recording"
or row["name"] in RECEIVING
or row["name"] in JOBS
and JOBS[row["name"]].poll() is None
for row in rows
):
return None, "ferma prima le registrazioni in corso"
# Chronological order by start time.
rows.sort(key=lambda row: row["started_at"] or "")
files = [db.media(row["name"])[1] for row in rows]
if not all(path and path.suffix == ".webm" for path in files):
return None, "solo registrazioni .webm"
# Merged name derived from the earliest part.
merged = rows[0]["name"] + "_merged"
if conn.execute("SELECT 1 FROM recordings WHERE name=?", (merged,)).fetchone():
return None, "unione già esistente"
dest = db.out_dir(merged) / "source.webm"
# Concat list for ffmpeg; removed after the run.
concat_list = dest.with_name("concat.txt")
concat_list.write_text(
"".join(f"file '{path.as_posix()}'\n" for path in files), encoding="utf-8"
)
# Stream copy via concat demuxer: no re-encode; parts must share codecs.
ffmpeg_result = subprocess.run(
[
"ffmpeg",
"-y",
"-v",
"error",
"-f",
"concat",
"-safe",
"0",
"-i",
str(concat_list),
"-c",
"copy",
str(dest),
],
capture_output=True,
text=True,
)
concat_list.unlink(missing_ok=True)
if ffmpeg_result.returncode:
return None, ffmpeg_result.stderr[-300:]
# Start offset of each part in the merged file (cumulative durations).
offsets, running_s = [], 0.0
for path in files:
offsets.append(running_s)
running_s += db.duration(path)
db.upsert_recording(
merged,
source="ext",
started_at=rows[0]["started_at"],
ended_at=rows[-1]["ended_at"],
chunks=sum(row["chunks"] or 0 for row in rows),
bytes=dest.stat().st_size,
duration_s=running_s,
status="queued",
)
for row, offset in zip(rows, offsets, strict=False):
# Copy each part's call events, shifted by its offset.
conn.execute(
"INSERT INTO call_events(name,t,kind,who_key,who,text) SELECT ?,t+?,kind,who_key,who,text FROM call_events WHERE name=?",
(merged, offset, row["name"]),
)
launch(merged, "audio")
return merged, None
def reaper():
"""Prefect cannot stop flows it did not launch: honour 'Cancel' from its UI and close runs whose process died."""
while True:
# Poll every 5 s.
time.sleep(5)
try:
# "any_" is Prefect's filter operator for "in this set".
body = json.dumps(
{"flow_runs": {"state": {"type": {"any_": ["RUNNING", "PENDING", "CANCELLING"]}}}}
).encode()
runs = json.load(
NOPROXY.open(
urllib.request.Request(
f"{PREFECT}/api/flow_runs/filter",
body,
{"Content-Type": "application/json"},
),
timeout=5,
)
)
if not runs:
continue
# flow_run_id -> our recording name.
by_id = {
row[1]: row[0]
for row in db.connect().execute(
"SELECT name, flow_run_id FROM recordings WHERE flow_run_id IS NOT NULL"
)
}
live = flow_pids()
for flow_run in runs:
name = by_id.get(flow_run["id"])
# Cancel requested in Prefect: stop our process, or just mark it if we don't own it.
if flow_run["state_type"] == "CANCELLING":
if name:
cancel(name, "cancelled from Prefect UI")
else:
prefect_state(flow_run["id"], "CANCELLED", "cancelled from Prefect UI")
# unknown id: a just-started flow may not have written flow_run_id yet -> only reap when no flow runs at all
elif (name and not any(f" {name} " in line + " " for line in live.values())) or (
not name and not live
):
prefect_state(
flow_run["id"], "CRASHED", "flow process is gone (killed or crashed)"
)
if name and db.connect().execute(
"SELECT status FROM recordings WHERE name=?", (name,)
).fetchone()[0] not in ("done", "error", "cancelled"):
db.set_status(name, "error", "flow process is gone (killed or crashed)")
except Exception as error:
if prefect_up():
print("reaper:", error, flush=True)
UPLOAD_EXT = {".mp4", ".mkv", ".mov", ".webm", ".wav", ".m4a", ".mp3"}
def _find(container, key):
"""First value of key k anywhere in a nested JSON object."""
if isinstance(container, dict):
if key in container:
return container[key]
container = list(container.values())
if isinstance(container, list):
for value in container:
if (found := _find(value, key)) is not None:
return found
def slot():
"""Live llama-server state (/slots): proves a long LLM call is moving even between progress ticks."""
# llama-server per-slot decode state; any failure -> None.
try:
state = json.load(NOPROXY.open(f"http://127.0.0.1:{llama.PORT}/slots", timeout=1))
except Exception:
return None
# /slots returns a list: take slot 0; keys are searched anywhere (schema varies).
state = state[0] if isinstance(state, list) and state else {}
return {
key: _find(state, key)
for key in ("is_processing", "n_prompt_tokens", "n_prompt_tokens_processed", "n_decoded")
}
def last_log(name):
"""Last meaningful line of out/<n>/logs/flow.log: what a started-but-not-yet-tracked run is doing (e.g. uv downloading deps)."""
log_file = out_root / name / "logs" / "flow.log"
# Log may not exist before the first run: show nothing.
try:
# Read only the tail: flow.log can be large.
with open(log_file, "rb") as file_handle:
file_handle.seek(max(0, log_file.stat().st_size - 4096))
tail = file_handle.read().decode("utf-8", "replace")
except OSError:
return ""
# Drop uv's UV_NATIVE_TLS noise so the real last line shows.
lines = [
line.strip() for line in tail.splitlines() if line.strip() and "UV_NATIVE_TLS" not in line
]
return lines[-1][-160:] if lines else ""
def prog(name, duration):
"""Step plan, current-step fraction and ETA from out/<n>/progress.json + learned seconds-per-audio-minute."""
progress = db.progress(name)
if not progress or not progress.get("step"):
return None
current_time, mins = time.time(), (duration or 0) / 60
# Speed key: shots/report are tracked per model, others per step.
def key(step):
return f"{step}@{llama.current(step == 'shots')}" if step in ("shots", "report") else step
cursor, elapsed_step = progress["step"], current_time - progress["step_start"]
step_estimate = db.spm(progress.get("key") or key(cursor)) * mins
if (
progress["total"] and progress["done"]
): # rate measured from the loop start (t0), not from the step start (model load etc.)
left, frac = (
(current_time - (progress.get("t0") or progress["step_start"]))
/ progress["done"]
* (progress["total"] - progress["done"]),
progress["done"] / progress["total"],
)
else:
left = max(step_estimate - elapsed_step, 0.1 * step_estimate)
frac = elapsed_step / (elapsed_step + left) if elapsed_step + left else 0
# Resume point's position in the pipeline order; earlier steps show as skipped.
order = db.ORDER
start_index = order.index(progress["start"]) if progress["start"] in order else 0
took = {step: end - begin for step, begin, end in progress["steps"]}
plan = []
for step in order:
if order.index(step) < start_index:
plan.append({"s": step, "state": "skip"})
elif step == cursor:
plan.append(
{
"s": step,
"state": "run",
"frac": round(frac, 3),
"left": round(left),
"secs": round(elapsed_step),
}
)
elif step in took:
plan.append({"s": step, "state": "done", "secs": round(took[step])})
else:
plan.append({"s": step, "state": "todo", "est": round(db.spm(key(step)) * mins)})
# ETA: rest of current step plus estimates for steps still to run.
eta_s = (
left + sum(plan_item.get("est", 0) for plan_item in plan if plan_item["state"] == "todo")
if mins
else None
)
total_elapsed = current_time - progress["run_start"]
return {
"step": cursor,
"note": progress["note"],
"done": progress["done"],
"total": progress["total"],
"frac": round(frac, 3),
"step_left": round(left),
"eta": None if eta_s is None else round(eta_s),
"elapsed": round(total_elapsed),
"pct": round(total_elapsed / (total_elapsed + eta_s), 3) if eta_s else None,
"idle": round(current_time - progress["updated"]),
"plan": plan,
"llm": slot() if cursor in ("shots", "docs", "report", "memory") else None,
}
# Snapshot polled by the GUI: recordings, queue, running jobs, LLM state.
def status():
timestamp = time.time()
recs = []
for row in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"):
name = row["name"]
record = dict(row)
# Seconds since last chunk while still receiving; None otherwise.
record["receiving_age_s"] = (
round(timestamp - RECEIVING[name]["last"]) if name in RECEIVING else None
)
# Only report.html is exposed; the GUI links to it.
record["files"] = ["report.html"] if (out_root / name / "report.html").exists() else []
job = JOBS.get(name)
record["running"] = bool(job and job.poll() is None)
record["title"] = title(name)
# Origin label stored in meta (upload filename or crop label).
record["upload"] = db.meta(name).get("upload")
# Progress only for running or pipeline-status rows.
record["prog"] = (
prog(name, record["duration_s"])
if record["running"] or record["status"] in db.ORDER
else None
)
if record["running"] and not record["prog"]:
record["boot"] = last_log(name)
# Source media size in MB (0 if dropped).
media_file = db.media(name)[0]
record["mb"] = round(media_file.stat().st_size / 1e6, 1) if media_file else 0
recs.append(record)
return {
"now": timestamp,
"recs": recs,
"busy": busy(),
"ask_blocked": ask_blocked(),
"queue": len(QUEUE),
"skip_shots": (db.GLOBAL / "skip_shots.txt").exists(),
"llm": [llama.current(True), llama.current(False)],
"omp": llama.omp_status(),
"llms": [
[[key, llama.label(key)] for key in llama.available(is_shots)]
for is_shots in (True, False)
],
}
# FTS MATCH; on a query syntax error retry with the input as one quoted phrase.
def fts(sql, query):
conn = db.connect()
try:
return conn.execute(sql, (query,)).fetchall()
# Fallback: FTS operators in user input become a literal quoted phrase.
except sqlite3.OperationalError:
return conn.execute(sql, ('"' + query.replace('"', '""') + '"',)).fetchall()
# Full-text search over speech and screen text.
def search(query):
speech_hits = []
# snippet(lines, col 3 = text, '[' ']' highlight, '…', 12 tokens).
for row in fts(
"SELECT name, t, speaker, snippet(lines, 3, '[', ']', '…', 12) FROM lines WHERE lines MATCH ? ORDER BY name DESC, t LIMIT 100",
query,
):
speech_hits.append([row[0], row[1], db.speaker_names(row[0]).get(row[2]) or row[2], row[3]])
screen_hits = []
# shot_text: FTS over screen text; same snippet convention.
for row 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",
query,
):
# Shot file for the matched frame; empty if none.
shot_row = (
db.connect()
.execute("SELECT file FROM shots WHERE name=? AND t=?", (row[0], row[1]))
.fetchone()
)
screen_hits.append([row[0], row[1], row[2], row[3], shot_row[0] if shot_row else ""])
return {"speech": speech_hits, "screen": screen_hits}
# Data for the speaker-naming UI: labels, names, talk time, samples, candidates.
def speakers_info(name):
conn = db.connect()
# Saved speaker -> person mapping, if already confirmed.
rows = [
dict(row)
for row in conn.execute(
"SELECT label, person, source, overlap_s FROM speaker_map WHERE name=?", (name,)
)
]
if not rows:
# No saved mapping yet: list the labels found in the transcript.
rows = [
{"label": row[0], "person": "", "source": "", "overlap_s": None}
for row in conn.execute(
"SELECT DISTINCT speaker FROM lines WHERE name=? AND speaker IS NOT NULL ORDER BY speaker",
(name,),
)
]
# Diarization segments (optional file) give talk time.
diar_path = out_root / name / "diar_segments.json"
talk = {}
# Talk time per diarized label, summed over segments.
for segment in json.loads(diar_path.read_text(encoding="utf-8")) if diar_path.exists() else []:
talk[segment["label"]] = talk.get(segment["label"], 0) + segment["end"] - segment["start"]
for row in rows:
row["talk_s"] = round(talk.get(row["label"], 0))
# Up to 3 longest lines as examples for naming the speaker.
row["samples"] = [
sample_row[0][:160]
for sample_row in conn.execute(
"SELECT text FROM lines WHERE name=? AND speaker=? ORDER BY length(text) DESC LIMIT 3",
(name, row["label"]),
)
]
rows.sort(key=lambda row: (len(row["label"]), row["label"]))
# Speakers seen in active/caption events are candidate names.
cand = sorted({row["who"] for row in db.events(name, "active", "caption") if row["who"]})
# Presence events carry the participant list as JSON in text.
for event in db.events(name, "present"):
cand += [person["who"] for person in json.loads(event["text"] or "[]")]
docs_path = out_root / name / "docs.json"
# docs.json (LLM-extracted people) also feeds candidate names.
if docs_path.exists():
cand += json.loads(docs_path.read_text(encoding="utf-8")).get("people", [])
return {"rows": rows, "candidates": sorted(set(cand))}
# Store sanitized call events; malformed entries are skipped silently.
def add_events(name, items):
rows = []
# At most 10000 events per request.
for item in items[:10000]:
try:
timestamp, kind, who_key, speaker, text = (
item["t"],
item["kind"],
item.get("who_key", ""),
item.get("who", ""),
item.get("text", ""),
)
except (KeyError, TypeError, AttributeError):
continue
# Accept only well-formed events: known kind, bounded sizes, non-negative time.
if (
isinstance(timestamp, (int, float))
and not isinstance(timestamp, bool)
and timestamp >= 0
and kind in db.EVENT_KINDS
and isinstance(who_key, str)
and isinstance(speaker, str)
and isinstance(text, str)
and len(who_key) <= 200
and len(speaker) <= 200
and len(text) <= 4000
):
rows.append((timestamp, kind, who_key, speaker, text))
db.add_events(name, rows)
UI_FILES = {
"/": ("index.html", "text/html; charset=utf-8"),
"/ui.css": ("ui.css", "text/css"),
"/ui.js": ("ui.js", "text/javascript; charset=utf-8"),
} # web UI, read per request
# HTTP handler: GUI, status JSON, media streaming, and all actions.
class Handler(BaseHTTPRequestHandler):
# Permissive CORS so the Teams extension can call us from its origin.
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 header_name, header_value in headers:
self.send_header(header_name, header_value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _json(self, payload):
self._send(json.dumps(payload, ensure_ascii=False).encode(), ctype="application/json")
def do_OPTIONS(self):
self._send()
def do_GET(self):
# Query params: name reduced to its basename so it cannot escape out/.
parsed = urlparse(self.path)
params = {key: value[0] for key, value in parse_qs(parsed.query).items()}
name = Path(params.get("name", "x")).name
# UI files read per request: edits show without restarting.
if parsed.path in UI_FILES:
self._send(
(HERE / "ui" / UI_FILES[parsed.path][0]).read_bytes(),
ctype=UI_FILES[parsed.path][1],
)
elif parsed.path == "/status":
self._json(status())
elif parsed.path == "/report":
file_path = out_root / name / "report.html"
self._send(
file_path.read_bytes(), ctype="text/html; charset=utf-8"
) if file_path.exists() else self._send(b"not found", 404)
elif parsed.path == "/shot":
# Basename only: the query cannot escape the shots folder.
file_path = out_root / name / "shots" / Path(params.get("file", "")).name
self._send(
file_path.read_bytes(), ctype="image/jpeg"
) if file_path.is_file() else self._send(b"not found", 404)
elif parsed.path == "/video":
self.video(name)
elif parsed.path == "/search":
self._json(search(params.get("q", "")))
elif parsed.path == "/speakers":
self._json(speakers_info(name))
elif parsed.path == "/pdf":
# PDF rendered on demand by headless Edge; failures return 500.
try:
file_path = make_pdf(name)
except Exception as error:
return self._send(f"errore: {error}".encode(), 500)
if file_path is None:
self._send(b"not found", 404)
else:
self._send(
file_path.read_bytes(),
ctype="application/pdf",
headers=[("Content-Disposition", f'inline; filename="{name}.pdf"')],
)
elif parsed.path == "/ask":
if not params.get("q", "").strip():
return self._send(b"domanda vuota", 400)
# 409 while a pipeline needs the GPU; the caller retries later.
if ask_blocked():
return self._send(b"pipeline in corso: riprova dopo", 409)
try:
self._json(ask_once(params["q"]))
except Exception as error:
return self._send(f"errore: {error!r}".encode(), 503)
elif parsed.path == "/ask_stream":
if not params.get("q", "").strip():
return self._send(b"domanda vuota", 400)
if ask_blocked():
return self._send(b"pipeline in corso: riprova dopo", 409)
# NDJSON, one event per line, no Content-Length: the connection closes at the end (HTTP/1.0 handler).
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Type", "application/x-ndjson; charset=utf-8")
self.send_header("Cache-Control", "no-cache")
self.end_headers()
try:
for event in ask_events(params["q"]):
self.wfile.write(json.dumps(event, ensure_ascii=False).encode() + b"\n")
self.wfile.flush()
except Exception as error:
# Headers are already sent, so the error travels as an event.
with contextlib.suppress(OSError):
self.wfile.write(json.dumps({"err": repr(error)}).encode() + b"\n")
else:
self._send(b"not found", 404)
# POST: ingestion (/chunk, /events, /upload), recording control, and actions.
def do_POST(self):
parsed = urlparse(self.path)
params = {key: value[0] for key, value in parse_qs(parsed.query).items()}
name = Path(params.get("name", "x")).name
if parsed.path == "/upload":
return self.upload(params)
# Read full body up front; /upload streams its own body instead.
data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if parsed.path == "/chunk":
# Append raw WebM bytes; the extension sends ~10 s pieces of one recording.
with open(db.out_dir(name) / "source.webm", "ab") as chunk_file:
chunk_file.write(data)
if name not in RECEIVING:
db.upsert_recording(name, source="ext", started_at=now(), status="recording")
# Last chunk time: status uses it for receiving_age_s.
RECEIVING.setdefault(name, {})["last"] = time.time()
# Keep chunk count and byte total current for the GUI.
db.connect().execute(
"UPDATE recordings SET chunks=chunks+1, bytes=bytes+?, updated_at=datetime('now') WHERE name=?",
(len(data), name),
)
self._send()
# Teams call events (JSON list) from the extension.
elif parsed.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 parsed.path == "/stop":
# Forget live-recording state so busy checks and crop guards clear.
RECEIVING.pop(name, None)
db.upsert_recording(name, ended_at=now(), status="queued")
# Hand off to the flow queue; the run starts at the audio step.
launch(name, "audio")
self._send(b"in coda: apri http://127.0.0.1:18765/")
elif parsed.path == "/delete":
if (
not db.connect()
.execute("SELECT 1 FROM recordings WHERE name=?", (name,))
.fetchone()
):
return self._send(b"not found", 404)
# Refuse while recording, queued or running.
job = JOBS.get(name)
if (
(job and job.poll() is None)
or name in RECEIVING
or any(queued_item[0] == name for queued_item in QUEUE)
):
return self._send(b"in elaborazione o in registrazione: ferma prima", 409)
db.delete_recording(name)
JOBS.pop(name, None)
self._send()
elif parsed.path == "/crop":
self.crop(name, params)
# Polled by the GUI during a crop; None when no crop is running.
elif parsed.path == "/crop_progress":
self._json({"pct": CROP.get(name)})
elif parsed.path == "/cancel":
# Kill the flow tree; empty reply if something was killed.
self._send(b"") if cancel(name) else self._send(
b"nessun processo attivo: run chiusa", 200
)
elif parsed.path == "/merge":
merged, error = merge(
[name_item for name_item in params.get("names", "").split(",") if name_item]
)
self._send(merged.encode() if merged else error.encode(), 200 if merged else 400)
elif parsed.path == "/drop_video":
freed_mb, error = drop_video(name)
self._send(
f"{freed_mb} MB liberati".encode() if not error else error.encode(),
200 if not error else 409,
)
elif parsed.path == "/title":
# Manual title, 404 if the meeting is unknown.
self._send(b"") if set_title(name, data.decode("utf-8", "replace")) else self._send(
b"not found", 404
)
elif parsed.path == "/run":
if not db.media(name)[0]:
return self._send(b"video eliminato: rielaborazione non possibile", 409)
# Re-run the flow from a step (default audio), with optional speaker count.
launched = launch(name, params.get("from", "audio"), int(params.get("speakers") or 0))
self._send(
b"" if launched else "già in coda o in esecuzione".encode(),
200 if launched else 409,
)
elif parsed.path == "/run_all":
start_from = params.get("from", "audio")
# Reject unknown resume points.
if start_from not in STEPS:
return self._send(b"bad step", 400)
self._send(b"") if run_all(start_from) else self._send(
"rielaborazione già in corso".encode(), 409
)
elif parsed.path == "/skip_shots":
flag_file = db.GLOBAL / "skip_shots.txt"
# Flag file: while present the pipeline skips the shots step.
if params.get("v") == "1":
flag_file.write_text("1")
else:
flag_file.unlink(missing_ok=True)
self._send()
elif parsed.path == "/llm":
kinds = [params.get("shots"), params.get("report")]
# Only models actually installed for the role are accepted.
if not (kinds[0] in llama.available(True) and kinds[1] in llama.available(False)):
return self._send(b"modello non installato", 400)
# Model swap only while idle: running jobs hold the loaded model.
if busy():
return self._send(b"pipeline in corso: cambia modello dopo", 409)
llama.choose(*kinds)
self._send()
elif parsed.path == "/speaker_map":
try:
mapping = json.loads(data)
except ValueError:
return self._send(b"bad json", 400)
# Save manual speaker names, then re-render so transcripts show them.
for label, person in mapping.items():
db.set_speaker_map(name, label, str(person).strip(), "manual")
if launch(name, "render"):
self._send(b"salvato, render in coda")
else:
self._send(b"salvato, render dopo il job in corso", 202)
else:
self._send(b"not found", 404)
# Serve meeting media to the player with HTTP Range (seeking).
def video(self, name):
audio_file, video_file = db.media(name)
media_path = video_file or audio_file
if media_path and media_path.suffix == ".webm" and name not in RECEIVING:
# MediaRecorder webm has no duration/cues: the player treats it as an endless stream. Cache a stream-copy remux (header with length + seek index).
preview = media_path.with_name("preview.webm")
if not preview.exists() or preview.stat().st_mtime < media_path.stat().st_mtime:
part_path = preview.with_suffix(".part.webm")
# Stream-copy remux fixes the missing duration; on failure serve the original.
if (
subprocess.run(
[
"ffmpeg",
"-y",
"-v",
"error",
"-i",
str(media_path),
"-c",
"copy",
str(part_path),
],
capture_output=True,
).returncode
== 0
):
part_path.replace(preview)
else:
part_path.unlink(missing_ok=True)
if preview.exists():
media_path = preview
if not media_path:
return self._send(b"not found", 404)
size = media_path.stat().st_size
first_byte, last_byte = 0, size - 1
# Parse single HTTP Range header (bytes=...); multi-range is not supported.
range_match = re.match(r"bytes=(\d*)-(\d*)$", self.headers.get("Range", ""))
if range_match and (range_match[1] or range_match[2]):
# "A-B" explicit range, "A-" open end, "-N" last N bytes.
if range_match[1]:
first_byte = int(range_match[1])
last_byte = min(int(range_match[2]) if range_match[2] else last_byte, last_byte)
else:
first_byte = max(0, size - int(range_match[2]))
else:
range_match = None
# Start past end: 416 Range Not Satisfiable.
if first_byte > last_byte:
return self._send(b"", 416, headers=[("Content-Range", f"bytes */{size}")])
self.send_response(206 if range_match else 200)
self.send_header(
"Content-Type", mimetypes.guess_type(media_path.name)[0] or "application/octet-stream"
)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(last_byte - first_byte + 1))
if range_match:
self.send_header("Content-Range", f"bytes {first_byte}-{last_byte}/{size}")
self.end_headers()
try:
with open(media_path, "rb") as file_handle:
file_handle.seek(first_byte)
left = last_byte - first_byte + 1
# 1 MiB pieces: large videos are never loaded whole.
while left and (chunk := file_handle.read(min(1 << 20, left))):
self.wfile.write(chunk)
left -= len(chunk)
except OSError:
pass # browser aborted the range (seek)
# Cut [start, end] with ffmpeg into a new source file; progress feeds CROP.
def crop(self, name, params):
audio_file, video_file = db.media(name)
source_file = video_file or audio_file
if not source_file:
return self._send(b"not found", 404)
# Cutting a recording still being written would race with its appends.
if name in RECEIVING:
return self._send(b"registrazione in corso: ferma prima", 409)
# Times are seconds from the start of the media.
try:
start, end = float(params["start"]), float(params["end"])
except (KeyError, ValueError):
return self._send(b"bad times", 400)
if not 0 <= start < end:
return self._send(b"intervallo non valido", 400)
inplace = (
params.get("inplace") == "1"
) # replace this meeting's source (and shift its call events) instead of creating a new meeting
job = JOBS.get(name)
if inplace and (
(job and job.poll() is None) or any(queued_item[0] == name for queued_item in QUEUE)
):
return self._send(b"elaborazione in corso: ferma prima", 409)
# Inplace keeps the name; otherwise a new meet_<timestamp> meeting is made.
new_name = name if inplace else "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S")
extension = ".mp4" if video_file else ".m4a"
dest = db.out_dir(new_name) / f"source{extension}"
part_file = dest.with_name(f"source{extension}.part")
# Video: re-encode to even dimensions (yuv420p requires them). Audio-only: drop video.
encode_args = (
[
"-vf",
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"23",
"-pix_fmt",
"yuv420p",
]
if video_file
else ["-vn"]
)
CROP[name] = 0
# -ss before -i: fast input seek; -t sets the cut length.
proc = subprocess.Popen(
[
"ffmpeg",
"-y",
"-v",
"error",
"-progress",
"pipe:1",
"-nostats",
"-ss",
str(start),
"-t",
str(end - start),
"-i",
str(source_file),
*encode_args,
"-c:a",
"aac",
"-b:a",
"128k",
"-movflags",
"+faststart",
"-f",
"mp4",
str(part_file),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
for line in proc.stdout:
# out_time_us is microseconds; /1e4 gives percent of the cut length.
if line.startswith("out_time_us=") and line[12:].strip().lstrip("-").isdigit():
CROP[name] = min(99, max(0, int(line[12:]) / 1e4 / (end - start)))
# Wait for ffmpeg to exit and collect its stderr for error messages.
ffmpeg_stderr = proc.stderr.read()
proc.wait()
CROP.pop(name, None)
# Stand-in with returncode/stderr so the checks below read like subprocess.run.
stand_in = type("R", (), {"returncode": proc.returncode, "stderr": ffmpeg_stderr})
# Cleanup on failure: remove partial file, and the new folder if we created it.
def fail(message):
return (
part_file.unlink(missing_ok=True),
None if inplace else dest.parent.rmdir(),
self._send(message.encode(), 500),
)
if stand_in.returncode or not part_file.exists() or not part_file.stat().st_size:
return fail(f"ffmpeg: {stand_in.stderr[-300:]}")
# Unreadable result (db.duration raises): remove it and report.
try:
duration = db.duration(part_file)
except ValueError as error:
return fail(f"ritaglio non leggibile: {error}")
# Replace this meeting's media: drop old originals and preview so only the cut remains.
if inplace:
for old_file in (audio_file, video_file, dest.with_name("preview.webm")):
if old_file and old_file != dest:
old_file.unlink(missing_ok=True)
conn = db.connect()
# Keep only events inside the cut, then shift them to the new t=0.
conn.execute(
"DELETE FROM call_events WHERE name=? AND (t<? OR t>?)", (name, start, end)
)
conn.execute("UPDATE call_events SET t=t-? WHERE name=?", (start, name))
# Atomic swap: the finished file appears only when complete.
part_file.replace(dest)
# In-place: same meeting, refreshed size/duration, back in the queue.
if inplace:
db.upsert_recording(
name, bytes=dest.stat().st_size, duration_s=duration, status="queued"
)
else:
db.set_meta(new_name, upload=f"{title(name) or name} [{int(start)}s-{int(end)}s]")
db.upsert_recording(
new_name,
source="upload",
started_at=now(),
status="queued",
bytes=dest.stat().st_size,
duration_s=duration,
)
launch(new_name, "audio")
self._json({"name": new_name, "duration_s": duration})
# Raw-body upload: whole file in the request body, saved as a new meeting, then queued.
def upload(self, params):
filename = Path(params.get("filename", "")).name
extension = Path(filename).suffix.lower()
content_length = int(self.headers.get("Content-Length", 0))
if extension not in UPLOAD_EXT:
return self._send(
f"formato non supportato: {extension or '?'} (usa {', '.join(sorted(UPLOAD_EXT))})".encode(),
400,
)
if not content_length:
return self._send(b"file vuoto", 400)
name = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S")
dest = db.out_dir(name) / f"source{extension}"
part_file = dest.with_name(f"source{extension}.part")
left = content_length
with open(part_file, "wb") as out_file:
while left and (chunk := self.rfile.read(min(1 << 20, left))):
out_file.write(chunk)
left -= len(chunk)
# Client aborted mid-upload: remove the partial file and its folder.
if left:
part_file.unlink(missing_ok=True)
dest.parent.rmdir()
return self._send(b"upload interrotto", 400)
part_file.replace(dest)
try:
duration = db.duration(dest)
except ValueError as error:
dest.unlink()
dest.parent.rmdir()
return self._send(f"file non leggibile: {error}".encode(), 400)
db.set_meta(name, upload=filename)
db.upsert_recording(
name,
source="upload",
started_at=now(),
status="queued",
bytes=content_length,
duration_s=duration,
)
launch(name, "audio")
self._json({"name": name, "duration_s": duration})
# Access logs are noisy; print them only with LOG_LEVEL=DEBUG.
def log_message(self, format_str, *log_args):
if os.environ.get("LOG_LEVEL", "INFO").upper() == "DEBUG":
print(format_str % log_args, flush=True)
# Startup: open DB, backfill, start Prefect, start the reaper.
db.connect()
backfill()
start_prefect()
threading.Thread(target=reaper, daemon=True).start()
print(f"listening http://127.0.0.1:{args.port}/", flush=True)
# Blocks for the life of the process.
ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()