Add explanatory comments across codebase

This commit is contained in:
Stefano Zini
2026-11-04 14:23:18 +01:00
parent b8aa5548a2
commit 82b72b6c28
34 changed files with 934 additions and 0 deletions
+5
View File
@@ -3,13 +3,18 @@ import subprocess
import db
# Convert the meeting's audio track to 16 kHz mono Opus (small, speech-optimised).
def run(name):
src = db.media(name)[0]
# No audio track: nothing to convert.
if src is None: raise FileNotFoundError(f"no audio source for {name}")
dst = db.out_dir(name) / "audio.opus"
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000",
# highpass 80 Hz removes rumble; loudnorm evens out volume (EBU R128: -18 LUFS, -2 dBTP peak, LRA 11); 24 kbps Opus.
"-af", "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11", "-c:a", "libopus", "-b:a", "24k", str(dst)],
capture_output=True, text=True)
# Surface the tail of ffmpeg's error output.
if r.returncode: raise RuntimeError(r.stderr[-500:])
# Store the duration probed from the output file.
db.upsert_recording(name, duration_s=db.duration(dst))
return dst
+6
View File
@@ -1,21 +1,27 @@
# Shared helpers: makes the CUDA DLLs findable and loads the Whisper model.
import glob, os, site
import numpy as np
# pip nvidia-* wheels ship cublas/cudnn DLLs; ctranslate2 needs them on PATH (Windows)
# Each nvidia/<lib>/bin folder from the pip wheels is added to the DLL search path and PATH.
for sp in site.getsitepackages():
for b in glob.glob(os.path.join(sp, "nvidia", "*", "bin")):
os.add_dll_directory(b); os.environ["PATH"] = b + os.pathsep + os.environ["PATH"]
# Import only after the DLL path is set up above, or CUDA libs fail to load.
from faster_whisper import WhisperModel
CORES = max(1, (os.cpu_count() or 2) // 2) # ponytail: logical/2 ~ physical cores (no psutil); exact count if hybrid CPUs need it
def load_model(name):
"""CUDA if it really works (probe one decode), else CPU int8."""
# Try CUDA first; the probe below forces the real CUDA libs to load now, so a missing DLL fails here.
try:
m = WhisperModel(name, device="cuda", compute_type="default")
# One second of silence forces an actual decode, not just a model load.
list(m.transcribe(np.zeros(16000, np.float32))[0])
return m, "cuda"
except Exception as e:
print("cuda failed, using cpu:", e, flush=True)
# CPU fallback: int8 quantisation, CORES threads.
return WhisperModel(name, device="cpu", compute_type="int8", cpu_threads=CORES), "cpu"
+40
View File
@@ -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())
+22
View File
@@ -4,6 +4,7 @@ from pathlib import Path
import numpy as np
import db
# Model files shipped under app/models/.
M = Path(__file__).parent / "models"
# sherpa-onnx default is 1 thread (>10 min for a 40-min call); 8 threads: ~6 min on 155H; physical-core count scales to bigger CPUs.
# CUDA measured slower (>7 min, GPU ~5 W): tiny models + one embedding per segment -> transfer/launch overhead dominates.
@@ -12,46 +13,64 @@ THREADS = max(1, (os.cpu_count() or 2) // 2)
def roster_size(name, default=5):
"""Distinct people seen in the Teams roster events -> cluster count (a fixed 5 merged 8 people into 4 labels)."""
# Speakers seen in roster events (not video tiles); each event's text is a JSON list of {who}.
who = {p["who"] for e in db.events(name, "present") if e["who_key"] != "video" for p in json.loads(e["text"] or "[]") if p.get("who")}
# Clamp the cluster count to 2-12; no roster -> default.
return min(max(len(who), 2), 12) if who else default
# Diarize audio.opus, attach speaker labels to transcript lines, and save. Returns nothing.
def run(name, speakers=0, threshold=0.85):
speakers = speakers or roster_size(name)
# Imported here so the module loads without sherpa-onnx installed.
import sherpa_onnx
src = db.out_dir(name) / "audio.opus"
# Decode audio to 16 kHz mono float32 (sherpa input format).
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
audio = np.frombuffer(raw, np.float32)
# Pyannote segmentation + speaker embedding + clustering.
sd = sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig(
segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")),
num_threads=THREADS),
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS),
# num_clusters > 0 fixes the speaker count and overrides threshold.
clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold),
# Drop blips under 0.3 s and merge gaps under 0.5 s.
min_duration_on=0.3, min_duration_off=0.5))
# Last printed decile, so progress prints every 10 %.
t0, last = time.time(), [-1]
def progress(done, total): # sherpa calls this per processed chunk; print every 10 %
pct = done * 100 // max(total, 1)
if pct // 10 > last[0]: last[0] = pct // 10; print(f"diarize {pct}% ({done}/{total}, {time.time() - t0:.0f} s)", flush=True)
# Update DB progress every 20 chunks (and at the end) to limit writes.
if done % 20 == 0 or done == total: db.tick(name, done, total, "impronte vocali dei segmenti")
return 0
# Status for the GUI before the slow segmentation starts.
db.tick(name, 0, 0, "segmentazione dell'audio (~1-2 min)")
# Run diarization; segments come back sorted by start time.
segs = [(s.start, s.end, s.speaker) for s in sd.process(audio, callback=progress).sort_by_start_time()]
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True)
lines = []
# Parse transcript lines '[mm:ss] text' into (seconds, text).
for l in (db.out_dir(name) / "transcript.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3]))
# order: first-appearance numbering of speakers, for 'Speaker N' labels.
out, order = [], {}
for i, (t, text) in enumerate(lines):
# A line lasts until the next line starts; the last line is assumed 5 s.
t1 = lines[i + 1][0] if i + 1 < len(lines) else t + 5
ov = {}
# Total overlap of each diarized segment with this line's window.
for s, e, sp in segs:
o = min(e, t1) - max(s, t)
if o > 0: ov[sp] = ov.get(sp, 0) + o
# Pick the speaker with the most overlap (None if no overlap).
sp = max(ov, key=ov.get) if ov else None
# Number speakers by first appearance in the text.
if sp is not None: order.setdefault(sp, len(order) + 1)
# same speaker continues: one paragraph, but cut every 60 s so the timestamps stay usable (one 11-min paragraph
# stamped 28:52 made every model end the report there)
@@ -60,8 +79,11 @@ def run(name, speakers=0, threshold=0.85):
# labels by first appearance in the text; clusters never seen in text get the following numbers
for s in sorted(segs):
order.setdefault(s[2], len(order) + 1)
# Save raw diarized segments as JSON.
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8")
# Replace DB transcript lines with speaker-labelled ones.
db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out])
# Count of speakers actually present in the text.
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None}))
print("saved", len(out), "speaker-labelled lines")
+45
View File
@@ -1,18 +1,28 @@
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow."""
import json, os, re, shutil, subprocess
# report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address.
import db, llama, report
# twg CLI: from PATH, else the default per-user install location.
TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
# Prompt: 4 short search queries (3-6 words) from the meeting description.
SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.'
# Prompt: relevance score 0-3 for each numbered candidate doc.
SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).'
# Full Jira key match (anchored).
KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$")
# Confluence checkbox line ("* [ ] text" or "* [x] text"); group 1 = text. Used to harvest people names.
PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
# Run twg. Returns parsed JSON for "-o json" calls, else stdout (None on failure).
# Retries once through the proxy when the failure looks like a network/proxy error.
def _twg(*args, timeout=120):
# Child env without Python home vars that would confuse twg.
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
for attempt in range(2):
r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
# JSON mode: parse stdout; twg may instead print a YAML envelope pointing at a spooled file.
if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON
except ValueError: out = None
@@ -20,80 +30,114 @@ def _twg(*args, timeout=120):
if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)):
try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError): pass
# Plain-text mode: stdout only on success.
else: out = r.stdout if r.returncode == 0 else None
# Stop unless this is the first attempt and stderr looks like a network/proxy error.
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
# Second attempt goes through the proxy.
env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY}
# Gather candidate docs for a meeting: queries, Confluence/Jira search, Jira key lookups, LLM relevance scoring.
# Returns the docs.json payload; raises on hard failure (run() catches it).
def _run(name):
if not os.path.exists(TWG): raise FileNotFoundError("twg not found")
# Per-meeting output directory.
d = db.out_dir(name)
meta = [json.loads(e["text"]) for e in db.events(name, "meta") if e["who_key"] != "video"] # Teams topic only, never a shot guess
title = (meta[-1].get("title") or "") if meta else ""
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else []
from shots import CONTENT_KINDS
# Titles of lead content screens: deduped, max 30.
screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30]
tx = db.out_dir(name) / "transcript.txt"
txt = tx.read_text(encoding="utf-8") if tx.exists() else ""
# Meeting description for the LLM: title, screen titles, glossary, first 800 words of transcript.
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}"
# Title is always a query; add up to 4 LLM-generated ones.
queries = [title] if title else []
queries += [q for q in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4] if isinstance(q, str)]
# Case-insensitive de-dup of queries.
queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1]
# Candidates keyed by URL across all queries.
cand = {}
for q in queries:
# Confluence: up to 6 hits per query; Jira: up to 4.
for app, lim in (("confluence", 6), ("jira", 4)):
for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []:
# Skip results without a URL or already seen.
u = it.get("url")
if not u or u in cand: continue
# Jira key from /browse/KEY-N URLs; Confluence page id from /pages/ID URLs.
jk = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", u); cid = re.search(r"/pages/(\d+)", u)
cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None,
"title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False}
items = list(cand.values())
# Text to scan for ticket keys: transcript plus shot OCR text.
blob = [txt] + [s.get("text") or "" for s in shots]
# Ticket keys found in the content (valid format), then keys already on candidates.
keys = [k for k in dict.fromkeys(m for b in blob for m in report.TICKET.findall(b)) if KEY.match(k)]
keys += [k for k in (e["key"] for e in items) if k and k not in keys]
# Keys literally mentioned in the meeting content.
mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)})
# Jira lookup: summary + status for keys, one batch of up to 26.
known = {}
# Only call twg when there are keys.
if keys[:20 + 6]:
r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for it in (r.get("data") or {}).get("items") or []:
if it.get("ok") and it.get("data"):
x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "")
# Apply Jira summary/status to candidates that have a key.
for e in items:
if e["key"] in known: e["title"], e["status"] = known[e["key"]]
# Add mentioned Jira tickets not already in items.
have = {e["key"] for e in items if e["key"]}
for k in keys:
if k in known and k in mentioned and k not in have:
items.append({"source": "jira", "key": k, "id": None, "title": known[k][0], "url": f"{report.JIRA_BROWSE}/{k}", "status": known[k][1], "snippet": "", "mentioned": True})
# Flag items mentioned in the meeting and resolved in Jira.
for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known)
# Relevance: LLM scores non-mentioned items; missing score = 0.
scores = {}
rel = [e for e in items if not e["mentioned"]]
# Only score non-mentioned items, if any.
if rel:
# Numbered candidate list appended to the meeting description.
u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel))
# Score indices refer to positions in rel.
for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []:
try: scores[int(s["i"])] = int(s["score"])
except (KeyError, TypeError, ValueError): pass
# Non-mentioned items keep the LLM score (0 if missing).
for i, e in enumerate(rel): e["score"] = scores.get(i, 0)
# Mentioned items score 3 unless already set.
for e in items:
e.setdefault("score", 3 if e["mentioned"] else 0)
# Keep mentioned items plus those scored >= 2, best first.
keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"])
# Cap per source: 8 Confluence; Jira: up to 6 non-mentioned plus all mentioned.
conf = [e for e in keep if e["source"] == "confluence"][:8]
jira = [e for e in keep if e["source"] == "jira" and not e["mentioned"]][:6] + [e for e in keep if e["mentioned"]]
keep = conf + jira
# Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body.
for e in keep:
if e["source"] == "confluence" and e["id"]:
b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or ""
# twg prefixes the body with a "Content loaded." banner line; drop it.
lines = b.splitlines()
if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:]
e["body"] = "\n".join(lines)[:6000]
else: e["body"] = f"{e['key']} {e['title']} ({e['status']})"
# Stable index used to reference docs from report.py.
for i, e in enumerate(keep): e["i"] = i
# People names: checkbox lines in bodies, multi-word only, deduped.
people = []
for e in keep:
for m in PEOPLE.finditer(e["body"]):
@@ -102,6 +146,7 @@ def _run(name):
return {"queries": queries, "items": keep, "people": people, "error": None}
# Entry point. Never fails the flow: errors are recorded in docs.json (error field) instead of raised.
def run(name):
try: out = _run(name)
except Exception as e:
+9
View File
@@ -1,21 +1,30 @@
// Make Teams see Edge instead of Opera: rewrite UA + client-hint request headers.
// Edge UA built from the browser's own UA: the Opera OPR/ token is removed and an Edg/ token is added.
const ua = navigator.userAgent;
// Chrome major version taken from the UA; falls back to 130 if the UA has no Chrome token.
const v = (ua.match(/Chrome\/(\d+)/) || [])[1] || "130";
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`;
// Sec-CH-UA brand list matching the Edge UA; "Not_A Brand" is a GREASE placeholder brand.
const brands = `"Microsoft Edge";v="${v}", "Chromium";v="${v}", "Not_A Brand";v="24"`;
// Helper: builds one declarativeNetRequest header operation.
const set = (header, value) => ({ header, operation: "set", value });
// Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start.
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [1],
addRules: [{
id: 1,
// Higher than default so this rule wins over other extensions' header rules.
priority: 1,
// Rewrite the outgoing request headers.
action: {
type: "modifyHeaders",
requestHeaders: [set("User-Agent", edgeUA), set("Sec-CH-UA", brands)],
},
condition: {
// Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft.
regexFilter: "^https://teams\\.(cloud\\.)?microsoft(\\.com)?/",
// Every request type Teams uses, including websocket handshakes.
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest", "script", "stylesheet", "image", "font", "websocket", "other"],
},
}],
+2
View File
@@ -1,2 +1,4 @@
<!-- Opened as a normal tab so Chrome can show the mic permission prompt; close it after granting. -->
<body>Allow the microphone, then close this tab.
<!-- mic.js requests the permission. -->
<script src="mic.js"></script>
+3
View File
@@ -1,3 +1,6 @@
// Run in mic.html (a normal tab): asks for mic permission once so offscreen.js can use it later without a prompt.
navigator.mediaDevices.getUserMedia({ audio: true })
// Stop the probe tracks at once: only the permission grant was needed, not the audio.
.then(s => { s.getTracks().forEach(t => t.stop()); document.body.append(" granted."); })
// Show the outcome in the page (the error text if the user denied or the call failed).
.catch(e => document.body.append(" " + e));
+1
View File
@@ -1 +1,2 @@
<!-- Hidden offscreen document created by popup.js to hold the recorder; not shown to the user. -->
<script src="offscreen.js"></script>
+22
View File
@@ -1,17 +1,25 @@
// Offscreen document: records the Teams tab (tabCapture) and uploads 10 s WebM chunks to the local server.
// Local server endpoint (server.py); must match start.js port 18765.
const API = "http://127.0.0.1:18765";
let rec, ctx, tab, mic, q = Promise.resolve(), name;
// state: idle | recording | transcribing | done | error ; popup polls it
const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" };
// Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored.
chrome.runtime.onMessage.addListener((m, _s, send) => {
if (m.to !== "off") return;
if (m.cmd === "status") send(S);
// start is async: reply with ok, or with the error text (also stored in S for the popup).
if (m.cmd === "start") start(m.id, m.tabId).then(() => send({ ok: true }), e => { S.state = "error"; S.text = String(e); send({ err: String(e) }); });
// teams.js events are re-based to seconds since recording start; events from before start are dropped.
if (m.cmd === "events") { for (const e of m.events) if (e.ts >= S.t0) S.ev.push({ t: (e.ts - S.t0) / 1000, kind: e.kind, who_key: e.who_key, who: e.who, text: e.text }); }
// Stop: MediaRecorder.onstop handles the finalisation.
if (m.cmd === "stop") { rec.stop(); send({ ok: true }); }
// Keep the message channel open for the async replies above.
return true;
});
// Send buffered Teams events to the server; on failure count it so the popup can warn.
async function flushEv() {
if (!S.ev.length) return;
const b = S.ev.splice(0);
@@ -22,36 +30,50 @@ async function flushEv() {
} catch { S.failed++; }
}
// Start recording the given tab (id from tabCapture.getMediaStreamId).
async function start(id, tabId) {
name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
// Tab capture stream: the chromeMediaSource constraint is the only way to get tab audio/video in an extension.
const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } };
tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src });
// Mixer: tab audio + optional mic are mixed into one destination track.
ctx = new AudioContext();
const dest = ctx.createMediaStreamDestination();
const t = ctx.createMediaStreamSource(tab);
t.connect(dest);
t.connect(ctx.destination); // tabCapture mutes the tab; play it back
// Mic is optional: needs the one-time grant from mic.html; without it the recording is tab-only.
try { // needs one-time grant via mic.html
mic = await navigator.mediaDevices.getUserMedia({ audio: true });
ctx.createMediaStreamSource(mic).connect(dest);
} catch { mic = null; }
// Output stream: tab video + mixed audio.
const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]);
// VP8 video + Opus audio at 1 Mbps video, a format the server's ffmpeg pipeline accepts.
rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
// Each 10 s chunk is uploaded in order through the q promise chain.
rec.ondataavailable = e => {
// Chain the upload on q so chunks reach the server in order; count success or failure, then flush events.
q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv);
};
// Stop path: wait for uploads, release the capture, then ask the server to transcribe.
rec.onstop = async () => {
S.state = "transcribing"; S.t1 = Date.now();
try {
// Wait for all queued chunk uploads to finish before asking for transcription.
await q;
await flushEv();
// Release tab/mic capture devices and the audio context.
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop()));
ctx.close();
// Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text.
const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" });
S.text = await r.text(); S.state = r.ok ? "done" : "error";
} catch (e) { S.text = "server down or failed: " + e; S.state = "error"; }
rec = null;
};
// Reset per-session state and record the start time; events are kept in S.ev until sent.
Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId });
// 10 s timeslice: MediaRecorder emits a chunk every 10 s.
rec.start(10000);
}
+5
View File
@@ -1,5 +1,10 @@
<!-- Extension popup: Start/Stop button, mic-grant link, status line and transcript view. -->
<body style="width:380px;font:13px sans-serif">
<!-- mic.html opens in a new tab so the permission prompt can appear; needed once. -->
<button id="go">Start</button> <a href="mic.html" target="_blank">grant mic (once)</a>
<!-- Status line, filled by popup.js. -->
<div id="st"></div>
<!-- Transcript/result text returned by the recorder. -->
<pre id="txt" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre>
<!-- popup.js drives the UI. -->
<script src="popup.js"></script>
+24
View File
@@ -1,12 +1,21 @@
// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
// Shorthand for getElementById.
const $ = id => document.getElementById(id);
// Forward a command to the offscreen document (addressed with to:"off").
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg });
// Format milliseconds as m:ss.
const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
// Last error shown when there is no offscreen document to report it.
let S = { state: "idle" }, lastErr = "";
// Refresh the button and status line from state S.
function render() {
const go = $("go"), st = $("st");
// Pipeline busy after stop: no new start until it finishes.
go.disabled = S.state === "transcribing";
// Button doubles as Stop while recording.
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start";
// Status line text per recorder state.
st.textContent = {
idle: "idle - open a Teams tab and press Start",
recording: `REC ${mmss(Date.now() - S.t0)} | ${S.chunks} chunks uploaded${S.failed ? ` | ${S.failed} FAILED (server down?)` : ""} | mic ${S.mic ? "on" : "OFF (grant it)"} | eventi call: ${S.evSent || 0}`,
@@ -14,33 +23,48 @@ function render() {
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
error: "ERROR (see below)",
}[S.state];
// Show the transcript/result text when there is one.
if (S.text) $("txt").textContent = S.text;
}
// Poll the recorder state every second.
async function poll() {
// Offscreen doc exists: ask it for its state. Otherwise show the last error, or idle.
if (await chrome.offscreen.hasDocument()) S = (await off({ cmd: "status" })) || S; else S = lastErr ? { state: "error", text: lastErr } : { state: "idle" };
render();
}
// Start / Stop click handler.
$("go").onclick = async () => {
// Stop path: first ask teams.js to stop its scanners.
if (S.state === "recording") {
// Tell the Teams content script to stop (errors ignored: the tab may be gone).
if (S.tabId != null) await chrome.tabs.sendMessage(S.tabId, { cmd: "cap-stop" }).catch(() => {});
// Give teams.js's final event batch time to reach the offscreen doc before the recorder stops.
await new Promise(r => setTimeout(r, 300));
await off({ cmd: "stop" }); return poll();
}
// Clear the previous error before a new attempt.
lastErr = "";
try {
// Tab the user is looking at when the button is pressed.
const [t] = await chrome.tabs.query({ active: true, currentWindow: true });
// The popup itself is an extension page; it can't be recorded.
if (t.url?.startsWith("chrome-extension:")) throw new Error("This is the extension's own page. Switch to the Teams tab, then click the icon.");
// Stream id that the offscreen document later passes to getUserMedia.
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id });
// Create the offscreen document once; it stays alive while recording.
if (!(await chrome.offscreen.hasDocument()))
await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" });
const r = await off({ cmd: "start", id, tabId: t.id });
if (r?.err) throw new Error(r.err);
// Tell teams.js to start its scanners; ignored if the content script is not on this tab.
chrome.tabs.sendMessage(t.id, { cmd: "cap-start" }).catch(() => {});
// Any failure is shown in the status line.
} catch (e) { lastErr = String(e); }
render(); poll();
};
// Keep status fresh while the popup is open.
poll(); setInterval(poll, 1000);
+16
View File
@@ -1,28 +1,44 @@
// MAIN world, document_start: navigator.* reports Edge instead of Opera.
(() => {
// Original UA string from the page (Opera).
const ua = navigator.userAgent;
// Only patch Opera; other browsers are left as-is.
if (!/OPR\//.test(ua)) return;
// Chrome major version, same logic as background.js.
const v = (ua.match(/Chrome\/(\d+)/) || [])[1] || "130";
// Same UA rewrite as background.js: drop OPR/, add Edg/.
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`;
// Replace any Opera brand entry with Microsoft Edge, keeping its version.
const fix = (b) => b.map((x) => (/opera/i.test(x.brand) ? { brand: "Microsoft Edge", version: x.version } : x));
// Getter-only property definer; configurable so it can be redefined.
const def = (o, k, g) => Object.defineProperty(o, k, { get: g, configurable: true });
// Override on Navigator.prototype so page scripts reading navigator.userAgent see Edge.
def(Navigator.prototype, "userAgent", () => edgeUA);
// appVersion is the UA without the leading "Mozilla/".
def(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
// userAgentData (Client Hints) exists only in Chromium-based browsers.
const d = navigator.userAgentData;
// Older builds without UA-CH: nothing more to patch.
if (!d) return;
// Brand list with Opera replaced by Edge.
const brands = fix(d.brands);
// Keep the original function bound to the real object.
const hev = d.getHighEntropyValues.bind(d);
// Replacement userAgentData object exposing the same fields as the original.
const patched = {
brands,
mobile: d.mobile,
platform: d.platform,
// High-entropy values also carry brands and fullVersionList: patch them too.
getHighEntropyValues: async (h) => {
const r = await hev(h);
if (r.brands) r.brands = fix(r.brands);
if (r.fullVersionList) r.fullVersionList = fix(r.fullVersionList);
return r;
},
// toJSON is used when the object is serialised; must match the patched fields.
toJSON: () => ({ brands, mobile: d.mobile, platform: d.platform }),
};
// Installed on the prototype, same as userAgent above.
def(Navigator.prototype, "userAgentData", () => patched);
})();
+54
View File
@@ -1,102 +1,155 @@
// Content script on Teams web: logs active speaker, shares, captions, chat, hands, presence while recording.
// Events go via the offscreen document (it has host_permissions for 127.0.0.1). Never clicks or types in the call.
// DOM selectors for the Teams web client. The data-tid attributes are Teams' internal test ids and can change with Teams releases.
const SEL = {
// Call elapsed-time element.
duration: '[data-tid="call-duration"]',
// Name label inside each participant tile.
nametag: '[data-tid="participant-info-nametag"]',
// Participant info container.
info: '[data-tid="participant-info"]',
// Speaking outline: data-is-speaking="true" while the participant talks.
speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]',
// The local user's own video tile.
self: '[data-tid="myself-video"]',
// Screen-share banner aria-label (English and Italian UI); group 2 is the sharer's name.
shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/,
caption: '[data-tid="author"],[data-tid="closed-caption-text"]', // DOM order; author only on first row of a speaker's run
// Chat selectors not found yet (null): chat capture is disabled.
chatMsg: null, chatAuthor: null, chatText: null, // discovery step
// Raised-hand selector not found yet (null): hand capture is disabled.
hand: null, // discovery step
};
// State: buf = queued events; timers = intervals; seenCap = caption rows already emitted; capAuthor = last caption speaker; seenChat; lastShare = current sharer; raised = hands up; lastTitle = last title sent.
let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
// Normalise a Teams display name: "LAST, First (Org)" -> "First Last"; ALL-CAPS words are title-cased.
const norm = raw => {
raw = (raw || "").trim();
// Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed.
const m = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!m) return raw;
// Reorder to "First Last" and title-case words that are fully uppercase.
return `${m[2]} ${m[1]}`.split(/\s+/).map(w => (w.length > 1 && w === w.toUpperCase() ? w[0] + w.slice(1).toLowerCase() : w)).join(" ");
};
// Walk up from an element to the participant tile (the ancestor containing a name tag).
const tileOf = el => { while (el && !el.querySelector(SEL.nametag)) el = el.parentElement; return el; };
// Stable participant key: the nearest ancestor data-tid containing "@" (an id), else the name text.
const keyOf = tile => {
for (let e = tile; e; e = e.parentElement) if ((e.dataset?.tid || "").includes("@")) return e.dataset.tid;
return tile.querySelector(SEL.nametag)?.textContent.trim() || "";
};
// Display name from a tile's name tag.
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
// Name of the local user, read from the self-video tile.
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; };
// Queue an event with a wall-clock timestamp; sent later by send().
const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text });
// Wrap timer callbacks so one exception does not kill the interval.
const guard = f => () => { try { f(); } catch (e) { console.error("[teams-whisper]", e); } };
// Send queued events to the offscreen document; errors ignored (the recorder may be closed).
const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
// All participant tiles currently in the DOM.
const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean);
// Emit the meeting title and call elapsed time, but only when the title changes.
function meta() {
// Page title looks like "Meeting | Name | Microsoft Teams": drop the leading segment and the trailing suffix.
const title = document.title.replace(/^[^|]*\|\s*/, "").replace(/\s*\|\s*Microsoft Teams$/, "");
// Nothing new since last time.
if (title === lastTitle) return;
lastTitle = title;
// Payload is JSON in the text field.
emit("meta", "", "", JSON.stringify({ title, call_elapsed: document.querySelector(SEL.duration)?.textContent.trim() || "", url: location.href }));
}
// Roster snapshot: one entry per participant key.
function present() {
// Dedupe by key (a participant can have more than one tile).
const seen = new Map();
// The self tile's name comes from the self-video element.
for (const t of tiles()) seen.set(keyOf(t), { key: keyOf(t), who: t.closest(SEL.self) ? selfName() : nameOf(t) });
// Roster snapshot payload.
emit("present", "", "", JSON.stringify([...seen.values()]));
}
// Emit one "active" event for each participant whose speaking outline is on.
function active() {
// Speaking outlines in the DOM.
for (const el of document.querySelectorAll(SEL.speaking)) {
const t = tileOf(el); if (!t) continue;
// The local user speaking is recorded under the key "self".
if (t.closest(SEL.self) || t.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(t), nameOf(t));
}
}
// Screen share: detect the sharer from the banner aria-label and emit start/stop on change.
function share() {
// Roster names to match the banner text against.
const names = tiles().map(nameOf);
let cur = "";
// Scan all aria-labels for the share banner.
for (const el of document.querySelectorAll("[aria-label]")) {
const m = el.getAttribute("aria-label").match(SEL.shareAria);
// Prefer a roster name the banner text starts with (labels can be truncated); else use the raw text.
if (m) { cur = names.find(n => n && m[2].startsWith(n)) || m[2]; break; }
}
// No change since last check.
if (cur === lastShare) return;
// Previous sharer stopped.
if (lastShare) emit("share_stop", "", lastShare);
if (cur) emit("share_start", "", cur);
lastShare = cur;
}
// Captions, chat and raised hands, each emitted once.
function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) {
// Author row sets the speaker for the text rows that follow it.
if (el.getAttribute("data-tid") === "author") { capAuthor = norm(el.textContent); continue; }
// caption text grows while spoken: emit once it was unchanged for a full tick
// Caption text of this row.
const text = el.textContent.trim(), s = seenCap.get(el) || {};
// Already emitted this row.
if (s.done) continue;
// Unchanged since last tick: treat as final and emit once.
if (text && s.text === text) { s.done = true; emit("caption", "", capAuthor, text); }
s.text = text; seenCap.set(el, s);
}
// Chat messages (inactive while SEL.chatMsg is null); each element is counted once.
if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el);
const text = el.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(el.querySelector(SEL.chatAuthor)?.textContent), text);
}
// Hand raises (inactive while SEL.hand is null); emit only new raises.
if (SEL.hand) {
// Hands raised this tick.
const now = new Set();
for (const el of document.querySelectorAll(SEL.hand)) {
const t = tileOf(el); if (!t) continue;
const k = keyOf(t); now.add(k);
// New raise since the last tick.
if (!raised.has(k)) emit("hand", k, nameOf(t));
}
// Keep only hands still up.
raised = now;
}
}
// Stop: clear timers, flush pending events, and close any open share.
function stop() {
timers.forEach(clearInterval); timers = [];
send();
if (lastShare) { emit("share_stop", "", lastShare); lastShare = ""; }
send();
}
// Start a fresh recording: stop old timers, then reset per-recording state.
function start() {
stop();
// Reset per-recording state.
buf = []; seenCap = new WeakMap(); capAuthor = ""; seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
// Emit the initial snapshot right away.
meta(); present();
// Periodic scans: speaker 500 ms, share and captions 1 s, roster 30 s, flush 5 s.
timers = [
setInterval(guard(() => { meta(); active(); }), 500),
setInterval(guard(share), 1000),
@@ -106,6 +159,7 @@ function start() {
];
}
// Start/stop commands sent by popup.js directly to this tab.
chrome.runtime.onMessage.addListener(m => {
if (m.cmd === "cap-start") start();
if (m.cmd === "cap-stop") stop();
+36
View File
@@ -4,28 +4,38 @@
# ///
# ponytail: ctranslate2 4.8 links cublas64_12 (matches the nvidia-*-cu12 wheels); bump all three together when it moves to CUDA 13
"""Meeting pipeline. uv run --script flow.py <name> [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]"""
# Prefect pipeline entry point. Env vars below (lines 8-16) must be set before prefect is imported (line 21).
import os
# Talk to the local Prefect server started by server.py; setdefault keeps a user override.
os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api")
# Bypass the corporate proxy for localhost, or Prefect API calls get routed out.
os.environ["NO_PROXY"] = "127.0.0.1,localhost"
# Turn off Prefect's usage analytics.
os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false"
# Prefect log level follows LOG_LEVEL (default INFO).
os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper())
os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI
# stdlib only: CLI args, JSON, paths, exit codes.
import argparse, json, sys
from pathlib import Path
from prefect import flow, task
from prefect.runtime import flow_run
from prefect.task_runners import ThreadPoolTaskRunner
# Pipeline stage modules living next to this file.
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
HERE = Path(__file__).parent
# Stage order. --from picks a start point; go() compares indices into this list.
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render", "title"]
# Record the current stage for the GUI. LLM stages include the loaded model name so timing stats stay per model.
def step_status(name, s):
# key per model for the LLM steps: their speed (and so the ETA) depends on it
db.step(name, s, f"{s}@{llama.current(s == 'shots')}" if s in ("shots", "report") else s)
# One Prefect task per stage: set status, then call the stage's run().
@task(name="audio")
def t_audio(name): step_status(name, "audio"); audio.run(name)
@@ -40,6 +50,7 @@ def t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speake
@task(name="speakers")
def t_speakers(name): step_status(name, "identifying"); speakers.run(name)
# shots/docs/report call LLM servers that can fail transiently: retry once after 10 s.
@task(name="shots", retries=1, retry_delay_seconds=10)
def t_shots(name, status=True):
if status: step_status(name, "shots")
@@ -55,6 +66,7 @@ def t_report(name): step_status(name, "report"); report.run(name)
def t_memory(name): step_status(name, "memory"); memory.run(name)
# Owns one llama-server process per run; switching profile (vision <-> text) restarts it.
class Llama:
"""Start llama-server in vision (shots) or text (report) profile; switching restarts it. Terminate in close() only if we started it."""
def __init__(self, name): self.name, self.p, self.vision = name, None, None
@@ -65,15 +77,18 @@ class Llama:
try:
p = llama.start(vision=vision, log=log)
except Exception:
# llama.log with 'out of memory' means another CUDA app holds VRAM; tell the user the fix.
if log.exists() and "out of memory" in log.read_text(errors="replace"):
raise RuntimeError("GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'")
raise
# Keep the process we started earlier; llama.start() returns None when a server is already running.
self.p = self.p or p
def close(self):
if self.p and self.p.poll() is None: self.p.terminate(); self.p.wait() # wait: port must be free before a profile switch
self.p = None
# Device: GUI/bench file wins, else cuda. Unknown values fall back to cuda.
def default_device():
try:
d = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
@@ -82,24 +97,31 @@ def default_device():
return "cuda"
# Up to 3 threads; ordering comes from explicit .result() waits, not from the runner.
@flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3))
def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str = "large-v3-turbo", device: str | None = None):
device = device or default_device()
# True if stage s is at or after the requested start (--from).
go = lambda s: STEPS.index(s) >= STEPS.index(start_from)
# Owns the llama-server process; always closed in the finally block.
L = Llama(name)
try:
# Link the DB row to this Prefect run so the GUI can find it.
db.upsert_recording(name, flow_run_id=str(flow_run.id))
db.progress_start(name, start_from)
# shots run every time unless the GUI toggle "Salta schermate" is on
# Resume: reuse shots already extracted by an earlier run.
sj = db.out_dir(name) / "shots.json"
try: done = json.loads(sj.read_text(encoding="utf-8"))
except (OSError, ValueError): done = []
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
skip_shots = no_shots
# Toggle on with no prior shots: write empty placeholders so downstream steps find their files.
if no_shots and not done:
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
db.replace_shots(name, [])
if skip_shots and go("shots"): print("shots skipped")
# Title/render restart: re-run only text-only post-processing, no vision model needed.
if start_from == "title":
L.ensure(vision=False)
report.retitle(name)
@@ -108,45 +130,58 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str
memory.run(name, link=False)
else:
if go("audio"): t_audio(name)
# Speaker labelling: diarize, then name mapping.
spk_chain = lambda: [t_diarize(name, speakers), t_speakers(name)] if go("diarize") else ([t_speakers(name)] if go("speakers") else None)
# NPU path: transcribe on the NPU while shots run on the GPU VLM at the same time.
if device == "npu" and go("transcribe") and go("shots") and not skip_shots:
db.set_status(name, "transcribing")
L.ensure()
f_t = t_transcribe.submit(name, model, "npu", False)
f_s = t_shots.submit(name, False)
# Wait for NPU transcription; shots keep running meanwhile.
try:
f_t.result()
except Exception as e:
# Only the NPU failure is handled here; anything else is a real error.
if "NPU failed" not in repr(e): raise
f_s.result(); L.close()
print("NPU failed, transcribed on cuda")
t_transcribe(name, model, "cuda")
# Shots already finished above; clear the handle.
spk_chain(); L.ensure(); f_s = None
else:
spk_chain()
# Shots still running in parallel; wait for them before text stages.
if f_s is not None: f_s.result()
else:
# Sequential path (CUDA, or NPU without shots).
if go("transcribe"): t_transcribe(name, model, device)
spk_chain()
if go("shots") and not skip_shots: L.ensure(); t_shots(name)
L.ensure(vision=False) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
if go("docs"): t_docs(name)
if go("report"): t_report(name)
# Memory update: always runs as the final stage.
t_memory(name)
db.step(name, "done")
except Exception as e:
# Record the failure for the GUI, then re-raise so Prefect marks the run failed.
db.set_status(name, "error", repr(e)[:500])
raise
finally:
L.close()
# Benchmark both transcribers on the same audio and store the choice for default_device().
def bench(name):
d = db.out_dir(name)
# A failed NPU run is recorded as None so the comparison below picks CUDA.
try: npu_s = transcribe.run(name, device="npu", out_path=d / "bench_npu.txt")
except Exception as e: print("npu error:", e); npu_s = None
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt")
# NPU is picked unless it failed or is more than 3x slower than CUDA (deliberate tolerance, not fastest-wins).
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
# Persist for later runs (read by default_device).
(db.GLOBAL / "transcribe_device.txt").write_text(dev)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
@@ -161,5 +196,6 @@ if __name__ == "__main__":
ap.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster"); ap.add_argument("--device", choices=["cuda", "npu"])
ap.add_argument("--bench-npu", action="store_true")
a = ap.parse_args()
# --bench-npu is a one-off benchmark; it does not run the pipeline.
if a.bench_npu: bench(a.name)
else: meeting(a.name, a.start, a.speakers, device=a.device)
+57
View File
@@ -1,6 +1,8 @@
# llama.py: starts llama-server (local GGUF chat/vision/embedding), routes chat to local or cloud models, installs omp and downloads models.
import functools, hashlib, json, os, shutil, socket, ssl, subprocess, sys, time, urllib.error, urllib.request
from pathlib import Path
# Paths relative to this file: bin/ (llama-server, omp), models/ (GGUF), out/ (GUI state).
HERE = Path(__file__).parent
SERVER = HERE / "bin" / "llama-server.exe"
MD = HERE / "models"
@@ -23,12 +25,15 @@ MODELS = {
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q],
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]),
}
# Ports on 127.0.0.1: chat completion server and bge-m3 embedding server.
PORT = 18081
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
# Cached: nvidia-smi is slow and the GPU does not change while the app runs.
@functools.cache
def vram_mib():
"""Largest NVIDIA GPU's total VRAM in MiB; 0 without NVIDIA driver."""
# memory.total per GPU in MiB, plain numbers (nounits); max() picks the largest card.
try: return max(int(x) for x in subprocess.run(["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=10).stdout.split())
except (OSError, ValueError, subprocess.SubprocessError): return 0
@@ -57,18 +62,22 @@ REMOTE = {
"an-haiku": ("Claude Haiku 5.5 (Anthropic, abbonamento)", "claude-haiku-5-5", True, "anthropic"),
"an-sonnet": ("Claude Sonnet 5.5 (Anthropic, abbonamento)", "claude-sonnet-5-5", True, "anthropic"),
}
# Headers that make Copilot's API accept requests as from the Copilot CLI / editor plugin.
_HDR = {"Editor-Version": "vscode/1.107.1", "Editor-Plugin-Version": "copilot-chat/0.26.7", "Copilot-Integration-Id": "copilot-developer-cli"}
_ctx = ssl.create_default_context(); _ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT # corp TLS proxy CA lacks critical basicConstraints
_NO_PROXY = "localhost,127.0.0.1,.audi.vwg,.vwgroup.com,.vwg,.italdesign.it" # same list as $PROFILE
# Cache of the proxy probe: [timestamp, proxy URL or None].
_PX = [0.0, None]
def proxy():
"""PROXY if reachable right now (TCP connect, 2 s; = $PROFILE's Test-Connection), else None. Re-checked every 5 min: laptops move between office/VPN/home."""
if time.time() - _PX[0] > 300:
# Reachability probe only: a TCP connect to the proxy host, no HTTP request.
try: socket.create_connection(("zproxy.idg.audi.vwg", 9400), timeout=2).close(); px = PROXY
except OSError: px = None
_PX[:] = [time.time(), px]
return _PX[1]
# One opener per proxy setting; the proxy URL is the cache key.
@functools.cache
def _opener(px):
return urllib.request.build_opener(urllib.request.ProxyHandler({"https": px, "http": px} if px else {}), urllib.request.HTTPSHandler(context=_ctx)).open
@@ -78,21 +87,28 @@ def _ropen():
def omp_env():
"""Env for omp subprocesses: omp ignores HTTP(S)_PROXY and reads PI_PROXY; the corp proxy re-signs TLS. Without the proxy, strip every proxy var."""
# Build omp's env without any inherited proxy vars, so a stale proxy setting cannot leak in.
env = {k: v for k, v in os.environ.items() if k.upper() not in ("HTTP_PROXY", "HTTPS_PROXY", "PI_PROXY", "NO_PROXY")}
# NODE_TLS_REJECT_UNAUTHORIZED=0: omp's Node runtime rejects the corp proxy's re-signed certificate.
# Corp proxy only while reachable; it re-signs TLS, so omp must accept its certificate.
if px := proxy(): env.update(HTTP_PROXY=px, HTTPS_PROXY=px, PI_PROXY=px, NO_PROXY=_NO_PROXY, NODE_TLS_REJECT_UNAUTHORIZED="0")
return env
# Local models whose GGUF file is present on disk.
def _local(): return [k for k, m in MODELS.items() if m[1].exists()]
# Installed local models, plus cloud models (vision=True keeps only those accepting images).
def available(vision=True): return _local() + [k for k, r in REMOTE.items() if r[2] or not vision]
def label(k): return (MODELS.get(k) or REMOTE[k])[0]
def current(vision=True):
"""Model for shots (vision) or report/ask (text): GUI choice if available, else 4B for shots (VRAM-only, near-35B shots)
and the biggest local model for reports (4B reports lose structure on long transcripts). Falls back to the first cloud model only when no local model is installed (cloud-only install)."""
# CHOICE holds "<vision key> <text key>"; an empty file gives [""] so fallbacks apply.
ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""]
k = ks[0] if vision else ks[-1] # a single key (old format) applies to both
if k in available(vision): return k
loc = _local()
# 4B fits fully in VRAM: shots near 35B quality at much higher speed (see MODELS).
if vision and "qwen4b" in loc: return "qwen4b"
return (loc or available(vision))[0]
@@ -103,15 +119,22 @@ _TOK = {} # provider -> (token, api base, fetched at)
def _token(provider):
"""(token, api base) via `omp token` (it refreshes expired OAuth). ponytail: 5-min cache, re-query on every call if a token ever dies inside it."""
t = _TOK.get(provider)
# Reuse the cached token for 5 min instead of spawning omp on every call.
if t and time.time() - t[2] < 300: return t[:2]
exe = omp_exe()
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio")
# --raw: bare token, or JSON {token, apiEndpoint}; 60 s guards against a hung omp.
r = subprocess.run([exe, "token", provider, "--raw"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60, env=omp_env())
# Non-zero exit = not logged in; surface the reason to the GUI.
if r.returncode: raise RuntimeError(f"{provider}: login necessario (Pinokio → Cloud login). {r.stderr.strip()[:200]}")
# omp prints a JSON object {token, apiEndpoint} or a bare token; accept both.
out = r.stdout.strip(); d = json.loads(out) if out.startswith("{") else {"token": out}
# Fallback API base when omp does not report apiEndpoint.
base = d.get("apiEndpoint") or ("https://api.githubcopilot.com" if provider == "github-copilot" else "https://api.anthropic.com")
# Cache the token with its fetch time (checked against the 5-min TTL above).
_TOK[provider] = (d["token"], base, time.time()); return _TOK[provider][:2]
# Cache for omp_status(): [timestamp, status dict].
_ST = [0.0, None]
def omp_status():
"""{'exe': path|None, 'github-copilot': None|reason, 'anthropic': None|reason}: can omp hand out a valid (refreshed) token right now. Cached 60 s (GUI polls every 3 s).
@@ -119,79 +142,108 @@ def omp_status():
if time.time() - _ST[0] < 60: return _ST[1]
s = {"exe": omp_exe()}
for p in ("github-copilot", "anthropic"):
# Drop the cached token so every provider is re-checked for real.
_TOK.pop(p, None)
try: _token(p); s[p] = None
except Exception as e: s[p] = str(e)
_ST[:] = [time.time(), s]; return s
# Headers Anthropic requires for subscription OAuth (mirrors Claude Code's client).
_AHDR = {"anthropic-version": "2023-06-01", "anthropic-beta": "claude-code-20250219,oauth-2025-04-20", "user-agent": "claude-cli/2.1.280", "x-app": "cli"}
def _anthropic(body, model, tok, timeout):
"""OpenAI chat body -> Anthropic Messages (subscription OAuth needs the Claude Code identity first, as omp/pi send) -> OpenAI-shaped response."""
# Anthropic accepts subscription OAuth only with the Claude Code identity as the first system block.
system, msgs = [{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude."}], []
for m in body["messages"]:
# Anthropic takes system as blocks, so system messages are collected separately.
if m["role"] == "system": system.append({"type": "text", "text": m["content"]}); continue
c = m["content"]
if isinstance(c, list): # shots.py: text + data-URL jpeg
# OpenAI content parts -> Anthropic blocks; images arrive as data URLs.
c = [{"type": "text", "text": p["text"]} if p["type"] == "text" else
# data:<mime>;base64,<data>: [5:] strips "data:", the mime is before ";".
{"type": "image", "source": {"type": "base64", "media_type": p["image_url"]["url"][5:].split(";")[0], "data": p["image_url"]["url"].split(",", 1)[1]}} for p in c]
msgs.append({"role": m["role"], "content": c})
req = {"model": model, "max_tokens": body.get("max_tokens", 8192), "system": system, "messages": msgs, "thinking": {"type": "disabled"}} # no temperature: deprecated on these models (HTTP 400); thinking off: it eats max_tokens (empty text)
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_AHDR}
# Request goes through _ropen() so the corp proxy applies when reachable.
try: d = json.load(_ropen()(urllib.request.Request("https://api.anthropic.com/v1/messages", json.dumps(req).encode(), h), timeout=timeout))
except urllib.error.HTTPError as e: raise RuntimeError(f"Anthropic {model}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
# Re-wrap in OpenAI shape so report/ask/memory callers need no Anthropic branch.
return {"choices": [{"message": {"content": "".join(b.get("text", "") for b in d["content"] if b["type"] == "text")}}],
"usage": {"prompt_tokens": d["usage"]["input_tokens"], "completion_tokens": d["usage"]["output_tokens"]}}
def post(body, vision, timeout):
"""Chat completion on llama-server, or on a cloud model (Copilot / Anthropic via omp login) when the GUI picked a REMOTE model."""
# Local llama-server unless the GUI picked a cloud (REMOTE) model.
# GUI choice decides local vs cloud; REMOTE holds the cloud model metadata.
k = current(vision); r = REMOTE.get(k)
if not r:
# Local llama-server, OpenAI-compatible endpoint.
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k}).encode(), {"Content-Type": "application/json"})
return json.load(_open(req, timeout=timeout))
# Cloud: token and API base from omp.
tok, base = _token(r[3])
# chat_template_kwargs is llama.cpp-specific; cloud APIs would reject it.
body = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1]}
if r[3] == "anthropic": return _anthropic(body, r[1], tok, timeout)
# Copilot needs this header to accept image inputs.
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR, **({"Copilot-Vision-Request": "true"} if vision else {})}
try: return json.load(_ropen()(urllib.request.Request(base + "/chat/completions", json.dumps(body).encode(), h), timeout=timeout))
except urllib.error.HTTPError as e:
if e.code == 400: raise # callers retry 400 without response_format
raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
# Persist the GUI choice as "<vision key> <text key>" in out/_global/llm.txt (read by current()).
def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
def content(resp, what):
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints)."""
# llama.cpp reports timings; cloud APIs report usage instead.
t = resp.get("timings") or {}
# Reasoning models: count thinking words for the speed log only.
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split())
if t: print(f"llm {what}: prompt {t.get('prompt_n', 0)} tok @ {t.get('prompt_per_second', 0):.0f} t/s, "
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s" + (f" (thinking ~{think} words)" if think else ""), flush=True)
elif resp.get("usage"): print(f"llm {what}: prompt {resp['usage'].get('prompt_tokens', 0)} tok, gen {resp['usage'].get('completion_tokens', 0)} tok (cloud)", flush=True)
return resp["choices"][0]["message"]["content"]
# Health probe: llama-server answers /health once the model is loaded.
def up(port=PORT):
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True
except Exception: return False
# Launch llama-server on port and wait until /health answers. Returns the Popen, or None if already up.
def _spawn(args, port, log):
# Already serving on this port: reuse it instead of starting a second copy.
if up(port): return None
# Log to a file, not a pipe: nothing reads a pipe here, so the server would block once it fills.
p = subprocess.Popen([str(SERVER), *args, "--port", str(port)], stdout=open(log, "w"), stderr=subprocess.STDOUT)
# Poll every 2 s for up to 20 min: large models take minutes to load.
for _ in range(600):
if up(port): return p
# Server exited (bad args, out of memory): fail now instead of waiting out the timeout.
assert p.poll() is None, f"llama-server died, see {log}"
time.sleep(2)
raise TimeoutError("llama-server not ready")
def start(vision=True, port=PORT, log="llama.log"):
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
# Cloud choice from the GUI: no local server to start.
if current(vision) in REMOTE: return None
# MODELS entry: (label, model, mmproj, vision args, text args).
_, model, mmproj, vargs, targs = MODELS[current(vision)]
# Vision: mmproj for images. Text: no mmproj. --jinja applies the model's chat template.
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *_fit(vargs, True)] if vision else _fit(targs, False)), "--jinja"], port, log)
def start_embed(log="embed.log"):
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
# bge-m3 on CPU only (-ngl 0, -dev none); 8k context; CLS pooling as bge-m3 expects.
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-dev", "none", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
# Latest stable omp build metadata (JSON with download URL and sha256).
OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
# models.yml seeded into ~/.omp/agent: Copilot provider and its BYOK models.
MODELS_YML = """providers:
github-copilot:
auth: none
@@ -242,6 +294,7 @@ def install_omp():
OMP_LOCAL.parent.mkdir(exist_ok=True)
ua = {"User-Agent": "teams-whisper-install"} # the build API answers 403 to python-urllib's default UA
j = json.load(_ropen()(urllib.request.Request(OMP_BUILD, headers=ua), timeout=60)); part = OMP_LOCAL.with_suffix(".part"); h = hashlib.sha256()
# Stream into .part while hashing; rename only after the sha256 check passes.
with _ropen()(urllib.request.Request(j["download"], headers=ua), timeout=900) as r, open(part, "wb") as f:
while b := r.read(1 << 20): h.update(b); f.write(b)
if h.hexdigest() != j["file"]["sha256"].lower(): part.unlink(); raise RuntimeError("omp download: checksum mismatch")
@@ -254,6 +307,7 @@ def login(provider, if_needed=False):
"""Interactive `omp login` in this console with the proxy env; if_needed: skip when omp already hands out a valid token (install)."""
exe = omp_exe()
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio")
# if_needed: skip the interactive login when a token is already available.
if if_needed:
try: _token(provider); print(provider, "already logged in"); return
except RuntimeError: pass
@@ -264,11 +318,14 @@ def download(url, dest):
dest = Path(dest)
if dest.exists(): print("kept", dest); return
dest.parent.mkdir(parents=True, exist_ok=True); part = dest.with_name(dest.name + ".part")
# Resume: bytes already in .part; ask the server for the rest (Range header).
have = part.stat().st_size if part.exists() else 0
h = {"User-Agent": "teams-whisper-install", **({"Range": f"bytes={have}-"} if have else {})}
# Append only if the server honored Range (206); otherwise restart the file.
with _ropen()(urllib.request.Request(url, headers=h), timeout=900) as r, open(part, "ab" if have and r.status == 206 else "wb") as f: shutil.copyfileobj(r, f, 1 << 20)
part.replace(dest); print("downloaded", dest)
# CLI entry point: `install-omp`, `login <provider> [--if-needed]`, `download <url> <dest>`.
if __name__ == "__main__":
a = sys.argv[1:]
if a == ["install-omp"]: install_omp()
+22
View File
@@ -11,66 +11,88 @@ from pathlib import Path
import numpy as np
import pyaudiowpatch as pa
# CLI: --screen adds video, --name sets the folder under out/, --seconds auto-stops.
ap = argparse.ArgumentParser()
ap.add_argument("--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)")
ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
ap.add_argument("--seconds", type=float, help="auto-stop after N seconds")
a = ap.parse_args()
out = Path(__file__).parent / "out" / a.name; out.mkdir(parents=True, exist_ok=True) # out/<name>/source.mp4 + source.wav
# Output rate: matches what transcription expects (16 kHz mono).
SR = 16000
# Downmix to mono, then resample to SR by linear interpolation (simple, fine for speech).
def to16k(x, ch, sr):
x = x.reshape(-1, ch).mean(axis=1)
n = int(len(x) * SR / sr)
return np.interp(np.linspace(0, len(x) - 1, n), np.arange(len(x)), x).astype(np.float32)
# Capture system audio (WASAPI loopback = what plays on the speakers) and the default mic.
def record():
p = pa.PyAudio()
# Loopback device and default mic device.
lb = p.get_default_wasapi_loopback()
mic = p.get_device_info_by_index(p.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"])
bufs = {"sys": [], "mic": []}
streams = []
# One stream per source, at the device's own channel count and rate; converted to 16 kHz mono in the mix step.
for key, d in (("sys", lb), ("mic", mic)):
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"])
# Callback appends raw PCM chunks; paContinue keeps the stream running.
def cb(data, f, t, s, key=key): bufs[key].append(data); return (None, pa.paContinue)
# int16 PCM, 1024-frame buffers.
st = p.open(format=pa.paInt16, channels=ch, rate=sr, input=True,
input_device_index=d["index"], frames_per_buffer=1024, stream_callback=cb)
streams.append((key, ch, sr, st))
print(f"loopback: {lb['name']}\nmic: {mic['name']}")
ff = None
# Optional screen capture: ffmpeg gdigrab at 15 fps, H.264 mp4.
if a.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(out / "source.mp4")], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("Recording... Ctrl+C to stop")
# Wait until Ctrl+C or the --seconds limit.
try:
t0 = time.time()
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5)
except KeyboardInterrupt: pass
# Send 'q' so ffmpeg finalises the mp4 cleanly.
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait()
# Stop PortAudio.
p.terminate()
# Mix: decode each stream and convert to 16 kHz mono float in [-1, 1].
mix = []
for key, ch, sr, st in streams:
raw = np.frombuffer(b"".join(bufs[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw): mix.append(to16k(raw[: len(raw) // ch * ch], ch, sr))
# Pad shorter streams with silence and sum them.
n = max(len(m) for m in mix)
y = sum(np.pad(m, (0, n - len(m))) for m in mix)
# Clip to avoid overflow when summing.
y = np.clip(y, -1, 1)
path = out / "source.wav"
# Write a 16-bit mono WAV.
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((y * 32767).astype(np.int16).tobytes())
return path
# Save the DB row, then run the transcription/report pipeline (flow.py) as a child uv process.
def finish(path):
import os
import db
now = time.strftime("%Y-%m-%d %H:%M:%S")
# Queued DB row with the start and end time.
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued")
# Drop inherited PYTHONHOME vars so the child uv/python picks its own interpreter.
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
# Point the child at the local Prefect server; bypass the proxy for localhost.
env.update(PREFECT_API_URL="http://127.0.0.1:4200/api", NO_PROXY="127.0.0.1,localhost")
subprocess.run(["uv", "run", "--script", "flow.py", a.name], cwd=Path(__file__).parent, env=env)
# Start timestamp stored in the DB row.
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
# Record, then hand off to the pipeline.
finish(record())
+38
View File
@@ -8,16 +8,23 @@ import contextlib, json, re, sys, urllib.request
import numpy as np
import db, llama, report
# bge-m3 embeddings endpoint on the local embedding server.
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
# MEM_MIN: min cosine to link; K_TOPIC: candidates per topic; K_ASK: excerpts for a question.
MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
# Direct opener bypassing the corp proxy (the embedding server is localhost).
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
# Italian prompt: link current-meeting topics to earlier excerpts; JSON output.
SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.')
# Prompt for ask(): answer from numbered excerpts only, cite as [n].
SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi SOLO JSON: {"answer":str}. Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.'
# Valid link statuses; anything else from the LLM is dropped.
STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
# Start the CPU embedding server for the block; stop it on exit only if this call started it.
@contextlib.contextmanager
def embedder(log):
p = llama.start_embed(log=log)
@@ -26,6 +33,7 @@ def embedder(log):
if p is not None: p.terminate()
# Embed texts via the local embedding server, 32 per request, each cut to 2000 chars.
def embed(texts):
out = []
for i in range(0, len(texts), 32):
@@ -33,14 +41,17 @@ def embed(texts):
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])]
v = np.array(out, dtype=np.float32)
# L2-normalize so dot products are cosine similarities.
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
def _stamp(n):
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n)
return m[0] if m else ""
# Load memory rows matching pred and stack their vectors into an (n, dim) matrix.
def _rows(pred):
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k.
rows = [r for r in db.connect().execute("SELECT * FROM memory") if pred(r)]
@@ -48,76 +59,101 @@ def _rows(pred):
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1)
# Summary entries may be dicts {"text": ...} or plain strings.
def _txt(x): return x["text"] if isinstance(x, dict) else str(x)
# Topic as one string: title (optional), summary, decisions, open questions.
def _topic_text(t, title=True):
parts = ([t["title"]] if title else []) + [_txt(x) for x in t.get("summary", [])] + list(t.get("decisions", [])) + list(t.get("open_questions", []))
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p)
# Embed one meeting's report items into the memory table (replaces its previous rows).
def index(name):
# slugify matches the report's heading anchors.
from markdown.extensions.toc import slugify
rep = report._load(name, "report.json", None)
if rep is None: return
rep, _ = report.named(name, rep)
items = []
# One item per topic summary, decision, action and open question.
for i, t in enumerate(rep["topics"], 1):
# Shared fields of every item of this topic: (name, position, start, meeting, date, title, anchor).
base = (name, i, t["start_s"], rep["meeting_title"], rep["date"], t["title"], slugify(report._head(i, t), "-"))
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])]
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])]
its += [("open_question", x) for x in t.get("open_questions", [])]
items += [(base, k, x) for k, x in its if x]
# Nothing to index: clear the old rows for this meeting.
if not items: db.replace_memory(name, []); return
# Prefix the title so each item's vector carries its topic context.
V = embed([f"{b[5]}: {x}" for b, _, x in items])
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)])
print(f"memory: indexed {len(items)} items")
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, text.
def _prev_line(n, r): return f"[{n}] {r['date']} «{r['meeting']}» — {r['topic']} ({r['kind']}): {r['text']}"
# Link this meeting's topics to earlier meetings; results go into report.json.
def _link(name):
rep = report._load(name, "report.json", None)
if rep is None: return
named_rep, _ = report.named(name, rep)
# Stamp of this meeting, from its folder name.
cur = _stamp(name)
# Only strictly earlier meetings; stamps sort lexicographically.
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur)
# Clear old links so re-running the step does not accumulate them.
for t in rep["topics"]: t["previous"] = []
if rows:
# Query vectors: each current topic as title + content.
Q = embed([_topic_text(t) for t in named_rep["topics"]])
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
S = Q @ M.T
for t, nt, s in zip(rep["topics"], named_rep["topics"], S):
# Best K_TOPIC candidates above the MEM_MIN similarity threshold.
top = [j for j in np.argsort(-s)[:K_TOPIC] if s[j] >= MEM_MIN]
if not top: continue
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", []))
# Prompt: current topic, then numbered earlier excerpts the model may cite as [n].
user = (f"ARGOMENTO: {nt['title']}\nSINTESI: {' '.join(_txt(x) for x in nt.get('summary', []))}\nDECISIONI: {'; '.join(nt.get('decisions', []))}\n"
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n"
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1)))
# report.chat returns parsed JSON or None; None -> no links.
r = report.chat(SYS_M, user, 1500) or {}
# Cap at 4 links per topic (matches the prompt).
for l in (r.get("links") or [])[:4]:
# Validate LLM output: ref in range, known status, non-empty text.
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip()
except (KeyError, TypeError, ValueError): continue
if 1 <= ref <= len(top) and st in STATUSES and tx:
p = rows[top[ref - 1]]
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"],
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]})
# Write links into report.json; run() re-renders from it.
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
def run(name, link=True):
"""Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow."""
try:
# Embedder lives for linking and indexing; its log sits with the meeting logs.
with embedder(db.logs(name) / "embed.log"):
if link:
try: _link(name)
except Exception as e: print("memory link skipped:", repr(e))
index(name)
except Exception as e: print("memory index skipped:", repr(e))
# Render even when the memory steps failed.
report.render(name)
# Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n].
def ask(q):
# Cosine search over the normalized matrix; keep the best K_ASK excerpts.
rows, M = _rows(lambda r: True)
if not rows: return {"answer": "Nessuna riunione indicizzata.", "sources": []}
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK]
@@ -128,7 +164,9 @@ def ask(q):
if __name__ == "__main__":
# Force UTF-8 so Italian text prints correctly on Windows consoles.
sys.stdout.reconfigure(encoding="utf-8")
# CLI: rebuild the memory index for every meeting that has a report.json.
if "--reindex" in sys.argv:
with embedder(db.GLOBAL / "embed.log"):
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
+111
View File
@@ -1,10 +1,15 @@
"""Topic summaries (local llama-server) + report.md / report.html rendering."""
import base64, difflib, json, re, unicodedata, urllib.request
# db: SQLite meeting store; llama: client for the local llama-server.
import db, llama
# Screen-capture kinds that count as shared content.
from shots import CONTENT_KINDS
# Base URL for Jira ticket links.
JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
# Jira key, e.g. ABC-123: uppercase project of 2-10 chars, then 1-6 digits.
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
# Prompt pass 1: split the transcript/screen timeline into topics, answer as JSON.
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
@@ -13,15 +18,21 @@ SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"to
'Nel summary riporta ciò che è stato detto, spiegato e deciso, non la navigazione tra le schermate (es. «si apre la console»): al massimo 6 punti per argomento. '
'Non scrivere voci vuote come «nessuna domanda aperta»: lascia la lista vuota. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Glossario dei termini corretti letti dallo schermo (la trascrizione può storpiarli, usa la grafia del glossario): ')
# Prompt pass 3: meeting title + up to 5 TL;DR points from the topic list.
SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr":[str]}. title: titolo breve della riunione (max 8 parole). Massimo 5 punti in tldr, in italiano, forma impersonale, senza etichette "Speaker N". Usa solo fatti presenti.'
# Prompt pass 2 (per topic): complete the summary with numbered doc extracts; from_docs = extra doc facts.
SYS_D = ('Hai un argomento di una riunione e alcuni estratti di documentazione aziendale numerati. Rispondi SOLO JSON: {"summary":[{"text":str,"doc":int|null}],"from_docs":[{"text":str,"doc":int}]}. '
'"summary": riscrivi i punti della sintesi mantenendo tutti i fatti della riunione; puoi completarli o correggerli con la documentazione indicando in "doc" il numero dell\'estratto usato (null se il punto viene solo dalla riunione). '
'Se riunione e documentazione divergono, riporta entrambe ("in riunione …; secondo la documentazione …"). "from_docs": massimo 3 fatti della documentazione pertinenti all\'argomento e non detti in riunione. Non citare etichette "Speaker N". Non inventare. Scrivi in italiano.')
# Tuning: CLUSTER = name similarity to merge spellings; TIDY_MIN = seconds below which a topic is merged into a neighbour; DOC_MIN = shared long words needed to attach a doc.
CLUSTER, TIDY_MIN, DOC_MIN = 0.82, 120, 3
# Local GUI server, used for links to previous meetings.
GUI = "http://127.0.0.1:18765"
# Seconds -> "mm:ss".
def mmss(s): s = int(s); return f"{s // 60:02d}:{s % 60:02d}"
# "mm:ss" (or leading digits) -> seconds; 0 if no match.
def secs(s):
m = re.match(r"(\d+):(\d+)", str(s))
return int(m[1]) * 60 + int(m[2]) if m else 0
@@ -30,11 +41,13 @@ def secs(s):
PROG = None # [name, calls done, calls expected] while report.run() is active
# Progress note: print (goes to the Prefect log) and, while run() is active, advance the DB progress counter.
def _tick(note):
print(f"report: {note}", flush=True) # flow(log_prints=True) -> Prefect log
if PROG: PROG[1] += 1; db.tick(PROG[0], PROG[1], max(PROG[2], PROG[1] + 1) if note != "fine" else PROG[1], note)
# Title typed manually in the meeting metadata (wins over the LLM title).
def _manual_title(name):
return db.meta(name).get("title", "")
@@ -50,19 +63,25 @@ def _strip_junk(o):
def chat(system, user, max_tokens, retries=2, think=False):
"""think=True only for the report passes (topics, docs merge, overview); docs queries and memory stay fast."""
# response_format requests JSON; enable_thinking toggles reasoning. THINK tokens are added only when thinking is on.
body = {"temperature": 0.2, "max_tokens": max_tokens + (THINK if think else 0),
"chat_template_kwargs": {"enable_thinking": think}, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
# Retry on unparseable output or a non-dict result.
for _ in range(retries):
try:
try:
r = llama.post(body, False, 1800)
except urllib.error.HTTPError as e:
# Only HTTP 400 is retried without response_format; other errors propagate.
if e.code != 400: raise
body.pop("response_format", None)
r = llama.post(body, False, 1800)
# Extract the assistant text from the response.
t = llama.content(r, f"report ({max_tokens} max)")
# Drop <think>...</think> reasoning blocks emitted by thinking models.
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
# Parse the outermost {...} span (tolerates prose around the JSON), then strip junk.
d = _strip_junk(json.loads(t[t.find("{"):t.rfind("}") + 1]))
if isinstance(d, dict): return d
except (ValueError, KeyError): pass
@@ -74,11 +93,13 @@ def _transcript(name):
return [(int(t), sp, x) for t, sp, x in db.connect().execute("SELECT t, speaker, text FROM lines WHERE name=? ORDER BY rowid", (name,))]
# Read out/<name>/<f> as JSON, or return default if the file is missing.
def _load(name, f, default):
p = db.out_dir(name) / f
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else default
# Presence-share spans from share_start/share_stop events; a share still open at the end runs to dur.
def _shares(evs, dur):
out, open_ = [], {}
for e in evs:
@@ -88,10 +109,12 @@ def _shares(evs, dur):
return sorted(out, key=lambda x: x["start"])
# Replace "Speaker N" labels in a string with mapped names (unknown labels kept as-is).
def _subst(s, names):
return re.sub(r"\bSpeaker (\d+)\b", lambda m: names.get(m[0]) or m[0], s) if isinstance(s, str) else s
# Apply f to every string leaf of a nested list/dict, returning a new structure.
def _deep(o, f):
if isinstance(o, str): return f(o)
if isinstance(o, list): return [_deep(x, f) for x in o]
@@ -99,6 +122,7 @@ def _deep(o, f):
return o
# Merge consecutive topics with equal titles (case-insensitive) into one.
def _merge(topics):
out = []
for t in topics:
@@ -110,7 +134,9 @@ def _merge(topics):
return out
# Name normalization: strip accents, lowercase, collapse whitespace, sort words so word order does not matter.
def _key(n): return " ".join(sorted(unicodedata.normalize("NFKD", n).encode("ascii", "ignore").decode().lower().split()))
# Similarity 0..1 of two names after _key normalization.
def _sim(a, b): return difflib.SequenceMatcher(None, _key(a), _key(b)).ratio()
@@ -130,6 +156,7 @@ def canon(counts, known, video=False, thr=CLUSTER):
return out
# Re-key attendee spans by canonical name; merged names keep the earliest first_t and latest last_t.
def _canon_att(att, cmap):
out = {}
for a in att.values():
@@ -140,6 +167,7 @@ def _canon_att(att, cmap):
return out
# Rename share presenters to canonical names (drop unknown ones), merge same-presenter shares with gaps <= 60 s, drop spans < 20 s; repeat until stable.
def _canon_shares(shares, cmap):
ss = sorted(({**s, "who": cmap[s["who"]]} for s in shares if s["who"] in cmap), key=lambda s: s["start"])
while True:
@@ -154,27 +182,34 @@ def _canon_shares(shares, cmap):
def _tidy(topics, dur, min_s=TIDY_MIN):
"""Sort, de-overlap, merge topics shorter than min_s into a neighbour, keep only screen facts timed inside the topic."""
# Sort, then push each topic to start no earlier than the previous one ends (no overlap); min length 1 s.
topics.sort(key=lambda t: t["start_s"])
prev = 0
for t in topics: t["start_s"] = max(t["start_s"], prev); t["end_s"] = max(t["end_s"], t["start_s"] + 1); prev = t["end_s"]
ln = lambda t: t["end_s"] - t["start_s"]
# Repeatedly merge the first topic shorter than min_s into a neighbour.
while len(topics) > 1:
i = next((i for i, t in enumerate(topics) if ln(t) < min_s), None)
if i is None: break
# Neighbour: the previous topic, or the next one when the short topic is first.
j = i - 1 if i else 1
lo, hi = min(i, j), max(i, j)
a, b = topics[lo], topics[hi]
m = dict(a)
# Merged topic keeps the title of the longer of the two.
m["title"] = (a if ln(a) >= ln(b) else b)["title"]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): m[k] = a[k] + b[k]
# Drop filler and duplicates created by the merge.
for k in ("decisions", "open_questions"): m[k] = _clean(m[k])
m["start_s"], m["end_s"] = min(a["start_s"], b["start_s"]), max(a["end_s"], b["end_s"])
topics[lo:hi + 1] = [m]
for t in topics:
# Keep shown facts whose mm:ss timestamp lies within the topic window, +/- 30 s.
t["shown"] = [x for x in t["shown"] if (m := re.search(r"(\d\d):(\d\d)", str(x))) and t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30]
return topics
# Model filler to discard: "nessuno/a", "non sono/è emers/stat...", "n/a", or lines of dashes.
FILLER = re.compile(r"(?i)^\s*(nessun[aoe]?|non (sono|è) (emers|stat)|n/?a\b|-+$)")
@@ -187,37 +222,52 @@ def _clean(xs):
return out
# Distinct lowercase words of 5+ letters: a cheap overlap signal for topic/doc matching.
def _words(s): return {w for w in re.findall(r"\w+", s.lower()) if len(w) >= 5}
def _pass_d(t, docs):
"""Complete/correct a topic's summary with the best-matching docs; sets t['summary'] and t['from_docs'] as {text, doc} dicts."""
# Words of the topic (title, summary, shown) to match against docs.
w = _words(" ".join([t["title"], *(x["text"] for x in t["summary"]), *t["shown"]]))
# Rank docs by number of shared words; keep the top 3 that reach DOC_MIN.
top = sorted(((len(w & _words(d["title"] + " " + d["body"])), d) for d in docs), key=lambda x: -x[0])
top = [d for n, d in top[:3] if n >= DOC_MIN]
if not top: return
# Numbered doc extracts [1..n] appended to the topic.
user = f"ARGOMENTO: {t['title']}\nSINTESI:\n" + "\n".join(f"- {x['text']}" for x in t["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join(
f"[{n}] {d['title']} ({d['source']})\n{d['body'][:2500]}" for n, d in enumerate(top, 1))
r = chat(SYS_D, user, 2500, think=True) or {}
# Map 1-based prompt doc number -> docs item index "i"; None if invalid.
ref = lambda n: top[n - 1]["i"] if isinstance(n, int) and 1 <= n <= len(top) else None
# Normalize LLM items to {text, doc}; drop empty ones.
fix = lambda l: [{"text": str(x["text"]), "doc": ref(x.get("doc"))} for x in l if isinstance(x, dict) and x.get("text")]
s = fix(r.get("summary") or [])
# Replace the summary only if the LLM returned something.
if s: t["summary"] = s
# from_docs: max 3, and only entries that cite a valid doc.
t["from_docs"] = [x for x in fix(r.get("from_docs") or [])[:3] if x["doc"] is not None]
def run(name, window_words=3000):
# Pipeline: (1) gather inputs, (2) build a timeline, (3) LLM topic extraction per chunk,
# (4) tidy topics, (5) docs pass + overview, (6) attach shots, (7) references, (8) write report.json and topics.
rec = db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
tx = _transcript(name)
# Duration from the recordings table, else last transcript timestamp + 5 s.
dur = (rec and rec[0]) or (tx[-1][0] + 5 if tx else 0)
shots = _load(name, "shots.json", []); glossary = _load(name, "glossary.json", [])
crop_ok = any((s.get("view") or "").startswith("view_") for s in shots) # when crops exist, frames without one show no shared content
# A shot is usable if its kind is a content kind and, when crops exist, it has a view_* crop.
usable = lambda s: s["kind"] in CONTENT_KINDS and (not crop_ok or (s.get("view") or "").startswith("view_"))
# Meeting event stream: meta, presence, share, chat, raised hand.
evs = db.events(name, "meta", "present", "share_start", "share_stop", "chat", "hand")
names = db.speaker_names(name)
meta = [json.loads(e["text"]) for e in evs if e["kind"] == "meta" and e["who_key"] != "video"] # Teams topic only; else LLM title from transcript
title = (meta[-1].get("title") or "") if meta else ""
# Share spans per presenter.
shares = _shares(evs, dur)
# att: attendee presence spans; src: sources that reported presence; counts: mentions per name (for canonicalization).
att, src, counts = {}, set(), {}
for e in evs:
if e["kind"] != "present": continue
@@ -226,91 +276,125 @@ def run(name, window_words=3000):
a["last_t"] = max(a["last_t"], e["t"])
src.add("video" if e["who_key"] == "video" else "teams")
counts[p["who"]] = counts.get(p["who"], 0) + 1
# "teams" if any Teams presence was seen, "video" if only video-frame names, else "none".
attendees_source = "teams" if "teams" in src else "video" if src else "none"
# Presenters read from shots count as mentions too.
for s in shots:
if s.get("presenter"): n = db.norm_name(s["presenter"]); counts[n] = counts.get(n, 0) + 1
# Sharers count as mentions too.
for s in shares: counts[s["who"]] = counts.get(s["who"], 0) + 1
# Known spellings: people from earlier docs.json plus Teams presence names.
known = list(dict.fromkeys(_load(name, "docs.json", {"people": []}).get("people", []) +
[p["who"] for e in evs if e["kind"] == "present" and e["who_key"] != "video" for p in json.loads(e["text"] or "[]")]))
# Canonical spelling per raw name; video-sourced names need at least 2 mentions.
cmap = canon(counts, known, video=attendees_source == "video")
# Apply the canonical map to attendees and shares.
att, shares = _canon_att(att, cmap), _canon_shares(shares, cmap)
# Chat messages for the report.
chats = [{"t": e["t"], "who": e["who"], "text": e["text"]} for e in evs if e["kind"] == "chat"]
# timeline items: (t, line)
items = [(t, f"[{mmss(t)}] " + (f"{names.get(sp, sp)}: " if sp else "") + x, len(x.split())) for t, sp, x in tx]
prev_text = None
for s in filter(usable, shots):
# Who was sharing at this frame's time, if anyone.
sh = next((x["who"] for x in shares if x["start"] <= s["t"] < x["end"]), None)
l = f"[{mmss(s['t'])}] [SCHERMO {s['kind']}{', condiviso da ' + sh if sh else ''}] {s.get('title') or ''}: {s.get('summary') or ''}"
# Include OCR text only when it differs from the previous frame; cap at 600 chars.
if s.get("text") and s["text"] != prev_text: l += "\n testo: " + s["text"].replace("\n", " / ")[:600]
prev_text = s.get("text"); items.append((s["t"], l, len(l.split())))
items += [(c["t"], f"[{mmss(c['t'])}] [CHAT] {c['who']}: {c['text']}", 0) for c in chats]
items += [(e["t"], f"[{mmss(e['t'])}] [MANO ALZATA] {e['who']}", 0) for e in evs if e["kind"] == "hand"]
items.sort(key=lambda x: x[0])
# Progress counter shared with _tick: [name, done, expected].
global PROG
# Split the timeline into chunks of about window_words words.
n_chunks = max(1, -(-sum(w for _, _, w in items) // window_words))
PROG = [name, 0, n_chunks + 3 * n_chunks + 1] # chunks + ~3 topics per chunk (docs pass) + overview
db.tick(name, 0, PROG[2], f"argomenti: blocco 1 di {n_chunks}")
# System prompt + glossary (or "nessuno").
system = SYS_A + (", ".join(glossary) or "nessuno")
topics, buf, words, wstart = [], [], 0, 0
# Send the buffered chunk to the LLM and append its topics.
def flush(end):
nonlocal buf, words
if not buf: return
d = chat(system, "\n".join(buf), 4000, think=True); _tick(f"argomenti: blocco {PROG[1] + 1} di {n_chunks} fatto")
ts = d.get("topics") if d else None
if not ts:
# Placeholder topic when the LLM returns nothing, so the time range is not lost.
ts = [{"title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"]}]
for t in ts:
t = {"title": str(t.get("title") or "Argomento"), "summary": list(t.get("summary") or []), "shown": list(t.get("shown") or []),
"decisions": _clean(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": _clean(t.get("open_questions") or []),
"start_s": secs(t.get("start")), "end_s": secs(t.get("end"))}
# Clamp end time into [start + 1 s, recording duration].
t["end_s"] = min(max(t["end_s"], t["start_s"] + 1), max(dur, t["start_s"] + 1))
topics.append(t)
buf, words = [], 0
# Group timeline items into chunks of ~window_words words, flushing at each boundary.
for t, l, w in items:
if not buf: wstart = t
buf.append(l); words += w
if words >= window_words: flush(t)
# Flush the last chunk.
flush(items[-1][0] if items else 0)
# Sort/merge/clamp topics (see _tidy).
topics = _tidy(topics, dur)
for t in topics:
# Action owners labelled "Speaker N" without a known name are blanked.
for a in t["actions"]:
if re.fullmatch(r"Speaker \d+", str(a.get("who", ""))) and a["who"] not in names: a["who"] = ""
# Candidate docs from docs.json (empty if no docs pass ran).
docs = _load(name, "docs.json", {"items": [], "people": []})["items"]
# Expected progress: the docs pass costs one tick per topic (when docs exist), plus the overview.
PROG[2] = PROG[1] + (len(topics) if docs else 0) + 1
for t in topics:
# Summaries become {text, doc} dicts; doc is filled in by the docs pass.
t["summary"] = [{"text": str(s), "doc": None} for s in t["summary"]]
t["from_docs"] = []
if docs: _pass_d(t, docs); _tick(f"documentazione per «{t['title'][:50]}»")
# Overview pass: title and TL;DR from the topics.
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800, think=True) or {}; _tick("fine")
tldr = [str(x) for x in (ov.get("tldr") or [])][:5]
# Manual title wins; otherwise the LLM title.
title = title or str(ov.get("title") or "").strip()
# Shots to attach: lead frames with usable content and at least 40 chars of OCR text.
good = [s for s in shots if s.get("lead") and usable(s) and len(s.get("text") or "") >= 40]
# Reset each topic's shot list.
for t in topics: t["shots"] = []
for s in good:
if not topics: break
# Topic containing the shot's time; else the topic with the nearest start.
tp = next((t for t in topics if t["start_s"] <= s["t"] <= t["end_s"]), None) or min(topics, key=lambda t: abs(t["start_s"] - s["t"]))
tp["shots"].append(s)
for t in topics:
# Keep the two shots with the most OCR text, then restore time order.
best = sorted(t["shots"], key=lambda s: -len(s.get("text") or ""))[:2]
t["shots"] = sorted(best, key=lambda s: s["t"])
# Entities from usable shots (urls/emails/numbers/systems) and ticket keys from speech.
cshots = [s for s in shots if usable(s)]
refs = {"tickets": {}, "urls": {}, "systems": {}, "emails": {}, "numbers": {}}
sysn = {}
# Collect entities from each usable shot.
for s in cshots:
e = s.get("entities") or {}
for k in ("urls", "emails", "numbers"):
for v in e.get(k, []): refs[k].setdefault(v, s["t"])
# System names keyed by lowercase; remember which frames show them.
for v in e.get("systems", []): sysn.setdefault(v.lower(), (v, set()))[1].add(s["file"])
# Lowercased transcript for substring checks.
alltx = " ".join(x for _, _, x in tx).lower()
# Keep systems seen in >= 2 frames or mentioned in speech; first time wins; names under 3 chars dropped.
for low, (v, files) in sysn.items():
if len(v) >= 3 and (len(files) >= 2 or low in alltx):
refs["systems"][v] = min(s["t"] for s in cshots if s["file"] in files)
# Ticket keys mentioned in speech, with first timestamp.
for t, _, x in tx:
for k in TICKET.findall(x): refs["tickets"].setdefault(k, t)
references = {"tickets": [{"key": k, "first_t": t} for k, t in refs["tickets"].items()],
@@ -318,16 +402,19 @@ def run(name, window_words=3000):
"systems": [{"name": k, "first_t": t} for k, t in refs["systems"].items()],
"emails": [{"email": k, "first_t": t} for k, t in refs["emails"].items()],
"numbers": [{"value": k, "t": t} for k, t in refs["numbers"].items()]}
# Screen timeline: usable lead frames; consecutive frames with the same title are merged.
screen = []
for s in shots:
if not s.get("lead") or not usable(s): continue
r = {k: s.get(k) for k in ("t", "t_end", "kind", "title", "summary")}
if screen and (screen[-1]["title"] or "").lower() == (r["title"] or "").lower(): screen[-1]["t_end"] = r["t_end"]
else: screen.append(r)
# Parse date/time from the recording name (teams_/meet_ YYYY-MM-DDTHH-MM-SS).
m = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name)
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": _manual_title(name) or title,
"tldr": tldr, "attendees": list(att.values()), "attendees_source": attendees_source, "known_spelling": bool(known),
"name_map": cmap, "shares": shares, "chat": chats, "references": references, "screen": screen, "topics": topics}
# report.json is what render() reads; topics also go to the DB table.
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_topics(name, topics)
@@ -344,9 +431,12 @@ def retitle(name):
p.write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
# Topic heading "N. title (start–end)"; slugified for anchors in render().
def _head(i, t): return f"{i}. {t['title']} ({mmss(t['start_s'])}–{mmss(t['end_s'])})"
# Apply the speaker-name map to every string in the report; unmapped "Speaker N" becomes "un partecipante".
# Returns (report, label -> name map).
def named(name, rep):
nm = rep.get("name_map", {})
names = {l: nm.get(p, p) for l, p in db.speaker_names(name).items()}
@@ -354,6 +444,7 @@ def named(name, rep):
# Render report.md and report.html from report.json (plus docs.json and diarization segments).
def render(name):
import markdown
from markdown.extensions.toc import slugify
@@ -362,17 +453,22 @@ def render(name):
docs = _load(name, "docs.json", None)
items = {x["i"]: x for x in (docs or {}).get("items", [])}
rep, names = named(name, rep)
# Diarization segments (label, start, end) for talk time.
segs = _load(name, "diar_segments.json", [])
# Turn ticket keys into Jira links.
link = lambda s: TICKET.sub(lambda m: f"[{m[0]}]({JIRA_BROWSE}/{m[0]})", s)
# Strip brackets and quotes so text fits in Markdown link text/titles.
q = lambda s: re.sub(r'[\[\]"]', "", s or "")
md = [f"# {rep['meeting_title'] or 'Riunione'} — {rep['date']}", "", f"**Durata:** {int(rep['duration_s'] // 60)} min", "", "## In breve", ""]
md += [f"- {x}" for x in rep["tldr"]] + [""]
# participants
# Talk time per named speaker, summed from diarization segments.
talk = {}
for s in segs:
p = names.get(s["label"])
if p: talk[p] = talk.get(p, 0) + s["end"] - s["start"]
# Video-sourced attendance: names read from frames only, no presence times.
video = rep["attendees_source"] == "video"
if video:
people = sorted({a["who"] for a in rep["attendees"]})
@@ -382,29 +478,35 @@ def render(name):
md += ["*Nomi letti dai fotogrammi (ortografia verificata sulla documentazione): verificare.*" if rep.get("known_spelling") else "*Nomi letti dai fotogrammi: verificare.*", "", ", ".join(people), ""]
else:
rows = {p: [v, None] for p, v in talk.items()}
# Teams-sourced: join talk time with presence windows by name (case-insensitive).
for a in rep["attendees"]:
k = next((p for p in rows if p.lower() == a["who"].lower()), a["who"])
rows.setdefault(k, [0, None])[1] = f"{mmss(a['first_t'])}–{mmss(a['last_t'])}"
if rows:
md += ["## Partecipanti", "", "| Partecipante | Parlato | Presente |", "|---|---|---|"]
md += [f"| {p} | {f'{int(v[0] // 60)} min' if v[0] else '—'} | {v[1] or '—'} |" for p, v in rows.items()] + [""]
# Screen-share spans.
if rep["shares"]:
md += ["## Condivisioni schermo", ""] + [f"- {mmss(s['start'])}–{mmss(s['end'])} {s['who']}" for s in rep["shares"]] + [""]
heads = []
# Topic index with anchor links to the sections below.
md += ["## Argomenti", ""]
for i, t in enumerate(rep["topics"], 1):
h = _head(i, t)
heads.append(h)
md.append(f"{i}. [{t['title']}](#{slugify(h, '-')})")
md.append("")
# Summary bullet; add a 📄 link when the cited doc is in items.
def cite(x):
x = x if isinstance(x, dict) else {"text": x, "doc": None}
c = f' [📄]({items[x["doc"]]["url"]} "{q(items[x["doc"]]["title"])}")' if x.get("doc") in items else ""
return f"- {x['text']}{c}"
for h, t in zip(heads, rep["topics"]):
md += [f"## {h}", "", "### Sintesi", ""] + [cite(x) for x in t["summary"]] + [""]
# Only doc facts whose doc is present in items.
fd = [x for x in t.get("from_docs", []) if x.get("doc") in items]
if fd: md += ["### Dalla documentazione", ""] + [f"- 📄 {x['text']} — [{q(items[x['doc']]['title'])}]({items[x['doc']]['url']})" for x in fd] + [""]
# Previous-meeting references, linked to the GUI report anchors.
pv = t.get("previous") or []
if pv: md += ["### Dalle riunioni precedenti", ""] + [f"- **{x['status']}** — {x['text']} — [{q(x.get('meeting') or x['name'])} {x['date']}, {q(x['topic'])} {mmss(x['t'])}]({GUI}/report?name={x['name']}#{x['anchor']})" for x in pv] + [""]
if t["shown"]: md += ["### Mostrato a schermo", ""] + [f"- {link(x)}" for x in t["shown"]] + [""]
@@ -413,11 +515,13 @@ def render(name):
if t["actions"]:
md += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"]
md += [f"| {a.get('who', '')} | {a.get('what', '')} | {a.get('when', '')} |" for a in t["actions"]] + [""]
# Embed shots: crop view if present, else the full frame; caption has time, sharer, summary.
for s in t["shots"]:
alt = re.sub(r"[\[\]()]", "", s.get("title") or "")
sh = next((x["who"] for x in rep["shares"] if x["start"] <= s["t"] < x["end"]), None)
cap = f"{mmss(s['t'])} — " + (f"condiviso da {sh} — " if sh else "") + f"{s.get('title') or ''} — {s.get('summary') or ''}"
md += [f"![{alt}](shots/{s.get('view') or s['file']})", "", f"*{cap}*", ""]
# Related docs section (items from docs.json).
if items:
md += ["## Documentazione correlata", ""]
for x in items.values():
@@ -427,6 +531,7 @@ def render(name):
if rep["chat"]:
md += ["## Chat", ""] + [f"[{mmss(c['t'])}] **{c['who']}:** {c['text']} " for c in rep["chat"]] + [""]
r = rep["references"]
# Tickets: from docs when docs.json exists (only those mentioned in the meeting), else transcript references.
tk = ([f"[{x['key']}]({x['url']}) — {q(x['title'])}" for x in items.values() if x["source"] == "jira" and x.get("mentioned")] if docs is not None
else [f"[{x['key']}]({JIRA_BROWSE}/{x['key']}) — {mmss(x['first_t'])}" for x in r["tickets"]])
sy = [f"{x['name']} — {mmss(x['first_t'])}" for x in r["systems"]]
@@ -434,6 +539,7 @@ def render(name):
md += ["## Riferimenti", ""]
for k, v in (("Ticket", tk), ("Sistemi", sy)):
if v: md += [f"**{k}**", ""] + [f"- {x}" for x in v] + [""]
# Collapsible screen timeline; table cells escape "|" and newlines.
if rep["screen"]:
md += [f'<details markdown="1"><summary>Cronologia schermo ({len(rep["screen"])} schermate)</summary>', "",
"## Cronologia schermo", "", "| Da | A | Tipo | Titolo | Sintesi |", "|---|---|---|---|---|"]
@@ -442,9 +548,13 @@ def render(name):
md += ["", "</details>", ""]
text = "\n".join(md)
(d / "report.md").write_text(text, encoding="utf-8")
# Markdown -> HTML (tables, toc, raw HTML blocks).
body = markdown.markdown(text, extensions=["tables", "toc", "md_in_html"])
# Inline shot images as base64 so the HTML is self-contained.
body = re.sub(r'src="shots/([^"]+)"', lambda m: 'src="data:image/jpeg;base64,' + base64.b64encode((d / "shots" / m[1]).read_bytes()).decode() + '"', body)
# Plain title from the first heading line.
h1 = re.sub(r"[#]+ ", "", md[0])
# Inline CSS: light theme; dark theme via prefers-color-scheme.
css = """:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442}
@media screen and (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757}}
*{box-sizing:border-box}body{max-width:860px;margin:auto;padding:56px 24px 96px;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif}
@@ -460,4 +570,5 @@ td,th{padding:9px 14px;border-bottom:1px solid var(--line);text-align:left;verti
img{width:100%;border:1px solid var(--line);border-radius:12px;margin-top:.8em}p>em{color:var(--mut);font-size:.88em}
details{margin-top:2.4em;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 18px}summary{cursor:pointer;color:var(--acc);font-weight:500}
code{background:var(--soft);border-radius:5px;padding:.1em .35em;font-size:.9em}"""
# Write a single self-contained HTML document (CSS inline, images base64).
(d / "report.html").write_text(f'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{h1}</title><style>{css}</style>\n{body}', encoding="utf-8")
+31
View File
@@ -4,29 +4,37 @@
"""Quality gate for meeting reports. uv run --script review.py <name> [<name>...]; exit 1 if any fails. No network/LLM."""
import base64, json, re, struct, sys
import db
# Shared helpers from report.py: ticket regex, key normaliser, name similarity.
from report import TICKET, _key, _sim
from shots import CONTENT_KINDS
# Stopwords used by english() to tell English from Italian text.
ENG = {"the", "and", "of", "with", "is", "shows", "showing", "screenshot", "meeting", "displays"}
ITA = {"il", "la", "di", "che", "con", "della", "viene", "mostra", "sono", "per"}
# True if text is mostly English: at least 3 English stopwords and more than Italian ones.
def english(s):
w = re.findall(r"[a-zà-ú]+", str(s).lower())
e, i = sum(x in ENG for x in w), sum(x in ITA for x in w)
return e >= 3 and e > i
# Read image width from the JPEG SOF marker (0 if not found).
def jpeg_w(p):
b = p.read_bytes(); i = 2
while i < len(b):
# Skip non-marker bytes.
if b[i] != 0xFF: i += 1; continue
m = b[i + 1]
# SOF0-SOF2: frame header holds height, then width (2 bytes each).
if m in (0xC0, 0xC1, 0xC2): return struct.unpack(">H", b[i + 7:i + 9])[0]
# Jump over this segment using its length field.
i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
return 0
# Run all quality rules on one meeting's outputs; print failures; True if none.
def review(name):
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
@@ -36,31 +44,41 @@ def review(name):
docs = json.loads((d / "docs.json").read_text(encoding="utf-8")) if (d / "docs.json").exists() else None
items = (docs or {}).get("items", [])
fails = []
# Record a failure with its rule code (R1-R12).
F = lambda code, detail: fails.append(f"FAIL {code} {str(detail)[:200]}")
# R1: no generic 'Speaker N' labels left in the report.
for m in re.finditer(r"\bSpeaker \d+\b", md): F("R1", md[max(0, m.start() - 40):m.end() + 40].replace("\n", " "))
# R2: topic count between dur/900 and dur/150 (min 3 / 4), so long calls get more topics.
T, dur = rep["topics"], rep["duration_s"]
if not max(3, dur / 900) <= len(T) <= max(4, dur / 150): F("R2", f"{len(T)} topics for {dur / 60:.0f} min")
# R2: every topic except the last must span at least 2 min.
for t in T[:-1]:
if t["end_s"] - t["start_s"] < 120: F("R2", f"short topic {t['title']} {t['end_s'] - t['start_s']}s")
for t in T:
for x in t["shown"]:
# R3: each shown timestamp must fall inside the topic span (+/-30 s).
m = re.search(r"(\d\d):(\d\d)", x)
if not m or not t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30: F("R3", f"{t['title']}: {x}")
byfile = {}
# Index shots by file name and by cropped view name, for R4.
for s in shots: byfile[s["file"]] = byfile[s.get("view") or s["file"]] = s
# R4: at most 2 images per section.
for sec in re.split(r"\n(?=## )", md):
imgs = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", sec)
if len(imgs) > 2: F("R4", f">2 images in {sec[:40]!r}")
# R4: every image used must be a content screen (CONTENT_KINDS).
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", md)
for f in used:
if byfile.get(f, {}).get("kind") not in CONTENT_KINDS: F("R4", f"{f} kind {byfile.get(f, {}).get('kind')}")
# R4: if cropping was applied, every image must be a cropped view_ file.
if any((s.get("view") or "").startswith("view_") for s in shots):
for f in used:
if not f.startswith("view_"): F("R4", f"uncropped image {f}")
# R5: collect all prose fields to check for English.
texts = list(rep["tldr"])
for t in T:
texts += [x["text"] if isinstance(x, dict) else x for x in t["summary"]] + [x["text"] for x in t.get("from_docs", [])]
@@ -68,6 +86,7 @@ def review(name):
for x in texts:
if english(x): F("R5", x)
# R6: read the participants section (table rows or comma list).
sec = re.search(r"## Partecipanti\n(.*?)(?=\n## )", md, re.S)
people = []
for l in (sec[1].splitlines() if sec else []):
@@ -75,36 +94,48 @@ def review(name):
c = l.split("|")[1].strip()
if c not in ("Partecipante", "") and not c.startswith("-"): people.append(c)
elif l.strip() and not l.startswith("*"): people += [x.strip() for x in l.split(",")]
# R6: no initials or truncated names.
for p in people:
if re.fullmatch(r"[A-Z]{1,3}", p) or "..." in p or "…" in p: F("R6", f"initials/truncated {p}")
# R6: no two participants that look like the same person (similarity >= 0.82).
for i, a in enumerate(people):
for b in people[i + 1:]:
if _sim(a, b) >= 0.82: F("R6", f"{a} ~ {b}")
# R7: share segments must be >= 20 s and not split by a gap of <= 60 s.
S = rep["shares"]
for s in S:
if s["end"] - s["start"] < 20: F("R7", f"short share {s}")
for a, b in zip(S, S[1:]):
if a["who"] == b["who"] and b["start"] - a["end"] <= 60: F("R7", f"mergeable {a['who']} {a['end']}->{b['start']}")
# R8: ticket keys from the report's Ticket section.
rs = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", md, re.S)
# R8: allowed keys: Jira-verified when docs ran, else keys from references.
ok = ({x["key"] for x in items if x["source"] == "jira" and x.get("mentioned")} if docs is not None
else {x["key"] for x in rep["references"]["tickets"]})
for k in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", rs[1] if rs else ""):
if k not in ok: F("R8", f"ticket {k}")
# R8: no raw number or e-mail lists.
if "Numeri a schermo" in md or "**Email**" in md: F("R8", "numbers/email lists present")
# R9: docs section must exist and citation links must point to fetched docs.
if items:
if "## Documentazione correlata" not in md: F("R9", "missing Documentazione correlata")
urls = {x["url"] for x in items}
# Citation icon links in the markdown.
for u in re.findall(r"\[📄\]\(([^ )]+)", md):
if u not in urls: F("R9", f"citation url not in docs {u}")
# R10: HTML must embed images, not reference shots/ paths.
if 'src="shots/' in html: F("R10", "unembedded image")
for b in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html):
# R10: an embedded image under 5000 bytes is a placeholder.
if len(base64.b64decode(b)) <= 5000: F("R10", "tiny image")
# R11: transcript must not be included in the report.
if "## Trascrizione" in md: F("R11", "transcript present")
for f in set(used):
# R12: cropped views must be at least 600 px wide.
if f.startswith("view_") and jpeg_w(d / "shots" / f) < 600: F("R12", f"{f} narrow {jpeg_w(d / 'shots' / f)}px")
print("\n".join(f"[{name}] {x}" for x in fails))
+126
View File
@@ -12,34 +12,48 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse, parse_qs
import threading
# Sibling modules: db (SQLite, paths), llama (model servers), memory (Q&A).
import db, llama, memory
# CLI: the GUI/extension port.
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=18765)
a = ap.parse_args()
# app/ folder: flow.py, ui/, and the modules live here.
HERE = Path(__file__).parent
# Meeting folders root; created at startup.
out = db.OUT; out.mkdir(exist_ok=True)
# Process-wide state shared by request threads and the queue runner.
R = {} # 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 = {k: v for k, v in os.environ.items() if k 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):
d = out / name; html = d / "report.html"; pdf = d / "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:
tmp = d / "_print.html"
# Print copy: expand <details>, add print CSS; original report untouched.
tmp.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:
@@ -56,7 +70,9 @@ def ask_once(q):
with LOCK:
own = []
try:
# Embed (CPU) and chat LLM start first; both are stopped in finally.
own = [p for p in (llama.start_embed(log=db.GLOBAL / "embed.log"), llama.start(vision=False, log=db.GLOBAL / "llama.log")) if p is not None]
# Answer with the running models.
return memory.ask(q)
finally:
for p in own: p.terminate()
@@ -85,11 +101,14 @@ def pump():
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"), 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 r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name"):
@@ -97,11 +116,13 @@ def run_all(start_from):
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)
@@ -109,11 +130,14 @@ def start_prefect():
cwd=HERE, env=ENV, stdout=open(db.GLOBAL / "prefect.log", "ab"), 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():
c = db.connect()
have = {r[0] for r in c.execute("SELECT name FROM recordings")}
# Register meetings with media on disk that the DB lacks.
for p in sorted(out.glob("*/source.*")):
n = p.parent.name
# Skip rows already known, unsupported extensions, and .webm still growing (mtime < 60 s).
if n in have or p.suffix.lower() not in UPLOAD_EXT or (p.suffix == ".webm" and time.time() - p.stat().st_mtime < 60): continue
db.upsert_recording(n, source="ext" if n.startswith("teams_") else "meet",
status="done" if (p.parent / "report.html").exists() else "queued", bytes=p.stat().st_size)
@@ -134,6 +158,7 @@ def title(n):
return TITLES[n][1]
# True while a run is queued or a flow process is alive (GPU in use).
def busy(): return bool(QUEUE) or any(p.poll() is None for p 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
@@ -153,12 +178,15 @@ def set_title(name, t):
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.
r = 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(l.split()[0]): l for l in r.stdout.splitlines() if "flow.py" in l and (name is None or f" {name} " in l + " ")}
def prefect_state(run_id, typ, msg):
# Prefect REST: force-set state on a flow run.
body = json.dumps({"state": {"type": typ, "name": typ.title(), "message": msg}, "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 e: print("prefect set_state failed:", e, flush=True)
@@ -166,9 +194,11 @@ def prefect_state(run_id, typ, msg):
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[:] = [q for q in QUEUE if q[0] != name]
j = JOBS.get(name)
pids = {j.pid} if j and j.poll() is None else set()
# /T kills children (uv -> python -> llama-server), /F forces it.
for pid in pids | set(flow_pids(name)): subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True)
r = db.connect().execute("SELECT flow_run_id FROM recordings WHERE name=?", (name,)).fetchone()
if r and r[0]: prefect_state(r[0], "CANCELLED", reason)
@@ -180,7 +210,9 @@ def drop_video(name):
"""Delete only the video/source file after the report: audio.opus, transcript, shots, report stay. Returns (MB freed, error)."""
r = db.connect().execute("SELECT status FROM recordings WHERE name=?", (name,)).fetchone()
j = JOBS.get(name)
# Only a finished report with no active run can drop its video.
if not r or r["status"] != "done" or name in R or (j and j.poll() is None) or any(q[0] == name for q 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 / name / "audio.opus").exists(): return 0, "manca audio.opus: video non eliminato"
fs = list((out / name).glob("source.*"))
if not fs: return 0, "nessun file sorgente"
@@ -195,23 +227,30 @@ def merge(names):
c = db.connect()
rows = [c.execute("SELECT name, started_at, ended_at, chunks, bytes, status FROM recordings WHERE name=?", (n,)).fetchone() for n 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(r["status"] == "recording" or r["name"] in R or r["name"] in JOBS and JOBS[r["name"]].poll() is None for r in rows): return None, "ferma prima le registrazioni in corso"
# Chronological order by start time.
rows.sort(key=lambda r: r["started_at"] or "")
files = [db.media(r["name"])[1] for r in rows]
if not all(f and f.suffix == ".webm" for f in files): return None, "solo registrazioni .webm"
# Merged name derived from the earliest part.
merged = rows[0]["name"] + "_merged"
if c.execute("SELECT 1 FROM recordings WHERE name=?", (merged,)).fetchone(): return None, "unione già esistente"
dst = db.out_dir(merged) / "source.webm"
# Concat list for ffmpeg; removed after the run.
lst = dst.with_name("concat.txt")
lst.write_text("".join(f"file '{f.as_posix()}'\n" for f in files), encoding="utf-8")
# Stream copy via concat demuxer: no re-encode; parts must share codecs.
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(dst)], capture_output=True, text=True)
lst.unlink(missing_ok=True)
if r.returncode: return None, r.stderr[-300:]
# Start offset of each part in the merged file (cumulative durations).
offs, o = [], 0.0
for f in files: offs.append(o); o += db.duration(f)
db.upsert_recording(merged, source="ext", started_at=rows[0]["started_at"], ended_at=rows[-1]["ended_at"], chunks=sum(r["chunks"] or 0 for r in rows),
bytes=dst.stat().st_size, duration_s=o, status="queued")
for r, off in zip(rows, offs):
# Copy each part's call events, shifted by its offset.
c.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, off, r["name"]))
launch(merged, "audio")
return merged, None
@@ -220,15 +259,19 @@ def merge(names):
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 = {r[1]: r[0] for r in db.connect().execute("SELECT name, flow_run_id FROM recordings WHERE flow_run_id IS NOT NULL")}
live = flow_pids()
for fr in runs:
name = by_id.get(fr["id"])
# Cancel requested in Prefect: stop our process, or just mark it if we don't own it.
if fr["state_type"] == "CANCELLING":
if name: cancel(name, "cancelled from Prefect UI")
else: prefect_state(fr["id"], "CANCELLED", "cancelled from Prefect UI")
@@ -256,8 +299,10 @@ def _find(o, k):
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: s = 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).
s = s[0] if isinstance(s, list) and s else {}
return {k: _find(s, k) for k in ("is_processing", "n_prompt_tokens", "n_prompt_tokens_processed", "n_decoded")}
@@ -265,9 +310,12 @@ def slot():
def last_log(n):
"""Last meaningful line of out/<n>/logs/flow.log: what a started-but-not-yet-tracked run is doing (e.g. uv downloading deps)."""
f = out / n / "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(f, "rb") as fh: fh.seek(max(0, f.stat().st_size - 4096)); tail = fh.read().decode("utf-8", "replace")
except OSError: return ""
# Drop uv's UV_NATIVE_TLS noise so the real last line shows.
lines = [l.strip() for l in tail.splitlines() if l.strip() and "UV_NATIVE_TLS" not in l]
return lines[-1][-160:] if lines else ""
@@ -277,12 +325,14 @@ def prog(n, dur):
p = db.progress(n)
if not p or not p.get("step"): return None
now, mins = time.time(), (dur or 0) / 60
# Speed key: shots/report are tracked per model, others per step.
key = lambda s: f"{s}@{llama.current(s == 'shots')}" if s in ("shots", "report") else s
cur, el = p["step"], now - p["step_start"]
est = db.spm(p.get("key") or key(cur)) * mins
if p["total"] and p["done"]: # rate measured from the loop start (t0), not from the step start (model load etc.)
left, frac = (now - (p.get("t0") or p["step_start"])) / p["done"] * (p["total"] - p["done"]), p["done"] / p["total"]
else: left = max(est - el, 0.1 * est); frac = el / (el + left) if el + left else 0
# Resume point's position in the pipeline order; earlier steps show as skipped.
o = db.ORDER; i0 = o.index(p["start"]) if p["start"] in o else 0
took = {s: e - b for s, b, e in p["steps"]}
plan = []
@@ -291,6 +341,7 @@ def prog(n, dur):
elif s == cur: plan.append({"s": s, "state": "run", "frac": round(frac, 3), "left": round(left), "secs": round(el)})
elif s in took: plan.append({"s": s, "state": "done", "secs": round(took[s])})
else: plan.append({"s": s, "state": "todo", "est": round(db.spm(key(s)) * mins)})
# ETA: rest of current step plus estimates for steps still to run.
eta = left + sum(x.get("est", 0) for x in plan if x["state"] == "todo") if mins else None
tot = now - p["run_start"]
return {"step": cur, "note": p["note"], "done": p["done"], "total": p["total"], "frac": round(frac, 3), "step_left": round(left),
@@ -298,65 +349,89 @@ def prog(n, dur):
"idle": round(now - p["updated"]), "plan": plan, "llm": slot() if cur in ("shots", "docs", "report", "memory") else None}
# Snapshot polled by the GUI: recordings, queue, running jobs, LLM state.
def status():
t = time.time(); rs = []
for r in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"):
n = r["name"]; d = dict(r)
# Seconds since last chunk while still receiving; None otherwise.
d["receiving_age_s"] = round(t - R[n]["last"]) if n in R else None
# Only report.html is exposed; the GUI links to it.
d["files"] = ["report.html"] if (out / n / "report.html").exists() else []
j = JOBS.get(n); d["running"] = bool(j and j.poll() is None); d["title"] = title(n)
# Origin label stored in meta (upload filename or crop label).
d["upload"] = db.meta(n).get("upload")
# Progress only for running or pipeline-status rows.
d["prog"] = prog(n, d["duration_s"]) if d["running"] or d["status"] in db.ORDER else None
if d["running"] and not d["prog"]: d["boot"] = last_log(n)
# Source media size in MB (0 if dropped).
w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0
rs.append(d)
return {"now": t, "recs": rs, "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": [[[k, llama.label(k)] for k in llama.available(v)] for v in (True, False)]}
# FTS MATCH; on a query syntax error retry with the input as one quoted phrase.
def fts(sql, q):
c = db.connect()
try: return c.execute(sql, (q,)).fetchall()
# Fallback: FTS operators in user input become a literal quoted phrase.
except sqlite3.OperationalError: return c.execute(sql, ('"' + q.replace('"', '""') + '"',)).fetchall()
# Full-text search over speech and screen text.
def search(q):
sp = []
# snippet(lines, col 3 = text, '[' ']' highlight, '…', 12 tokens).
for r in fts("SELECT name, t, speaker, snippet(lines, 3, '[', ']', '…', 12) FROM lines WHERE lines MATCH ? ORDER BY name DESC, t LIMIT 100", q):
sp.append([r[0], r[1], db.speaker_names(r[0]).get(r[2]) or r[2], r[3]])
sc = []
# shot_text: FTS over screen text; same snippet convention.
for r 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", q):
# Shot file for the matched frame; empty if none.
f = db.connect().execute("SELECT file FROM shots WHERE name=? AND t=?", (r[0], r[1])).fetchone()
sc.append([r[0], r[1], r[2], r[3], f[0] if f else ""])
return {"speech": sp, "screen": sc}
# Data for the speaker-naming UI: labels, names, talk time, samples, candidates.
def speakers_info(name):
c = db.connect()
# Saved speaker -> person mapping, if already confirmed.
rows = [dict(r) for r in c.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": r[0], "person": "", "source": "", "overlap_s": None} for r in c.execute("SELECT DISTINCT speaker FROM lines WHERE name=? AND speaker IS NOT NULL ORDER BY speaker", (name,))]
# Diarization segments (optional file) give talk time.
p = out / name / "diar_segments.json"
talk = {}
# Talk time per diarized label, summed over segments.
for s in (json.loads(p.read_text(encoding="utf-8")) if p.exists() else []): talk[s["label"]] = talk.get(s["label"], 0) + s["end"] - s["start"]
for r in rows:
r["talk_s"] = round(talk.get(r["label"], 0))
# Up to 3 longest lines as examples for naming the speaker.
r["samples"] = [x[0][:160] for x in c.execute("SELECT text FROM lines WHERE name=? AND speaker=? ORDER BY length(text) DESC LIMIT 3", (name, r["label"]))]
rows.sort(key=lambda r: (len(r["label"]), r["label"]))
# Speakers seen in active/caption events are candidate names.
cand = sorted({r["who"] for r in db.events(name, "active", "caption") if r["who"]})
# Presence events carry the participant list as JSON in text.
for e in db.events(name, "present"):
cand += [p["who"] for p in json.loads(e["text"] or "[]")]
dp = out / name / "docs.json"
# docs.json (LLM-extracted people) also feeds candidate names.
if dp.exists(): cand += json.loads(dp.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 e in items[:10000]:
try:
t, k, wk, w, x = e["t"], e["kind"], e.get("who_key", ""), e.get("who", ""), e.get("text", "")
except (KeyError, TypeError, AttributeError): continue
# Accept only well-formed events: known kind, bounded sizes, non-negative time.
if (isinstance(t, (int, float)) and not isinstance(t, bool) and t >= 0 and k in db.EVENT_KINDS
and isinstance(wk, str) and isinstance(w, str) and isinstance(x, str)
and len(wk) <= 200 and len(w) <= 200 and len(x) <= 4000):
@@ -367,7 +442,9 @@ def add_events(name, items):
UI = {"/": ("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 H(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", "*")
@@ -379,57 +456,73 @@ class H(BaseHTTPRequestHandler):
def _json(self, o): self._send(json.dumps(o, 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/.
u = urlparse(self.path); q = {k: v[0] for k, v in parse_qs(u.query).items()}; name = Path(q.get("name", "x")).name
# UI files read per request: edits show without restarting.
if u.path in UI: self._send((HERE / "ui" / UI[u.path][0]).read_bytes(), ctype=UI[u.path][1])
elif u.path == "/status": self._json(status())
elif u.path == "/report":
f = out / name / "report.html"
self._send(f.read_bytes(), ctype="text/html; charset=utf-8") if f.exists() else self._send(b"not found", 404)
elif u.path == "/shot":
# Basename only: the query cannot escape the shots folder.
f = out / name / "shots" / Path(q.get("file", "")).name
self._send(f.read_bytes(), ctype="image/jpeg") if f.is_file() else self._send(b"not found", 404)
elif u.path == "/video": self.video(name)
elif u.path == "/search": self._json(search(q.get("q", "")))
elif u.path == "/speakers": self._json(speakers_info(name))
elif u.path == "/pdf":
# PDF rendered on demand by headless Edge; failures return 500.
try: f = make_pdf(name)
except Exception as e: return self._send(f"errore: {e}".encode(), 500)
if f is None: self._send(b"not found", 404)
else: self._send(f.read_bytes(), ctype="application/pdf", headers=[("Content-Disposition", f'inline; filename="{name}.pdf"')])
elif u.path == "/ask":
if not q.get("q", "").strip(): return self._send("domanda vuota".encode(), 400)
# 409 while a pipeline needs the GPU; the caller retries later.
if ask_blocked(): return self._send("pipeline in corso: riprova dopo".encode(), 409)
try: self._json(ask_once(q["q"]))
except Exception as e: return self._send(f"errore: {e!r}".encode(), 503)
else: self._send(b"not found", 404)
# POST: ingestion (/chunk, /events, /upload), recording control, and actions.
def do_POST(self):
u = urlparse(self.path); q = {k: v[0] for k, v in parse_qs(u.query).items()}; name = Path(q.get("name", "x")).name
if u.path == "/upload": return self.upload(q)
# Read full body up front; /upload streams its own body instead.
data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if u.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 f: f.write(data)
if name not in R: db.upsert_recording(name, source="ext", started_at=now(), status="recording")
# Last chunk time: status uses it for receiving_age_s.
R.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 u.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 u.path == "/stop":
# Forget live-recording state so busy checks and crop guards clear.
R.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("in coda: apri http://127.0.0.1:18765/".encode())
elif u.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.
j = JOBS.get(name)
if (j and j.poll() is None) or name in R or any(x[0] == name for x in QUEUE): return self._send("in elaborazione o in registrazione: ferma prima".encode(), 409)
db.delete_recording(name); JOBS.pop(name, None); self._send()
elif u.path == "/crop": self.crop(name, q)
# Polled by the GUI during a crop; None when no crop is running.
elif u.path == "/crop_progress": self._json({"pct": CROP.get(name)})
elif u.path == "/cancel":
# Kill the flow tree; empty reply if something was killed.
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
elif u.path == "/merge":
m, err = merge([n for n in q.get("names", "").split(",") if n])
@@ -438,33 +531,41 @@ class H(BaseHTTPRequestHandler):
mb, err = drop_video(name)
self._send(f"{mb} MB liberati".encode() if not err else err.encode(), 200 if not err else 409)
elif u.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 u.path == "/run":
if not db.media(name)[0]:
return self._send("video eliminato: rielaborazione non possibile".encode(), 409)
# Re-run the flow from a step (default audio), with optional speaker count.
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 0))
self._send(b"" if ok else "già in coda o in esecuzione".encode(), 200 if ok else 409)
elif u.path == "/run_all":
f = q.get("from", "audio")
# Reject unknown resume points.
if f not in STEPS: return self._send(b"bad step", 400)
self._send(b"") if run_all(f) else self._send("rielaborazione già in corso".encode(), 409)
elif u.path == "/skip_shots":
f = db.GLOBAL / "skip_shots.txt"
# Flag file: while present the pipeline skips the shots step.
if q.get("v") == "1": f.write_text("1")
else: f.unlink(missing_ok=True)
self._send()
elif u.path == "/llm":
ks = [q.get("shots"), q.get("report")]
# Only models actually installed for the role are accepted.
if not (ks[0] in llama.available(True) and ks[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("pipeline in corso: cambia modello dopo".encode(), 409)
llama.choose(*ks); self._send()
elif u.path == "/speaker_map":
try: m = 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 m.items(): db.set_speaker_map(name, label, str(person).strip(), "manual")
if launch(name, "render"): self._send("salvato, render in coda".encode())
else: self._send("salvato, render dopo il job in corso".encode(), 202)
else: self._send(b"not found", 404)
# Serve meeting media to the player with HTTP Range (seeking).
def video(self, name):
a, v = db.media(name); f = v or a
if f and f.suffix == ".webm" and name not in R:
@@ -472,16 +573,20 @@ class H(BaseHTTPRequestHandler):
pv = f.with_name("preview.webm")
if not pv.exists() or pv.stat().st_mtime < f.stat().st_mtime:
t = pv.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(f), "-c", "copy", str(t)], capture_output=True).returncode == 0: t.replace(pv)
else: t.unlink(missing_ok=True)
if pv.exists(): f = pv
if not f: return self._send(b"not found", 404)
size = f.stat().st_size; lo, hi = 0, size - 1
# Parse single HTTP Range header (bytes=...); multi-range is not supported.
m = re.match(r"bytes=(\d*)-(\d*)$", self.headers.get("Range", ""))
if m and (m[1] or m[2]):
# "A-B" explicit range, "A-" open end, "-N" last N bytes.
if m[1]: lo = int(m[1]); hi = min(int(m[2]) if m[2] else hi, hi)
else: lo = max(0, size - int(m[2]))
else: m = None
# Start past end: 416 Range Not Satisfiable.
if lo > hi: return self._send(b"", 416, headers=[("Content-Range", f"bytes */{size}")])
self.send_response(206 if m else 200)
self.send_header("Content-Type", mimetypes.guess_type(f.name)[0] or "application/octet-stream")
@@ -491,45 +596,62 @@ class H(BaseHTTPRequestHandler):
try:
with open(f, "rb") as fh:
fh.seek(lo); left = hi - lo + 1
# 1 MiB pieces: large videos are never loaded whole.
while left and (b := fh.read(min(1 << 20, left))): self.wfile.write(b); left -= len(b)
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, q):
a, v = db.media(name); src = v or a
if not src: return self._send(b"not found", 404)
# Cutting a recording still being written would race with its appends.
if name in R: return self._send("registrazione in corso: ferma prima".encode(), 409)
# Times are seconds from the start of the media.
try: s, e = float(q["start"]), float(q["end"])
except (KeyError, ValueError): return self._send(b"bad times", 400)
if not 0 <= s < e: return self._send("intervallo non valido".encode(), 400)
inplace = q.get("inplace") == "1" # replace this meeting's source (and shift its call events) instead of creating a new meeting
j = JOBS.get(name)
if inplace and ((j and j.poll() is None) or any(x[0] == name for x in QUEUE)): return self._send("elaborazione in corso: ferma prima".encode(), 409)
# Inplace keeps the name; otherwise a new meet_<timestamp> meeting is made.
new = name if inplace else "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S"); ext = ".mp4" if v else ".m4a"
dst = db.out_dir(new) / f"source{ext}"; tmp = dst.with_name(f"source{ext}.part")
# Video: re-encode to even dimensions (yuv420p requires them). Audio-only: drop video.
enc = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"] if v else ["-vn"]
CROP[name] = 0
# -ss before -i: fast input seek; -t sets the cut length.
p = subprocess.Popen(["ffmpeg", "-y", "-v", "error", "-progress", "pipe:1", "-nostats", "-ss", str(s), "-t", str(e - s), "-i", str(src), *enc,
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-f", "mp4", str(tmp)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for ln in p.stdout:
# out_time_us is microseconds; /1e4 gives percent of the cut length.
if ln.startswith("out_time_us=") and ln[12:].strip().lstrip("-").isdigit(): CROP[name] = min(99, max(0, int(ln[12:]) / 1e4 / (e - s)))
# Wait for ffmpeg to exit and collect its stderr for error messages.
err = p.stderr.read(); p.wait(); CROP.pop(name, None)
# Stand-in with returncode/stderr so the checks below read like subprocess.run.
r = type("R", (), {"returncode": p.returncode, "stderr": err})
# Cleanup on failure: remove partial file, and the new folder if we created it.
fail = lambda msg: (tmp.unlink(missing_ok=True), None if inplace else dst.parent.rmdir(), self._send(msg.encode(), 500))
if r.returncode or not tmp.exists() or not tmp.stat().st_size: return fail(f"ffmpeg: {r.stderr[-300:]}")
# Unreadable result (db.duration raises): remove it and report.
try: dur = db.duration(tmp)
except ValueError as x: return fail(f"ritaglio non leggibile: {x}")
# Replace this meeting's media: drop old originals and preview so only the cut remains.
if inplace:
for f in (a, v, dst.with_name("preview.webm")):
if f and f != dst: f.unlink(missing_ok=True)
c = db.connect()
# Keep only events inside the cut, then shift them to the new t=0.
c.execute("DELETE FROM call_events WHERE name=? AND (t<? OR t>?)", (name, s, e))
c.execute("UPDATE call_events SET t=t-? WHERE name=?", (s, name))
# Atomic swap: the finished file appears only when complete.
tmp.replace(dst)
# In-place: same meeting, refreshed size/duration, back in the queue.
if inplace: db.upsert_recording(name, bytes=dst.stat().st_size, duration_s=dur, status="queued")
else:
db.set_meta(new, upload=f"{title(name) or name} [{int(s)}s-{int(e)}s]")
db.upsert_recording(new, source="upload", started_at=now(), status="queued", bytes=dst.stat().st_size, duration_s=dur)
launch(new, "audio")
self._json({"name": new, "duration_s": dur})
# Raw-body upload: whole file in the request body, saved as a new meeting, then queued.
def upload(self, q):
fn = Path(q.get("filename", "")).name; ext = Path(fn).suffix.lower(); n = int(self.headers.get("Content-Length", 0))
if ext not in UPLOAD_EXT: return self._send(f"formato non supportato: {ext or '?'} (usa {', '.join(sorted(UPLOAD_EXT))})".encode(), 400)
@@ -538,6 +660,7 @@ class H(BaseHTTPRequestHandler):
dst = db.out_dir(name) / f"source{ext}"; tmp = dst.with_name(f"source{ext}.part"); left = n
with open(tmp, "wb") as f:
while left and (b := self.rfile.read(min(1 << 20, left))): f.write(b); left -= len(b)
# Client aborted mid-upload: remove the partial file and its folder.
if left: tmp.unlink(missing_ok=True); dst.parent.rmdir(); return self._send("upload interrotto".encode(), 400)
tmp.replace(dst)
try: dur = db.duration(dst)
@@ -546,10 +669,13 @@ class H(BaseHTTPRequestHandler):
db.upsert_recording(name, source="upload", started_at=now(), status="queued", bytes=n, duration_s=dur)
launch(name, "audio")
self._json({"name": name, "duration_s": dur})
# Access logs are noisy; print them only with LOG_LEVEL=DEBUG.
def log_message(self, fmt, *x):
if os.environ.get("LOG_LEVEL", "INFO").upper() == "DEBUG": print(fmt % x, 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:{a.port}/", flush=True)
# Blocks for the life of the process.
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
+43
View File
@@ -2,10 +2,15 @@
import base64, collections, json, re, subprocess, urllib.error, urllib.request
import db, llama
# Fallback result when a frame can't be read: all schema keys present, neutral values.
EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None}
# Kinds whose content is worth summarising in the report (the rest are chat/video/other).
CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"}
# Crop frames to the model-reported shared-content box (see _view).
CROP_BOX = True
# Allowed values for 'kind'; also the grammar enum in SCHEMA.
KINDS = ["slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket", "chat", "video_tiles", "other"]
# Schema shorthands: _S bounded string, _N nullable string, _L bounded string list.
_S, _N, _L = {"type": "string", "maxLength": 300}, {"type": ["string", "null"], "maxLength": 200}, {"type": "array", "items": {"type": "string", "maxLength": 120}, "maxItems": 25}
# json_schema -> llama.cpp grammar: valid JSON + valid kind every time (small models broke JSON / looped to max_tokens)
SCHEMA = {"type": "object", "additionalProperties": False,
@@ -17,6 +22,7 @@ SCHEMA = {"type": "object", "additionalProperties": False,
"content_box": {"anyOf": [{"type": "array", "items": {"type": "integer"}, "minItems": 4, "maxItems": 4}, {"type": "null"}]}}}
# v3: v1's inline JSON template (the model never sees the grammar: v2 without it -> kind=video_tiles, title=null) + every field defined
# (v1 left title undefined), summary rules in Italian (v1 'ITALIAN' got echoed). Text before image: image-first measured worse.
# Italian/English VLM prompt. Field list mirrors SCHEMA; the rules stop invented values.
PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"' + '|'.join(KINDS) + '","title":str|null,"app":str|null,"summary":str,"text":str,'
'"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}\n'
'Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles and captions, except for people/presenter/meeting_title.\n'
@@ -30,36 +36,46 @@ PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON:
'- content_box: bounding box of the shared screen area (excluding Teams toolbar, video tiles, captions) in 0-1000 coordinates of this image; null if nothing is shared.\n'
'Never invent: use null or [] when absent.')
# Jira-style issue key, e.g. ABC-123 (2-10 char project prefix).
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
# http(s) URL; stops at whitespace, quotes or closing brackets.
URL = re.compile(r"""https?://[^\s)\]>"']+""")
# Simple e-mail address.
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
# Send one keyframe to the VLM. json_mode=False drops response_format for servers that reject it.
def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode()
body = {"max_tokens": 4000, "temperature": 0.1, # dense screens (mail/slides transcribed in "text") need ~2000 tok; 1200 truncated them -> empty cloud reply / bad JSON -> silent kind "other"
"chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]}
# Constrain output with the schema; plain json_object when no schema is set.
if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"}
return llama.content(llama.post(body, True, 900), f"shot {path.name}")
# Read one frame. Two tries on bad JSON; always returns a full dict (EMPTY on failure).
def read_shot(path):
json_mode = True
# Retry once: VLM replies are sometimes malformed.
for _ in range(2):
try:
try: t = _ask(path, json_mode)
except urllib.error.HTTPError as e:
if e.code != 400 or not json_mode: raise
json_mode = False; t = _ask(path, False)
# Drop reasoning blocks some models emit before the JSON.
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
# Keep only the outermost {...} in case of surrounding text.
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
if isinstance(d, dict): return {**EMPTY, **d}
except (ValueError, KeyError, IndexError): pass # IndexError: cloud returned empty "choices" (content filter / transient)
return dict(EMPTY)
# Deduplicate case-insensitively, keep order, drop empties.
def _dedupe(xs):
seen, out = set(), []
for x in xs:
@@ -68,6 +84,7 @@ def _dedupe(xs):
return out
# Merge regex-found tickets/URLs/e-mails into the model's entities; edits d in place.
def _augment(d):
ent = d.get("entities") if isinstance(d.get("entities"), dict) else {}
blob = f"{d.get('text') or ''} {d.get('summary') or ''}"
@@ -81,11 +98,14 @@ def _augment(d):
def _bars(video, dur):
"""ffmpeg crop filter trimming black side bars, or None. dur: seconds (webm has no container duration)."""
# Frame width, to check the crop is a real side-bar removal.
w = int(subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", str(video)],
capture_output=True, text=True).stdout.strip() or 0)
# cropdetect: black threshold 24, round 16 px, sampled at mid-video.
r = subprocess.run(["ffmpeg", "-ss", str(dur / 2), "-i", str(video), "-vf", "cropdetect=24:16:0", "-frames:v", "60", "-f", "null", "-"],
capture_output=True, text=True)
m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr)
# Reject if the detected width is under half the frame (not a side-bar case).
if not m or not w or int(m[-1][0]) < 0.5 * w: return None
return "crop=" + ":".join(m[-1])
@@ -93,11 +113,15 @@ def _bars(video, dur):
def _view(path, box):
"""Crop the shared content out of a keyframe; returns the file name to display."""
from PIL import Image
# Fall back to the full frame when no usable box was returned.
if not CROP_BOX or not isinstance(box, list) or len(box) != 4 or not all(isinstance(v, (int, float)) for v in box): return path.name
im = Image.open(path); W, H = im.size
# Model boxes are 0-1000 normalised; any value >1000 means pixel coordinates.
sx, sy = (1, 1) if max(box) > 1000 else (W / 1000, H / 1000)
x1, x2 = sorted((box[0] * sx, box[2] * sx)); y1, y2 = sorted((box[1] * sy, box[3] * sy))
# 1% padding so text at the edge is not cut.
x1, x2 = max(0, x1 - W * .01), min(W, x2 + W * .01); y1, y2 = max(0, y1 - H * .01), min(H, y2 + H * .01)
# Ignore crops under 25% of the frame in either direction.
if x2 - x1 < .25 * W or y2 - y1 < .25 * H: return path.name
out = path.with_name(f"view_{path.stem}.jpg")
im.crop((int(x1), int(y1), int(x2), int(y2))).convert("RGB").save(out, quality=90)
@@ -105,26 +129,33 @@ def _view(path, box):
def _times(video, scene, bars=None):
# fps=2 sampling at 640 px wide; keep frames on scene change, the first frame, or >=60 s since the last kept one. showinfo prints pts_time to stderr.
r = subprocess.run(["ffmpeg", "-i", str(video), "-vf",
(bars + "," if bars else "") + f"fps=2,scale=640:-2,select='gt(scene,{scene})+isnan(prev_selected_t)+gte(t-prev_selected_t,60)',showinfo",
"-f", "null", "-"], capture_output=True, text=True)
# Timestamps (seconds) parsed from showinfo output.
return [float(m) for m in re.findall(r"pts_time:([\d.]+)", r.stderr)]
# Extract scene-change keyframes, dedupe, read each with the VLM, write shots.json and glossary, derive share/presence events.
def run(name, max_frames=60, scene=0.05):
import imagehash
from PIL import Image
d = db.out_dir(name)
# media() returns (audio, video); index 1 is the video.
video = db.media(name)[1]
# No video: write empty outputs and stop.
if video is None:
db.replace_shots(name, [])
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]")
return
sd = d / "shots"
sd.mkdir(exist_ok=True)
# Clear frames from a previous run.
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
db.tick(name, 0, 0, "estrazione dei fotogrammi dal video")
kept = [] # (t, path, hash)
# Duration from DB, used for the black-bar detection.
bars = _bars(video, (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [0])[0] or 0)
for t in _times(video, scene, bars):
p = sd / f"shot_{int(t)//60:02d}m{int(t)%60:02d}s.jpg"
@@ -133,8 +164,10 @@ def run(name, max_frames=60, scene=0.05):
*(["-vf", bars] if bars else []), "-q:v", "3", str(p)], check=True)
if not p.exists(): continue
h = imagehash.phash(Image.open(p))
# pHash distance <=8 = near-duplicate of the last kept frame: drop it.
if kept and h - kept[-1][2] <= 8: p.unlink(); continue
kept.append((t, p, h))
# Too many frames: keep evenly spaced ones up to max_frames.
if len(kept) > max_frames:
keep = sorted({round(i * (len(kept) - 1) / (max_frames - 1)) for i in range(max_frames)})
for i, k in enumerate(kept):
@@ -142,6 +175,7 @@ def run(name, max_frames=60, scene=0.05):
kept = [kept[i] for i in keep]
db.tick(name, 0, len(kept), "avvio del modello di visione")
# srv is None if llama-server was already running (we do not stop someone else's).
srv = llama.start(log=db.logs(name) / "llama.log") # None if already running
rows = []
try:
@@ -151,19 +185,24 @@ def run(name, max_frames=60, scene=0.05):
r["view"] = _view(p, r.pop("content_box", None))
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True)
finally:
# Stop only the server this function started.
if srv: srv.terminate()
# Duration from DB; fall back to last frame time + 60 s.
dur = (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [None])[0]
if dur is None: dur = rows[-1]["t"] + 60 if rows else 0
prev = None
# lead=False when a row repeats the previous kind+title (continuation of the same topic).
for i, r in enumerate(rows):
r["t_end"] = rows[i + 1]["t"] if i + 1 < len(rows) else dur
key = (r["kind"], (r["title"] or "").lower()) if r["title"] else None
r["lead"] = not (key and key == prev)
prev = key
# Persist to file and DB.
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_shots(name, rows)
# Glossary: terms appearing in the most frames (3-40 chars), top 150.
cnt = collections.Counter()
for r in rows:
e = r["entities"]
@@ -171,13 +210,17 @@ def run(name, max_frames=60, scene=0.05):
(d / "glossary.json").write_text(json.dumps([w for w, _ in cnt.most_common(150)], ensure_ascii=False), encoding="utf-8")
c = db.connect()
# Derive events only if the call has no roster presence events yet (avoid duplicates).
if c.execute("SELECT count(*) FROM call_events WHERE name=? AND kind='present' AND who_key<>'video'", (name,)).fetchone()[0] == 0:
# Replace any video-derived events from an earlier run.
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
ev = []
# People shown on video tiles -> 'present' events. Names with a space and >4 chars only (skips initials).
for r in rows:
ppl = [n for n in (db.norm_name(x) for x in r["people"]) if " " in n and len(n) > 4]
if ppl: ev.append((r["t"], "present", "video", "", json.dumps([{"key": "video", "who": n} for n in ppl], ensure_ascii=False)))
last = None
# Presenter changes -> share_start / share_stop pairs.
for r in rows:
pr = db.norm_name(r["presenter"]) if r["presenter"] else None
if pr != last:
+6
View File
@@ -3,16 +3,19 @@ import json
import db
# Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name.
def run(name):
p = db.out_dir(name) / "diar_segments.json"
ev = db.events(name, "active", "caption")
if not p.exists() or not ev: return
segs = json.loads(p.read_text(encoding="utf-8"))
iv = []
# Intervals where a person was speaking or captioned: 'active' is a 0.5 s point, 'caption' is +/-2 s around its timestamp.
for e in ev:
if not e["who"]: continue
a, b = (e["t"], e["t"] + 0.5) if e["kind"] == "active" else (e["t"] - 2, e["t"] + 2)
iv.append((a, b, e["who"]))
# Total overlap seconds per (label, person).
tot = {}
for s in segs:
d = tot.setdefault(s["label"], {})
@@ -24,7 +27,10 @@ def run(name):
got, used = {}, set()
for ov, label, who in pairs:
if label in got or who in used: continue
# Accept only if overlap >= 5 s and >= 40 % of the label's total.
if ov >= 5 and ov / sum(tot[label].values()) >= 0.4: got[label] = (who, ov); used.add(who)
# Every label gets a row, even unmatched ones (who='').
for label in {s["label"] for s in segs}:
who, ov = got.get(label, ("", sum(tot.get(label, {}).values())))
# Store the mapping (source 'auto', with overlap seconds).
db.set_speaker_map(name, label, who, "auto", ov)
+22
View File
@@ -5,9 +5,11 @@ import numpy as np
import db
HERE = Path(__file__).parent
# Pre-converted OpenVINO Whisper model; downloaded on first NPU use.
NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
# Log via Prefect when inside a flow; print otherwise.
def _log(msg):
try:
from prefect import get_run_logger
@@ -25,39 +27,50 @@ def aggregate(segs):
for s, e, t in segs:
t = t.strip()
if not t: continue
# Count consecutive identical segments; the 3rd+ repeat is a whisper loop and is skipped.
rep = rep + 1 if t == last else 0; last = t
if rep >= 2: continue
# A pause over 1 s starts a new line.
if buf and s - end > 1: flush()
if not buf: start = s
buf.append(t); end = e
# End the line at sentence punctuation, or after 12 s.
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
flush()
return lines
# Decode to 16 kHz mono float32 PCM via ffmpeg; the format whisper and the NPU pipeline expect.
def _decode(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
return np.frombuffer(raw, np.float32)
# Faster-whisper on CUDA (CPU fallback in common.load_model); returns (segments, device). tick(done, total) reports progress.
def _cuda(audio, model, glossary, tick=lambda done, total: None):
import common
# Load the model; dev is 'cuda' or 'cpu'.
m, dev = common.load_model(model)
# ponytail: >~20 hotwords crowd whisper's prompt -> dropped text + repetition loops (seen with 60)
kw = {"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False} if glossary else {}
try:
# Italian forced; VAD (voice activity detection) skips silence.
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
out = []
# Keep each segment, reporting progress by its end time.
for s in segs: out.append((s.start, s.end, s.text)); tick(s.end, info.duration)
return out, dev
finally:
# Free the model (VRAM) before returning, even on error.
del m; gc.collect()
# OpenVINO GenAI Whisper on the Intel NPU. Failure raises 'NPU failed' so flow.py can fall back to CUDA.
def _npu(audio):
try:
import openvino_genai as ov
# First run: download the pre-converted model; if that fails, export it locally with optimum (slow).
if not NPU_MODEL_DIR.exists():
from huggingface_hub import snapshot_download
try:
@@ -65,32 +78,41 @@ def _npu(audio):
except Exception:
subprocess.run(["optimum-cli", "export", "openvino", "--model", "openai/whisper-large-v3-turbo",
"--weight-format", "fp16", str(NPU_MODEL_DIR)], check=True)
# Load the pipeline on the NPU device.
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True)
# Empty output counts as failure.
if not res.chunks: raise RuntimeError("no chunks returned")
return [(c.start_ts, c.end_ts, c.text) for c in res.chunks]
except Exception as e:
raise RuntimeError(f"NPU failed: {e!r}")
# Transcribe one meeting into transcript.txt and DB lines. out_path is used by --bench-npu to write a side file only.
def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path | None = None):
audio = db.out_dir(name) / "audio.opus"
gl = db.out_dir(name) / "glossary.json"
# Glossary from shots (used as whisper hotwords).
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
t0 = time.time()
# NPU reports no progress; CUDA reports per segment.
if device == "npu":
db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)")
segs, used = _npu(audio), "npu"
else:
tick = lambda done, total: db.tick(name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio")
segs, used = _cuda(audio, model, glossary, tick)
# Group segments into timestamped lines.
lines = aggregate(segs)
# Format as [mm:ss] text, the format diarize.py parses.
txt = "\n".join(f"[{t//60:02d}:{t%60:02d}] {x}" for t, x in lines)
for l in txt.splitlines(): _log(l)
secs = time.time() - t0
# Benchmark mode: write to the given file only; leave the DB alone.
if out_path is not None:
out_path.write_text(txt, encoding="utf-8")
return secs
# Normal mode: persist transcript file and DB rows, and record which device was used.
(db.out_dir(name) / "transcript.txt").write_text(txt, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs)
+15
View File
@@ -1,29 +1,44 @@
<!doctype html><meta charset=utf-8><title>Meetings</title>
<!-- Local Web UI for recorded Teams meetings; ui.js renders and drives everything. -->
<link rel=stylesheet href=/ui.css>
<!-- Header: title, omp login status (omps) and queue summary (qs), both filled by tick() in ui.js. -->
<main><header><div><h1>Riunioni</h1><div class=hs><span id=omps title="login: menu Pinokio → Cloud login"></span><span id=qs></span></div></div>
<!-- Header actions: settings popover and upload. -->
<div class=ha>
<!-- Settings popover: skip-screenshots switch and LLM model pickers (wired by setSkip / setLlm in ui.js). -->
<details class=cfg><summary title="impostazioni di elaborazione">⚙ Impostazioni</summary><div class=pop>
<label class=sw title="non legge le schermate condivise: elaborazione molto più veloce, report solo dal parlato"><input type=checkbox id=skp onchange=setSkip()><i></i><span><b>Salta schermate</b><small>più veloce, report solo dal parlato</small></span></label>
<label class=fl>Modello schermate<select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select></label>
<label class=fl>Modello report<select id=llmr title="modello per il report" onchange=setLlm()></select></label></div></details>
<!-- Upload button; the hidden file input below does the picking. -->
<button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<!-- Hidden file input used by pick(). -->
<input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header>
<!-- Bulk-action bar, shown only when recordings are checked (upd() in ui.js). -->
<div class=card id=bulk hidden><b id=bn></b><a onclick=selAll(1)>tutte</a><a onclick=selAll(0)>nessuna</a><span class=sep></span>
<button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci</button>
<select id=bf title="step da cui rielaborare"><option>audio<option>transcribe<option>diarize<option>speakers<option>shots<option>docs<option>report<option>memory<option>render</select><button onclick=bulkRun() title="rielabora le registrazioni spuntate dallo step scelto">Rielabora da qui</button>
<button class=del onclick=bulkDrop() title="elimina solo i file video, report e trascrizione restano">Elimina video</button>
<button class=del onclick=bulkDel()>Elimina tutto</button></div>
<!-- Drag-and-drop hint; ui.js also accepts drops anywhere on the page. -->
<div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div>
<!-- Upload progress card (send() in ui.js). -->
<div class="card" id=ub hidden><div class=pg style="margin:0;border:0;padding:0;background:none"><div class=pgh><span><span class=big id=ubig>0%</span> &nbsp;<b id=utitle></b></span><button id=ucancel>annulla</button></div>
<div class=bar><i id=ubar></i></div><div class=sub><span id=utxt></span></div></div></div>
<!-- Search over speech and screen text, plus Q&A over the meetings. -->
<div class=card><div class=row><input id=q placeholder="Cerca nel parlato e sullo schermo"><button onclick=srch()>Cerca</button></div>
<div id=sr></div><div class=row><input id=qa placeholder="Chiedi alle riunioni"><select id=llma title="modello per le risposte (stesso del report)" onchange="llmr.value=llma.value;setLlm()"></select><button class=pri id=ab onclick=ask()>Chiedi</button></div><div id=ar></div></div>
<!-- Meetings table: rendered by tick() in ui.js. -->
<div class="card t"><table id=t></table></div></main>
<!-- Preview and crop dialog (play() in ui.js). -->
<dialog id=cdlg><div class=pgh><b id=ctitle></b><button onclick=cclose()>✕ chiudi</button></div>
<video id=cv controls preload=metadata></video>
<!-- Crop controls: start and end time as mm:ss or h:mm:ss. -->
<div class=row style="margin-top:10px"><button onclick="cs.value=fmt(cv.currentTime)">⇤ inizio = qui</button><input class=tm id=cs value="00:00">
<input class=tm id=ce><button onclick="ce.value=fmt(cv.currentTime)">fine = qui ⇥</button>
<button onclick=cplay()>▶ anteprima ritaglio</button><button class=pri id=cgo_ onclick="cgo(0)">✂ Ritaglia e salva come nuova riunione</button><button id=cgi_ onclick="cgo(1)">✂ Ritaglia e salva in questa riunione</button></div>
<!-- Progress bar for the crop re-encode (polled from /crop_progress). -->
<progress id=cpr max=100 value=0 hidden style="width:100%"></progress>
<div id=cmsg>L'originale resta intatto: il ritaglio diventa una nuova riunione (mm:ss o h:mm:ss).</div></dialog>
<!-- Web UI logic. -->
<script src=/ui.js></script>
+47
View File
@@ -1,54 +1,101 @@
/* Theme colours as CSS variables; light theme by default. */
:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442;--acc2:#b05535;--on:#fff;
--red:#f6e0dc;--redf:#a33a2a;--amb:#f7ecd6;--ambf:#8a5a12;--grn:#e2eedf;--grnf:#3d6b35;--gry:#ebe9e1;--gryf:#5e5d57}
/* Dark theme overrides, applied when the OS prefers dark. */
@media (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757;--acc2:#e58a6c;--on:#1f1e1d;
--red:#4a2b26;--redf:#f0a597;--amb:#4a3d24;--ambf:#ecc77f;--grn:#2d3f2a;--grnf:#a8d39c;--gry:#3a3a35;--gryf:#c2c0b6}}
/* Base reset and body typography. */
*{box-sizing:border-box}body{font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;margin:0;padding:32px 24px 64px;background:var(--bg);color:var(--fg)}
/* Centred page column; header wraps on narrow windows. */
main{max-width:1200px;margin:auto}header{display:flex;align-items:end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px}
/* Serif page heading. */
h1{font:500 30px/1.2 ui-serif,Georgia,"Times New Roman",serif;letter-spacing:-.01em;margin:0}
/* Card container for each section. */
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:16px}
/* Flex rows for toolbars and search; inputs grow to fill. */
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.row+.row{margin-top:10px}.row input{flex:1;min-width:220px}
/* Shared form-control look. */
input,select,button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:6px 10px}
/* Accent focus ring. */
input:focus,select:focus{outline:2px solid var(--acc);outline-offset:-1px}
/* Default buttons; primary buttons (.pri) use the accent colour. */
button{cursor:pointer;background:var(--soft)}button:hover{border-color:var(--mut)}button:disabled{opacity:.5;cursor:default}
button.pri{background:var(--acc);border-color:var(--acc);color:var(--on)}button.pri:hover{background:var(--acc2)}
/* Search and Q&A result containers. */
#sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px}
/* Meetings table: full width, rows separated by lines. */
table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tbody.rec:last-child tr:last-child td{border-bottom:0}
/* Alternate background per recording group (tbody.rec); accent bar marks the main row. */
tbody.rec:nth-of-type(even) td{background:color-mix(in srgb,var(--acc) 7%,transparent)}tbody.rec tr.main td:first-child{box-shadow:inset 3px 0 var(--acc)}tbody.rec tr:last-child td{border-bottom:2px solid var(--line)}
/* Table headers. */
th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;letter-spacing:.05em}.card.t{padding:4px 8px;overflow-x:auto}
/* Status badge pill. */
.b{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:500;background:var(--gry);color:var(--gryf)}
/* Status colours: red = recording/error/cancelled, amber = in progress, green = done. */
.recording,.error,.cancelled{background:var(--red);color:var(--redf)}.audio,.transcribing,.diarizing,.identifying,.shots,.docs,.report,.memory{background:var(--amb);color:var(--ambf)}.done{background:var(--grn);color:var(--grnf)}
/* Links, muted small text, speaker-panel row background. */
a{color:var(--acc);cursor:pointer;margin-right:10px;text-decoration:none}a:hover{text-decoration:underline}small{color:var(--mut)}.sp td{background:var(--soft)}.sp div{margin-bottom:8px}
/* Speaker-panel footer buttons. */
.sp .sa{display:flex;gap:8px;justify-content:flex-end;margin-top:12px;padding-top:12px;border-top:1px solid var(--line)}.sp .sa button{padding:7px 16px;font-weight:500}.sp td{padding:14px 16px}
/* Spacing for table action buttons; muted queue counter. */
td button,td select{margin:0 4px 4px 0}#qs{color:var(--mut)}
/* Progress panel (.pg) shown while a pipeline runs. */
.pg{padding:14px 16px 12px;background:var(--soft);border:1px solid var(--line);border-radius:12px;margin:0 0 8px}
/* Progress panel header row. */
.pgh{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap;margin-bottom:8px}.pgh b{font-size:15px}.pgh .n{color:var(--mut)}
/* Large percentage figure and ETA text. */
.big{font:600 22px/1 ui-serif,Georgia,serif;letter-spacing:-.01em}.eta{color:var(--mut);font-size:13px}.eta b{color:var(--fg);font-size:13px}
/* Progress bar track; .thin is the per-step bar. */
.bar{height:12px;background:var(--line);border-radius:99px;overflow:hidden}.bar.thin{height:6px;margin-top:10px}
/* Bar fill: animated diagonal stripes (moved by the mv keyframes). */
.bar>i{display:block;height:100%;width:0;border-radius:99px;transition:width .9s ease;background-color:var(--acc);
background-image:linear-gradient(45deg,rgba(255,255,255,.2) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.2) 50%,rgba(255,255,255,.2) 75%,transparent 75%),linear-gradient(90deg,var(--acc),var(--acc2));
background-size:24px 24px,100% 100%;animation:mv 1s linear infinite}
@keyframes mv{to{background-position:24px 0,0 0}}
/* Indeterminate bar: sliding 30% segment (used while progress is unknown). */
.bar.ind>i{width:30%!important;animation:mv 1s linear infinite,ind 1.6s ease-in-out infinite}@keyframes ind{0%{margin-left:-30%}100%{margin-left:100%}}
/* Step chips row. */
.steps{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
/* Step chip base. */
.st{font-size:12px;padding:3px 10px;border-radius:99px;background:var(--card);border:1px solid var(--line);color:var(--mut);white-space:nowrap}
/* Step chip states: ok, running (pulsing), skipped (struck through). */
.st.ok{background:var(--grn);color:var(--grnf);border-color:transparent}.st.run{background:var(--acc);color:var(--on);border-color:transparent;animation:pulse 1.8s ease-in-out infinite}.st.skip{opacity:.4;text-decoration:line-through}
@keyframes pulse{50%{opacity:.72}}
/* Caption line under the progress bar. */
.sub{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:6px;font-size:12.5px;color:var(--mut)}
/* Live activity line with pulsing dot. */
.live{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:13px;color:var(--mut)}.dot{flex:none;width:9px;height:9px;border-radius:50%;background:var(--grnf);animation:pulse 1s ease-in-out infinite}
/* Live activity severity: warn = amber, bad = red with a static dot. */
.live.warn,.live.warn b{color:var(--ambf)}.live.warn .dot{background:var(--ambf)}.live.bad,.live.bad b{color:var(--redf)}.live.bad .dot{background:var(--redf);animation:none}
/* Upload card stays visible while scrolling. */
#ub{position:sticky;top:12px;z-index:5}#ub .pgh{margin-bottom:10px}
/* Dashed outline while a file is dragged over the page. */
body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14px}
/* Hint text. */
#hint{color:var(--mut);font-size:12.5px}
/* Destructive buttons. */
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}
/* Preview/crop dialog. */
dialog{border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--fg);padding:16px;width:min(960px,94vw)}dialog::backdrop{background:rgba(0,0,0,.5)}
/* Video inside the dialog. */
dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}
/* Header layout; separator line under it; the subtitle line hides when empty. */
header{align-items:center;padding-bottom:16px;border-bottom:1px solid var(--line)}.hs{display:flex;gap:12px;flex-wrap:wrap;margin-top:4px;font-size:12.5px;color:var(--mut)}.hs:empty{display:none}
/* Header action group. */
.ha{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.ha>button,.cfg summary{padding:8px 14px;font-weight:500}
/* Settings dropdown (details/summary). */
.cfg{position:relative}.cfg summary{list-style:none;cursor:pointer;user-select:none;background:var(--soft);border:1px solid var(--line);border-radius:9px}.cfg summary::-webkit-details-marker{display:none}.cfg summary:hover,.cfg[open] summary{border-color:var(--mut)}
/* Settings popover panel. */
.pop{position:absolute;right:0;top:calc(100% + 8px);z-index:20;width:300px;display:flex;flex-direction:column;gap:14px;padding:16px;background:var(--card);border:1px solid var(--line);border-radius:14px;box-shadow:0 10px 30px rgba(0,0,0,.18)}
/* On/off switch: the checkbox is hidden and the track (i) is styled. */
.sw{display:flex;gap:12px;align-items:center;cursor:pointer}.sw span{display:flex;flex-direction:column}.sw small{font-size:12px}
/* Switch track. */
.sw input{position:absolute;opacity:0;width:0;height:0}.sw i{flex:none;position:relative;width:38px;height:22px;border-radius:99px;background:var(--line);transition:background .15s}
/* Switch knob. */
.sw i::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s}
/* Checked state: knob slides 16 px. */
.sw input:checked+i{background:var(--acc)}.sw input:checked+i::after{transform:translateX(16px)}.sw input:focus-visible+i{outline:2px solid var(--acc);outline-offset:2px}.sw input:disabled+i{opacity:.5}
/* Labelled select in the settings popover. */
.fl{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--mut)}.fl select{width:100%;font-size:14px;color:var(--fg)}
/* Bulk-action bar: sticky at the top while visible. */
#bulk{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 14px;position:sticky;top:12px;z-index:6;box-shadow:0 6px 20px rgba(0,0,0,.12)}#bulk[hidden]{display:none}#bulk a{cursor:pointer}#bulk .sep{flex:1}
+84
View File
@@ -1,78 +1,137 @@
// Web UI logic: polls /status every 3 s, renders the meetings table, and wires search, Q&A, upload, crop and bulk actions to the local server.
// Escape text for innerHTML (&, <, >, ").
const E=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
// Seconds -> mm:ss (minutes can exceed 59; no hour form here).
const fmt=s=>{s=Math.round(s);return String(Math.floor(s/60)).padStart(2,"0")+":"+String(s%60).padStart(2,"0")};
// Enter in the search box runs the search.
q.onkeydown=e=>{if(e.key=="Enter")srch()};
// Enter in the Q&A box asks the question.
qa.onkeydown=e=>{if(e.key=="Enter")ask()};
// Q&A: /ask answers from the meeting data. The model may take minutes to load on first use.
async function ask(){if(!qa.value)return;ar.innerHTML="<small>…avvio modelli / risposta (può richiedere qualche minuto)</small>";
const r=await fetch("/ask?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return}const j=await r.json();
// Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing.
ar.innerHTML="<div>"+E(j.answer).replace(/\[(\d+)\]/g,(m,n)=>{const s=j.sources[n-1];return s?`<a href="/report?name=${s.name}#${s.anchor}" target=_blank>[${n}]</a>`:m})+"</div>"+
j.sources.map(s=>`<div><small>[${s.n}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} ${fmt(s.t)} (${s.kind}): ${E(s.text)}</small></div>`).join("")}
// Search over speech and screen text (/search).
async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json();
// Speech hits: [meeting, seconds, speaker, text]. Screen hits: [meeting, seconds, speaker, text, shot file] and link to the screenshot.
sr.innerHTML=j.speech.map(r=>`<div>${E(r[0])} ${fmt(r[1])} ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")+j.screen.map(r=>`<div>🖥 <a href="/shot?name=${r[0]}&file=shots/${r[4]}" target=_blank>${E(r[0])} ${fmt(r[1])}</a> ${E(r[2]||"")}: ${E(r[3])}</div>`).join("")}
// Start a pipeline run from the chosen step (/run); 409 means it is already running.
async function run(n){const f=document.getElementById("f-"+n).value;const r=await fetch(`/run?name=${n}&from=${f}`,{method:"POST"});if(r.status==409)alert("già in esecuzione");tick()}
// Names of the checked recording rows (.mg checkboxes).
const sel_=()=>[...document.querySelectorAll(".mg:checked")].map(x=>x.value);
// Show the bulk bar only when something is checked, and show the selected count.
function upd(){const n=sel_().length;bulk.hidden=!n;bn.textContent=`${n} selezionat${n==1?"a":"e"}`}
// Check or uncheck all recording rows.
function selAll(v){document.querySelectorAll(".mg").forEach(x=>x.checked=!!v);upd()}
// Run one POST per selected recording and collect failures into a single alert.
async function bulk_(path,names,label){let bad=[];for(const n of names){const r=await fetch(`${path}${path.includes("?")?"&":"?"}name=${n}`,{method:"POST"});if(!r.ok)bad.push(`${n}: ${await r.text()}`)}
if(bad.length)alert(`${label}: ${names.length-bad.length}/${names.length} ok\n`+bad.join("\n"));tick()}
// Re-run the selected recordings from the step chosen in #bf.
function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")}
// Bulk delete of video files only; report, transcript and screenshots are kept.
function bulkDrop(){const n=sel_();if(confirm(`Eliminare i file video di ${n.length} riunioni?
Report, trascrizione, audio e schermate restano, ma non potranno più essere rielaborate. Non si può annullare.`))bulk_("/drop_video",n,"elimina video")}
// Bulk delete of whole recordings; asks for confirmation first.
function bulkDel(){const n=sel_();if(confirm(`Eliminare definitivamente ${n.length} riunioni?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))bulk_("/delete",n,"elimina")}
// Merge two or more checked recordings (same meeting restarted) into one.
async function mergeSel(){const n=sel_();if(n.length<2)return alert("spunta almeno 2 registrazioni");const r=await fetch("/merge?names="+n.join(","),{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Names whose speakers panel is open; kept across re-renders.
const open_=new Set();
// Toggle the speakers panel for one recording and re-render.
async function spk(n){editing=false;open_.has(n)?open_.delete(n):open_.add(n);tick()}
// Speakers panel: diarization label -> person mapping, with a datalist of candidate names.
async function panel(n){const j=await (await fetch("/speakers?name="+n)).json();
return `<tr class=sp><td colspan=7><datalist id="cand-${n}">${j.candidates.map(c=>`<option value="${E(c)}">`).join("")}</datalist>`+
j.rows.map(r=>`<div><b>${E(r.label)}</b> ${fmt(r.talk_s)} <input data-n="${n}" data-l="${E(r.label)}" list="cand-${n}" value="${E(r.person)}"> ${r.source}${r.source=="auto"&&r.overlap_s!=null?" "+Math.round(r.overlap_s)+"s":""}<br><small>${r.samples.map(E).join(" | ")}</small></div>`).join("")+
`<div class=sa><button class=pri onclick="saveSpk('${n}')">✓ Salva nomi</button><button onclick="spk('${n}')">✕ Chiudi</button></div>`}
// Read the label -> person inputs and save them (/speaker_map).
async function saveSpk(n){const m={};document.querySelectorAll(`input[data-n="${n}"]`).forEach(i=>m[i.dataset.l]=i.value);
const r=await fetch("/speaker_map?name="+n,{method:"POST",body:JSON.stringify(m)});editing=false;const t=await r.text();open_.delete(n);tick();alert(t)}
// Recompute the automatic title from the report.
async function retitle(n){const r=await fetch(`/run?name=${n}&from=title`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
const sel={};
// Delete one recording after confirmation.
async function del_(n,label){if(!confirm(`Eliminare definitivamente "${label}"?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))return;
const r=await fetch("/delete?name="+n,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Delete only the video file of one recording (report and transcript stay).
async function dropVid(n,mb){if(!confirm(`Eliminare il file video (${mb} MB)?
Report, trascrizione, audio e schermate restano, ma la riunione non potrà più essere rielaborata. Non si può annullare.`))return;
const r=await fetch("/drop_video?name="+n,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Prompt for a new title; empty means automatic. The date suffix is stripped from the default text.
async function setTitle(n,cur){const t=prompt("Titolo della riunione (vuoto = automatico)",cur.replace(/ — \d{4}-\d\d-\d\d.*$/,""));if(t===null)return;
const r=await fetch("/title?name="+n,{method:"POST",body:t});if(!r.ok)alert(await r.text());tick()}
// "mm:ss" or "h:mm:ss" -> seconds.
const sec=s=>s.trim().split(":").reduce((a,x)=>a*60+(+x),0);
// Open the preview dialog for recording n; the video is streamed from /video.
function play(n,d,t){cv.src="/video?name="+n;ctitle.textContent=t;cs.value="00:00";ce.value=d?fmt(d):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration)};cdlg.showModal()}
// Stop and unload the video so the file handle is released.
function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()}
// Esc closes the dialog through the same cleanup.
cdlg.addEventListener("cancel",cclose);
// Play from the start time; pause at the end time when one is set.
function cplay(){cv.currentTime=sec(cs.value);cv.play();const e=sec(ce.value);cv.ontimeupdate=()=>{if(e>0&&cv.currentTime>=e){cv.pause();cv.ontimeupdate=null}}}
// Crop: inplace replaces the original (after confirm); otherwise a new meeting is created from the clip.
async function cgo(inplace){const a=sec(cs.value),b=sec(ce.value),n=new URL(cv.src).searchParams.get("name");
// Validate the interval: start >= 0 and end after start.
if(!(a>=0&&b>a)){cmsg.textContent="intervallo non valido";return}
// Replacing the original is irreversible, so confirm first.
if(inplace&&!confirm("Sostituire il video di questa riunione con il ritaglio? L'originale va perso e la riunione viene rielaborata da zero."))return;
if(inplace){cv.pause();cv.removeAttribute("src");cv.load()} // release the file: Windows can't replace a source the browser has open
// Disable both crop buttons while the re-encode runs.
cgo_.disabled=cgi_.disabled=true;cmsg.textContent="ritaglio in corso… (ricodifica, può richiedere minuti)";cpr.value=0;cpr.hidden=false;
// Poll crop progress every 700 ms while the blocking /crop request is pending.
const iv=setInterval(async()=>{try{const p=(await(await fetch("/crop_progress?name="+n,{method:"POST"})).json()).pct;if(p!=null){cpr.value=p;cmsg.textContent=`ritaglio in corso… ${Math.round(p)}%`}}catch(e){}},700);
// Blocking request: the server re-encodes the clip, which can take minutes.
const r=await fetch(`/crop?name=${n}&start=${a}&end=${b}${inplace?"&inplace=1":""}`,{method:"POST"});clearInterval(iv);cgo_.disabled=cgi_.disabled=false;cpr.hidden=true;
// Show the result and refresh the table.
if(!r.ok){cmsg.textContent="errore: "+await r.text();return}cmsg.textContent=inplace?"✓ riunione ritagliata, rielaborazione avviata":"✓ creata nuova riunione, elaborazione avviata";tick()}
// Cancel a running or queued pipeline (after confirm).
async function stopRun(n){if(!confirm(`Fermare ${n}?`))return;await fetch("/cancel?name="+n,{method:"POST"});tick()}
// Save the screenshot-model and report-model choice on the server.
async function setLlm(){const r=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!r.ok)alert(await r.text());tick()}
// Save the "skip screenshots" switch on the server.
async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()}
// Italian labels for pipeline steps.
const LBL={audio:"Audio",transcribing:"Trascrizione",diarizing:"Chi parla",identifying:"Nomi parlanti",shots:"Schermate",docs:"Documentazione",report:"Report",memory:"Memoria"};
// What each step does, shown under the progress bar.
const HOW={audio:"pulizia e normalizzazione dell'audio",transcribing:"Whisper trascrive il parlato",diarizing:"riconoscimento di chi parla",identifying:"abbinamento voci-nomi",shots:"il modello di visione legge ogni schermata condivisa",docs:"ricerca su Confluence e Jira",report:"il modello scrive argomenti, decisioni e azioni",memory:"indicizzazione per la ricerca tra riunioni"};
// Seconds -> "N s", "N min" or "H h MM min".
const dur=s=>{if(s==null||!isFinite(s))return"–";s=Math.max(0,Math.round(s));if(s<60)return s+" s";const m=Math.round(s/60);return m<60?m+" min":Math.floor(m/60)+" h "+String(m%60).padStart(2,"0")+" min"};
// Seconds from now -> local HH:MM.
const clock=s=>new Date(Date.now()+s*1000).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});
// Per recording: last [timestamp, tokens decoded], used to compute tokens/s between ticks.
const LT={};
// LLM activity line: prompt reading vs token writing; idle time sets the severity colour.
function live(n,p){const l=p.llm;let txt="",act=false;
// Model is busy: compare token counts with the previous tick.
if(l&&l.is_processing){act=true;const k=n,prev=LT[k],now=Date.now(),d=l.n_decoded||0;
// Tokens/s from the delta since the previous tick.
if(d>0){const tps=prev&&d>prev[1]?(d-prev[1])/((now-prev[0])/1000):null;txt=`Il modello sta scrivendo: <b>${d}</b> token${tps?` · <b>${tps.toFixed(1)}</b> token/s`:""}`}
else txt=`Il modello sta leggendo il contesto: <b>${l.n_prompt_tokens_processed||0}</b> di ${l.n_prompt_tokens} token`;
// Store this sample for the next tick.
LT[k]=[now,d]}
// Severity by idle time: under 90 s ok, under 300 s warn, otherwise bad.
const idle=p.idle,cls=act||idle<90?"":idle<300?"warn":"bad";
// Status text for the idle time.
const tail=act?`ultimo passo completato ${dur(idle)} fa`:idle<90?`attivo · aggiornato ${dur(idle)} fa`:idle<300?`nessun avanzamento da <b>${dur(idle)}</b>: può essere normale (avvio modello, passo lungo)`:`nessuna attività da <b>${dur(idle)}</b>: possibile blocco, controlla il log Prefect o premi stop`;
return `<div class="live ${cls}"><span class=dot></span><span>${txt?txt+" — ":""}${tail}</span></div>`}
// Progress panel for a recording: boot, queued, or running pipeline.
function progPanel(r){const p=r.prog;
// Pipeline starting: the Python environment can take minutes on the first run.
if(!p&&r.running)return `<tr><td colspan=7><div class=pg><div class=pgh><span><span class=big>…</span> &nbsp;<b>Avvio della pipeline</b> <span class=n>— preparazione dell'ambiente Python (la prima volta scarica le dipendenze: qualche minuto)</span></span></div><div class="bar ind"><i></i></div><div class="live"><span class=dot></span><span>${E(r.boot||"in avvio…")}</span></div></div>`;
// Queued behind another run, or nothing to show.
if(!p)return r.status=="queued"?`<tr><td colspan=7><div class=pg><div class=pgh><b>In coda</b><span class=eta>parte appena finisce l'elaborazione in corso</span></div><div class="bar ind"><i></i></div></div>`:"";
// Overall percent (null if unknown) and the running step.
const pct=p.pct!=null?Math.round(p.pct*100):null,cur=p.plan.find(x=>x.state=="run");
// Step chips: skipped / done with duration / running with fraction / pending with estimate.
const chips=p.plan.map(x=>x.state=="skip"?`<span class="st skip" title="non rieseguito">${LBL[x.s]}</span>`:x.state=="done"?`<span class="st ok">✓ ${LBL[x.s]} · ${dur(x.secs)}</span>`:x.state=="run"?`<span class="st run">● ${LBL[x.s]} · ${Math.round(x.frac*100)}%</span>`:`<span class=st>${LBL[x.s]} · ~${dur(x.est)}</span>`).join("");
// Done-of-total counter and step label.
const cnt=p.total?`${p.done} di ${p.total}`:"",step=LBL[p.step]||p.step;
// Panel markup: header, progress bars, step chips and live status.
return `<tr><td colspan=7><div class=pg>
<div class=pgh><span><span class=big>${pct!=null?pct+"%":"…"}</span> &nbsp;<b>${step}</b> <span class=n>— ${E(p.note||HOW[p.step]||"")}</span></span>
<span class=eta>${p.eta!=null?`fine prevista <b>~${clock(p.eta)}</b> · mancano <b>${dur(p.eta)}</b> · `:""}trascorso ${dur(p.elapsed)}</span></div>
@@ -82,35 +141,60 @@ return `<tr><td colspan=7><div class=pg>
<div class=sub><span>${step}: ${cnt?cnt+" · ":""}${Math.round(p.frac*100)}%</span><span>${cur?`questo passo: ancora ~${dur(cur.left)} (in corso da ${dur(cur.secs)})`:""}</span></div>
${live(r.name,p)}</div>`}
function pick(){up.click()}
// Upload with XHR so we get upload progress events. Target: POST /upload?filename=.
function send(f){const x=new XMLHttpRequest(),t0=Date.now();ub.hidden=false;ubar.style.width="0%";utitle.textContent="Caricamento di "+f.name;ubig.textContent="0%";
// Update bar, percent, MB/s and ETA from upload progress.
x.upload.onprogress=e=>{if(!e.lengthComputable)return;const p=e.loaded/e.total,s=(Date.now()-t0)/1000,v=e.loaded/Math.max(s,.1);
ubar.style.width=(p*100).toFixed(1)+"%";ubig.textContent=Math.floor(p*100)+"%";
utxt.textContent=`${(e.loaded/1e6).toFixed(0)} di ${(e.total/1e6).toFixed(0)} MB · ${(v/1e6).toFixed(1)} MB/s · mancano ${dur((e.total-e.loaded)/v)}`};
// Upload finished on the client; the server now validates the file and starts processing.
x.upload.onload=()=>{utxt.textContent="File ricevuto: controllo del formato e avvio dell'elaborazione…"};
// Success: show the recording duration; hide the card after 6 s.
x.onload=()=>{if(x.status==200){const j=JSON.parse(x.responseText);ubig.textContent="✓";utxt.textContent=`Avviata l'elaborazione (${dur(j.duration_s)} di registrazione): segui l'avanzamento qui sotto`;setTimeout(()=>ub.hidden=true,6000)}
else{ubig.textContent="!";utxt.textContent="Errore: "+x.responseText}tick()};
// Network error.
x.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
// Cancel: abort the request and hide the card.
ucancel.onclick=()=>{x.abort();ub.hidden=true};
// File is sent as the raw request body.
x.open("POST","/upload?filename="+encodeURIComponent(f.name));x.send(f)}
// File picker upload; reset the input so the same file can be picked again.
up.onchange=()=>{if(up.files[0])send(up.files[0]);up.value=""};
// Dragging over the page: highlight the drop zone.
addEventListener("dragover",e=>{e.preventDefault();document.body.classList.add("drag")});
// Leaving the window (no relatedTarget) clears the highlight.
addEventListener("dragleave",e=>{if(!e.relatedTarget)document.body.classList.remove("drag")});
// Drop anywhere on the page: upload the first file.
addEventListener("drop",e=>{e.preventDefault();document.body.classList.remove("drag");const f=e.dataTransfer.files[0];if(f)send(f)});
// Refresh the whole UI from /status: header, LLM pickers, table.
async function tick(){try{const j=await (await fetch("/status")).json();ab.disabled=j.ask_blocked;ab.title=j.ask_blocked?"pipeline in corso":"";
// Browser tab title shows the progress of the first running pipeline.
const runp=j.recs.map(r=>r.prog).filter(p=>p&&p.pct!=null);document.title=runp.length?`${Math.round(runp[0].pct*100)}% · ${LBL[runp[0].step]} · Riunioni`:"Riunioni";
// Refill the LLM pickers from the server list; skip the focused one so the user's choice is not overwritten.
for(const [s,i,p] of [[llm,0,"shots: "],[llmr,1,"report: "],[llma,1,""]])if(document.activeElement!==s){s.innerHTML=j.llms[i].map(([k,l])=>`<option value=${k}>${p}${E(l)}`).join("");s.value=j.llm[i];s.disabled=j.busy}
// Skip-screenshots switch; disabled while busy.
skp.checked=j.skip_shots;skp.disabled=j.busy;
// omp login status: red and showing the error when logged out.
const o=j.omp;omps.innerHTML=!o.exe?`<span style="color:var(--redf)">omp non installato</span>`:[["github-copilot","Copilot"],["anthropic","Anthropic"]].map(([k,l])=>`<span title="${E(o[k]||"login valido")}"${o[k]?' style="color:var(--redf)"':""}>${o[k]?"✗":"✓"} ${l}</span>`).join(" · ");
// Queue size in the header.
qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:"";
// Remember step-select values so they survive the re-render.
document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value);
// Table header.
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
// One tbody per recording; "running" when the status is done but the process is still alive.
for(const r of j.recs){const st=r.running&&r.status=="done"?"running":r.status;
// Display title, falling back to the upload name.
const nm=r.title||r.upload;
// Main row: checkbox, title and rename buttons; status badge with error text and time since last data.
h+=`<tbody class=rec><tr class=main><td><input type=checkbox class=mg value="${r.name}">${nm?`<b>${E(nm)}</b><br><small>${r.name}</small>`:r.name} <button class=del title="modifica titolo" onclick="setTitle('${r.name}','${E(r.title||r.upload||"").replace(/'/g,"")}')">✎</button>${r.mb&&r.files.includes("report.html")?`<button class=del title="ricalcola titolo" onclick="retitle('${r.name}')">↻</button>`:""}<td><span class="b ${r.status}" title="${E(r.error)}">${r.status}</span>${r.receiving_age_s!=null&&r.status=="recording"?` <small>${r.receiving_age_s}s ago</small>`:""}${r.error?`<br><small>${E(r.error)}</small>`:""}<td>${r.duration_s?fmt(r.duration_s):""}<td>${r.speakers??""}<td>${r.mb}
<td>${r.files.includes("report.html")?`<a href="/report?name=${r.name}" target=_blank>report</a><a href="/pdf?name=${r.name}" target=_blank>pdf</a>`:""}${r.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${r.flow_run_id}" target=_blank>prefect</a>`:""}
<td>${r.mb?`<select id="f-${r.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(s=>`<option>${s}`).join("")}</select><button onclick="run('${r.name}')">run</button>`:""}<button onclick="spk('${r.name}')">speakers</button>${r.mb?`<button title="anteprima e ritaglio" onclick="play('${r.name}',${r.duration_s||0},'${E(nm||r.name).replace(/'/g,"")}')">▶ video</button>`:""}${r.mb&&r.status=="done"&&!r.running?`<button title="elimina solo il file video: report, trascrizione e schermate restano, ma non si può più rielaborare" onclick="dropVid('${r.name}',${r.mb})">🎞 elimina video</button>`:""}${r.running||r.status=="queued"?`<button onclick="stopRun('${r.name}')">stop</button>`:`<button class=del title="elimina la riunione" onclick="del_('${r.name}','${E(nm||r.name).replace(/'/g,"")}')">🗑</button>`}`;
h+=progPanel(r);
if(open_.has(r.name))h+=await panel(r.name);h+="</tbody>"}
// Re-render only when not editing a speaker field and no table input has focus, so user input is kept.
const ae=document.activeElement;if(!editing&&!(ae&&t.contains(ae)&&/^(INPUT|SELECT)$/.test(ae.tagName))){const ck=[...document.querySelectorAll(".mg:checked")].map(x=>x.value);t.innerHTML=h;for(const k in sel){const e=document.getElementById(k);if(e)e.value=sel[k]}document.querySelectorAll(".mg").forEach(x=>x.checked=ck.includes(x.value));upd()}}catch(e){}}
// Set while typing in a speaker name input.
let editing=false;t.addEventListener("input",e=>{if(e.target.dataset.n)editing=true});t.addEventListener("change",e=>{if(e.target.classList.contains("mg"))upd()});
// Initial load, then poll every 3 s.
tick();setInterval(tick,3000);