Apply ruff lint and rename cryptic identifiers to readable names

This commit is contained in:
Stefano Zini
2026-11-05 09:09:20 +01:00
parent 19de4654ff
commit ead33657c7
24 changed files with 4459 additions and 1856 deletions
+34 -9
View File
@@ -1,20 +1,45 @@
"""Cheap non-AI audio cleanup: mono 16k, highpass, loudnorm -> out/<name>/audio.opus.""" """Cheap non-AI audio cleanup: mono 16k, highpass, loudnorm -> out/<name>/audio.opus."""
import subprocess import subprocess
import db import db
# Convert the meeting's audio track to 16 kHz mono Opus (small, speech-optimised). # Convert the meeting's audio track to 16 kHz mono Opus (small, speech-optimised).
def run(name): def run(name):
src = db.media(name)[0] source_path = db.media(name)[0]
# No audio track: nothing to convert. # No audio track: nothing to convert.
if src is None: raise FileNotFoundError(f"no audio source for {name}") if source_path is None:
dst = db.out_dir(name) / "audio.opus" raise FileNotFoundError(f"no audio source for {name}")
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", output_path = db.out_dir(name) / "audio.opus"
result = subprocess.run(
[
"ffmpeg",
"-y",
"-v",
"error",
"-i",
str(source_path),
"-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. # 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)], "-af",
capture_output=True, text=True) "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11",
"-c:a",
"libopus",
"-b:a",
"24k",
str(output_path),
],
capture_output=True,
text=True,
)
# Surface the tail of ffmpeg's error output. # Surface the tail of ffmpeg's error output.
if r.returncode: raise RuntimeError(r.stderr[-500:]) if result.returncode:
raise RuntimeError(result.stderr[-500:])
# Store the duration probed from the output file. # Store the duration probed from the output file.
db.upsert_recording(name, duration_s=db.duration(dst)) db.upsert_recording(name, duration_s=db.duration(output_path))
return dst return output_path
+18 -11
View File
@@ -1,27 +1,34 @@
# Shared helpers: makes the CUDA DLLs findable and loads the Whisper model. # Shared helpers: makes the CUDA DLLs findable and loads the Whisper model.
import glob, os, site import glob
import os
import site
import numpy as np import numpy as np
# pip nvidia-* wheels ship cublas/cudnn DLLs; ctranslate2 needs them on PATH (Windows) # 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. # Each nvidia/<lib>/bin folder from the pip wheels is added to the DLL search path and PATH.
for sp in site.getsitepackages(): for site_packages in site.getsitepackages():
for b in glob.glob(os.path.join(sp, "nvidia", "*", "bin")): for bin_dir in glob.glob(os.path.join(site_packages, "nvidia", "*", "bin")):
os.add_dll_directory(b); os.environ["PATH"] = b + os.pathsep + os.environ["PATH"] os.add_dll_directory(bin_dir)
os.environ["PATH"] = bin_dir + os.pathsep + os.environ["PATH"]
# Import only after the DLL path is set up above, or CUDA libs fail to load. # Import only after the DLL path is set up above, or CUDA libs fail to load.
from faster_whisper import WhisperModel from faster_whisper import WhisperModel # noqa: E402
CORES = max(
1, (os.cpu_count() or 2) // 2
) # ponytail: logical/2 ~ physical cores (no psutil); exact count if hybrid CPUs need it
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): def load_model(name):
"""CUDA if it really works (probe one decode), else CPU int8.""" """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 CUDA first; the probe below forces the real CUDA libs to load now, so a missing DLL fails here.
try: try:
m = WhisperModel(name, device="cuda", compute_type="default") whisper_model = WhisperModel(name, device="cuda", compute_type="default")
# One second of silence forces an actual decode, not just a model load. # One second of silence forces an actual decode, not just a model load.
list(m.transcribe(np.zeros(16000, np.float32))[0]) list(whisper_model.transcribe(np.zeros(16000, np.float32))[0])
return m, "cuda" return whisper_model, "cuda"
except Exception as e: except Exception as error:
print("cuda failed, using cpu:", e, flush=True) print("cuda failed, using cpu:", error, flush=True)
# CPU fallback: int8 quantisation, CORES threads. # CPU fallback: int8 quantisation, CORES threads.
return WhisperModel(name, device="cpu", compute_type="int8", cpu_threads=CORES), "cpu" return WhisperModel(name, device="cpu", compute_type="int8", cpu_threads=CORES), "cpu"
+292 -112
View File
@@ -1,12 +1,20 @@
"""SQLite index of meetings (out/meetings.db) + shared helpers.""" """SQLite index of meetings (out/meetings.db) + shared helpers."""
import json, re, sqlite3, subprocess, time
import contextlib
import json
import re
import sqlite3
import subprocess
import time
from pathlib import Path from pathlib import Path
# Everything lives under out/ next to this file: the DB and per-meeting folders. # Everything lives under out/ next to this file: the DB and per-meeting folders.
HERE = Path(__file__).parent HERE = Path(__file__).parent
OUT = HERE / "out" OUT = HERE / "out"
DB = OUT / "meetings.db" DB = OUT / "meetings.db"
GLOBAL = OUT / "_global" # llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs, edge profile GLOBAL = (
OUT / "_global"
) # llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs, edge profile
GLOBAL.mkdir(parents=True, exist_ok=True) GLOBAL.mkdir(parents=True, exist_ok=True)
# SQLite schema, applied on every connect(). FTS5 tables back full-text search; # SQLite schema, applied on every connect(). FTS5 tables back full-text search;
@@ -30,7 +38,20 @@ CREATE TABLE IF NOT EXISTS memory(name TEXT, idx INTEGER, kind TEXT, t REAL, mee
CREATE INDEX IF NOT EXISTS memory_name ON memory(name); CREATE INDEX IF NOT EXISTS memory_name ON memory(name);
""" """
# Pipeline statuses written to recordings.status, in run order. # Pipeline statuses written to recordings.status, in run order.
STATUSES = ["recording", "queued", "audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory", "done", "error"] STATUSES = [
"recording",
"queued",
"audio",
"transcribing",
"diarizing",
"identifying",
"shots",
"docs",
"report",
"memory",
"done",
"error",
]
# Event kinds accepted in call_events (Teams web-call signals). # Event kinds accepted in call_events (Teams web-call signals).
EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "caption", "chat", "hand"} EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "caption", "chat", "hand"}
@@ -39,89 +60,131 @@ EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "captio
def connect() -> sqlite3.Connection: def connect() -> sqlite3.Connection:
OUT.mkdir(exist_ok=True) OUT.mkdir(exist_ok=True)
# Autocommit (isolation_level=None) so BEGIN/COMMIT below are explicit; wait up to 30 s on locks. # Autocommit (isolation_level=None) so BEGIN/COMMIT below are explicit; wait up to 30 s on locks.
c = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False) conn = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False)
# WAL: the GUI can read while the flow writes. # WAL: the GUI can read while the flow writes.
c.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA journal_mode=WAL")
c.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
# Idempotent: every CREATE uses IF NOT EXISTS. # Idempotent: every CREATE uses IF NOT EXISTS.
c.executescript(SCHEMA) conn.executescript(SCHEMA)
return c return conn
# Insert or update a recordings row; only the kwargs given are written. # Insert or update a recordings row; only the kwargs given are written.
def upsert_recording(name: str, **f): def upsert_recording(name: str, **fields):
c = connect() conn = connect()
cols = ["name", *f] cols = ["name", *fields]
# Empty kwargs -> "name=name" no-op, keeps the ON CONFLICT clause valid SQL. # 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" sets = ",".join(f"{column}=excluded.{column}" for column in fields) or "name=name"
c.execute(f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) " conn.execute(
f"ON CONFLICT(name) DO UPDATE SET {sets}", [name, *f.values()]) f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) "
f"ON CONFLICT(name) DO UPDATE SET {sets}",
[name, *fields.values()],
)
# Upsert status (and error) for a meeting; updated_at is SQLite UTC time. # Upsert status (and error) for a meeting; updated_at is SQLite UTC time.
def set_status(name: str, status: str, error: str | None = None): def set_status(name: str, status: str, error: str | None = None):
c = connect() conn = connect()
c.execute("INSERT INTO recordings(name,status,error,updated_at) VALUES(?,?,?,datetime('now')) " conn.execute(
"INSERT INTO recordings(name,status,error,updated_at) VALUES(?,?,?,datetime('now')) "
"ON CONFLICT(name) DO UPDATE SET status=excluded.status,error=excluded.error,updated_at=excluded.updated_at", "ON CONFLICT(name) DO UPDATE SET status=excluded.status,error=excluded.error,updated_at=excluded.updated_at",
(name, status, error)) (name, status, error),
)
# Replace all transcript lines of a meeting; rows are (t, speaker, text). # Replace all transcript lines of a meeting; rows are (t, speaker, text).
def replace_lines(name, rows): def replace_lines(name, rows):
c = connect() conn = connect()
c.execute("BEGIN") conn.execute("BEGIN")
c.execute("DELETE FROM lines WHERE name=?", (name,)) conn.execute("DELETE FROM lines WHERE name=?", (name,))
c.executemany("INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)", [(name, t, s, x) for t, s, x in rows]) conn.executemany(
c.execute("COMMIT") "INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)",
[(name, time_s, speaker, text) for time_s, speaker, text in rows],
)
conn.execute("COMMIT")
# Replace shots; shot_text is the FTS mirror of shots and must change with it. # Replace shots; shot_text is the FTS mirror of shots and must change with it.
def replace_shots(name, rows): def replace_shots(name, rows):
c = connect() conn = connect()
c.execute("BEGIN") conn.execute("BEGIN")
c.execute("DELETE FROM shots WHERE name=?", (name,)) conn.execute("DELETE FROM shots WHERE name=?", (name,))
c.execute("DELETE FROM shot_text WHERE name=?", (name,)) conn.execute("DELETE FROM shot_text WHERE name=?", (name,))
for r in rows: for shot in rows:
c.execute("INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)", conn.execute(
(name, r["t"], r.get("t_end"), r["file"], r.get("kind"), r.get("title"), r.get("app"), "INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)",
r.get("summary"), r.get("text"), json.dumps(r.get("entities") or {}, ensure_ascii=False))) (
name,
shot["t"],
shot.get("t_end"),
shot["file"],
shot.get("kind"),
shot.get("title"),
shot.get("app"),
shot.get("summary"),
shot.get("text"),
json.dumps(shot.get("entities") or {}, ensure_ascii=False),
),
)
# FTS body: extracted text plus LLM summary. # FTS body: extracted text plus LLM summary.
c.execute("INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)", conn.execute(
(name, r["t"], r.get("title") or "", f"{r.get('text') or ''}\n{r.get('summary') or ''}")) "INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)",
c.execute("COMMIT") (
name,
shot["t"],
shot.get("title") or "",
f"{shot.get('text') or ''}\n{shot.get('summary') or ''}",
),
)
conn.execute("COMMIT")
# Replace topics; each row also keeps the full topic dict as JSON. # Replace topics; each row also keeps the full topic dict as JSON.
def replace_topics(name, topics): def replace_topics(name, topics):
c = connect() conn = connect()
c.execute("BEGIN") conn.execute("BEGIN")
c.execute("DELETE FROM topics WHERE name=?", (name,)) conn.execute("DELETE FROM topics WHERE name=?", (name,))
c.executemany("INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)", conn.executemany(
[(name, i, t["title"], t.get("start_s"), t.get("end_s"), json.dumps(t, ensure_ascii=False)) for i, t in enumerate(topics)]) "INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)",
c.execute("COMMIT") [
(
name,
index,
topic["title"],
topic.get("start_s"),
topic.get("end_s"),
json.dumps(topic, ensure_ascii=False),
)
for index, topic in enumerate(topics)
],
)
conn.execute("COMMIT")
# Replace memory rows for a meeting (rows already carry vec bytes, see SCHEMA). # Replace memory rows for a meeting (rows already carry vec bytes, see SCHEMA).
def replace_memory(name, rows): def replace_memory(name, rows):
c = connect() conn = connect()
c.execute("BEGIN") conn.execute("BEGIN")
c.execute("DELETE FROM memory WHERE name=?", (name,)) conn.execute("DELETE FROM memory WHERE name=?", (name,))
c.executemany("INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)", rows) conn.executemany(
c.execute("COMMIT") "INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)",
rows,
)
conn.execute("COMMIT")
# Per-meeting folder out/<name>/, created on demand. # Per-meeting folder out/<name>/, created on demand.
def out_dir(name) -> Path: def out_dir(name) -> Path:
d = OUT / name folder = OUT / name
d.mkdir(parents=True, exist_ok=True) folder.mkdir(parents=True, exist_ok=True)
return d return folder
# Per-meeting logs folder (e.g. embed.log). # Per-meeting logs folder (e.g. embed.log).
def logs(name) -> Path: def logs(name) -> Path:
d = out_dir(name) / "logs" folder = out_dir(name) / "logs"
d.mkdir(exist_ok=True) folder.mkdir(exist_ok=True)
return d return folder
def meta(name) -> dict: def meta(name) -> dict:
@@ -129,36 +192,71 @@ def meta(name) -> dict:
return _jload(OUT / name / "meta.json", {}) return _jload(OUT / name / "meta.json", {})
def set_meta(name, **kw): def set_meta(name, **fields):
m = {**meta(name), **kw} merged = {**meta(name), **fields}
# Falsy values (None, "") are dropped rather than stored. # Falsy values (None, "") are dropped rather than stored.
_jsave(out_dir(name) / "meta.json", {k: v for k, v in m.items() if v}) _jsave(out_dir(name) / "meta.json", {key: value for key, value in merged.items() if value})
# ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ---- # ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ----
ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses ORDER = [
"audio",
"transcribing",
"diarizing",
"identifying",
"shots",
"docs",
"report",
"memory",
] # step statuses
# Flow step name -> GUI status it maps to (render and title roll into memory). # Flow step name -> GUI status it maps to (render and title roll into memory).
FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying", FROM = {
"shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory", "title": "memory"} "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. # Learned speeds, merged over SPM at runtime.
STATS = GLOBAL / "step_stats.json" 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); # 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>") # replaced by a moving average of real runs as soon as one finishes (keys "<step>" or "<step>@<model>")
SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30, SPM = {
"docs": 2, "report@qwen35b": 21, "report@qwen4b": 7, "report": 15, "memory": 1} "audio": 1,
"transcribing": 6,
"diarizing": 9,
"identifying": 1,
"shots@qwen4b": 23,
"shots@qwen35b": 48,
"shots": 30,
"docs": 2,
"report@qwen35b": 21,
"report@qwen4b": 7,
"report": 15,
"memory": 1,
}
# Read JSON; missing or corrupt file -> default. # Read JSON; missing or corrupt file -> default.
def _jload(p, default): def _jload(path, default):
try: return json.loads(p.read_text(encoding="utf-8")) try:
except (OSError, ValueError): return default return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return default
# Write JSON via a temp file then rename, so readers never see a partial file. # Write JSON via a temp file then rename, so readers never see a partial file.
def _jsave(p, o): def _jsave(path, data):
tmp = p.with_suffix(".tmp"); tmp.write_text(json.dumps(o), encoding="utf-8") tmp_path = path.with_suffix(".tmp")
try: tmp.replace(p) tmp_path.write_text(json.dumps(data), encoding="utf-8")
except OSError: pass # reader had it open: next tick writes again # reader had it open: next tick writes again
with contextlib.suppress(OSError):
tmp_path.replace(path)
# Seconds of work per audio minute for a step; a measured value beats the default. # Seconds of work per audio minute for a step; a measured value beats the default.
@@ -169,9 +267,19 @@ def spm(key):
def delete_recording(name): def delete_recording(name):
"""Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out/<name>/.""" """Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out/<name>/."""
import shutil import shutil
c = connect()
for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"): conn = connect()
c.execute(f"DELETE FROM {t} WHERE name=?", (name,)) for table in (
"recordings",
"lines",
"shots",
"shot_text",
"topics",
"call_events",
"speaker_map",
"memory",
):
conn.execute(f"DELETE FROM {table} WHERE name=?", (name,))
shutil.rmtree(OUT / name, ignore_errors=True) shutil.rmtree(OUT / name, ignore_errors=True)
@@ -182,82 +290,149 @@ def progress(name):
# Fresh progress.json for a run; 'start' is the first step to execute (via FROM). # Fresh progress.json for a run; 'start' is the first step to execute (via FROM).
def progress_start(name, start_from): def progress_start(name, start_from):
now = time.time() now = time.time()
_jsave(out_dir(name) / "progress.json", {"run_start": now, "start": FROM.get(start_from, "audio"), "step": None, "key": None, _jsave(
"step_start": now, "done": 0, "total": 0, "note": "", "updated": now, "steps": []}) out_dir(name) / "progress.json",
{
"run_start": now,
"start": FROM.get(start_from, "audio"),
"step": None,
"key": None,
"step_start": now,
"done": 0,
"total": 0,
"note": "",
"updated": now,
"steps": [],
},
)
def step(name, status, key=None): def step(name, status, key=None):
"""Close the previous step (learn its speed), open `status` ("done" closes the run).""" """Close the previous step (learn its speed), open `status` ("done" closes the run)."""
set_status(name, status) set_status(name, status)
p = progress(name) state = progress(name)
if not p: return if not state:
return
now = time.time() now = time.time()
if p["step"]: if state["step"]:
p["steps"].append([p["step"], p["step_start"], now]) state["steps"].append([state["step"], state["step_start"], now])
row = connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() row = (
connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
)
mins = (row[0] or 0) / 60 if row else 0 mins = (row[0] or 0) / 60 if row else 0
if mins > 1 and now - p["step_start"] > 5: # skip no-op steps if mins > 1 and now - state["step_start"] > 5: # skip no-op steps
# Learn speed (seconds per audio minute); exponential average with the previous value. # 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 stats = _jload(STATS, {})
st[k] = round(v if k not in st else 0.5 * st[k] + 0.5 * v, 2); _jsave(STATS, st) stat_key = state["key"] or state["step"]
speed = (now - state["step_start"]) / mins
stats[stat_key] = round(
speed if stat_key not in stats else 0.5 * stats[stat_key] + 0.5 * speed, 2
)
_jsave(STATS, stats)
# 'done' clears step so the GUI shows the run as finished. # '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) state.update(
_jsave(OUT / name / "progress.json", p) step=None if status == "done" else status,
key=key or status,
step_start=now,
done=0,
total=0,
note="",
updated=now,
)
_jsave(OUT / name / "progress.json", state)
def tick(name, done, total, note=""): def tick(name, done, total, note=""):
"""In-step progress; also the heartbeat the GUI uses to show the run is alive.""" """In-step progress; also the heartbeat the GUI uses to show the run is alive."""
p = progress(name) state = progress(name)
if not p: return if not state:
return
now = time.time() now = time.time()
if done == 0 and total: p["t0"] = now # loop starts now: rate excludes model load / frame extraction before it if done == 0 and total:
p.update(done=done, total=total, note=note, updated=now) state["t0"] = now # loop starts now: rate excludes model load / frame extraction before it
_jsave(OUT / name / "progress.json", p) state.update(done=done, total=total, note=note, updated=now)
_jsave(OUT / name / "progress.json", state)
def media(name): def media(name):
"""(audio source, video source) in out/<name>/: source.<ext> (the CLI recorder may write source.wav + source.mp4); .wav/.m4a/.mp3 have no video.""" """(audio source, video source) in out/<name>/: source.<suffix> (the CLI recorder may write source.wav + source.mp4); .wav/.m4a/.mp3 have no video."""
# First existing candidate wins (order = preference). # First existing candidate wins (order = preference).
def first(*exts): def first(*exts):
for e in exts: for suffix in exts:
p = OUT / name / f"source{e}" candidate = OUT / name / f"source{suffix}"
if p.exists(): return p if candidate.exists():
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov") return candidate
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(
".webm", ".mp4", ".mkv", ".mov"
)
def duration(path) -> float: def duration(path) -> float:
"""Seconds. MediaRecorder webm has no container duration (N/A): fall back to a copy-demux pass (~1 s/h).""" """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). # 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)], probe = subprocess.run(
capture_output=True, text=True) ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
try: return float(p.stdout.strip()) capture_output=True,
except ValueError: pass text=True,
)
try:
return float(probe.stdout.strip())
except ValueError:
pass
# Slow path: decode the whole stream with -c copy; ffmpeg prints time= progress to stderr. # 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", "-"], result = subprocess.run(
capture_output=True, text=True) [
"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). # 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) times = re.findall(r"time=(\d+):(\d\d):(\d\d(?:\.\d+)?)", result.stderr)
if not m: raise ValueError(((p.stderr or r.stderr).strip() or "nessuna durata")[-300:]) if not times:
h, mi, s = m[-1] raise ValueError(((probe.stderr or result.stderr).strip() or "nessuna durata")[-300:])
return int(h) * 3600 + int(mi) * 60 + float(s) hours, minutes, seconds = times[-1]
return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
def add_events(name, rows): def add_events(name, rows):
connect().executemany("INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)", connect().executemany(
[(name, *r) for r in rows]) "INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
[(name, *row) for row in rows],
)
def events(name, *kinds): def events(name, *kinds):
q = "SELECT * FROM call_events WHERE name=?" query = "SELECT * FROM call_events WHERE name=?"
# Optional kind filter; ORDER BY t gives timeline order. # Optional kind filter; ORDER BY t gives timeline order.
if kinds: q += f" AND kind IN ({','.join('?' * len(kinds))})" if kinds:
return connect().execute(q + " ORDER BY t", (name, *kinds)).fetchall() query += f" AND kind IN ({','.join('?' * len(kinds))})"
return connect().execute(query + " ORDER BY t", (name, *kinds)).fetchall()
def speaker_names(name) -> dict: def speaker_names(name) -> dict:
# Only real names: an empty or NULL person keeps the raw speaker label. # Only real names: an empty or NULL person keeps the raw speaker label.
return {r["label"]: r["person"] for r in connect().execute( return {
"SELECT label,person FROM speaker_map WHERE name=? AND person<>'' AND person IS NOT NULL", (name,))} row["label"]: row["person"]
for row in connect().execute(
"SELECT label,person FROM speaker_map WHERE name=? AND person<>'' AND person IS NOT NULL",
(name,),
)
}
# Upsert speaker label -> person, with its source (auto/manual) and overlap seconds. # Upsert speaker label -> person, with its source (auto/manual) and overlap seconds.
@@ -266,14 +441,19 @@ def set_speaker_map(name, label, person, source, overlap_s=None):
"INSERT INTO speaker_map(name,label,person,source,overlap_s) VALUES(?,?,?,?,?) " "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 " "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. # Manual names win; automatic matches never overwrite them.
"WHERE speaker_map.source != 'manual' OR excluded.source = 'manual'", (name, label, person, source, overlap_s)) "WHERE speaker_map.source != 'manual' OR excluded.source = 'manual'",
(name, label, person, source, overlap_s),
)
def norm_name(raw: str) -> str: def norm_name(raw: str) -> str:
"""Port of norm() in ext/teams.js: 'Rossi, MARIO (IG/S-32)' -> 'Mario Rossi'.""" """Port of norm() in suffix/teams.js: 'Rossi, MARIO (IG/S-32)' -> 'Mario Rossi'."""
raw = (raw or "").strip() raw = (raw or "").strip()
# Groups: "Last, First" plus an optional trailing "(...)" suffix, which is dropped. # Groups: "Last, First" plus an optional trailing "(...)" suffix, which is dropped.
m = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw) match = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw)
if not m: return raw if not match:
return raw
# Title-case only ALL-CAPS words; mixed-case words are kept as written. # Title-case only ALL-CAPS words; mixed-case words are kept as written.
return " ".join(w.title() if w.isupper() else w for w in f"{m[2]} {m[1]}".split()) return " ".join(
word.title() if word.isupper() else word for word in f"{match[2]} {match[1]}".split()
)
+118 -41
View File
@@ -1,11 +1,17 @@
"""Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled).""" """Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled)."""
import json, os, re, subprocess, time
import json
import os
import re
import subprocess
import time
from pathlib import Path from pathlib import Path
import numpy as np
import db import db
import numpy as np
# Model files shipped under app/models/. # Model files shipped under app/models/.
M = Path(__file__).parent / "models" MODEL_DIR = 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. # 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. # CUDA measured slower (>7 min, GPU ~5 W): tiny models + one embedding per segment -> transfer/launch overhead dominates.
THREADS = max(1, (os.cpu_count() or 2) // 2) THREADS = max(1, (os.cpu_count() or 2) // 2)
@@ -14,7 +20,13 @@ THREADS = max(1, (os.cpu_count() or 2) // 2)
def roster_size(name, default=5): 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).""" """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}. # 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")} who = {
person["who"]
for event in db.events(name, "present")
if event["who_key"] != "video"
for person in json.loads(event["text"] or "[]")
if person.get("who")
}
# Clamp the cluster count to 2-12; no roster -> default. # Clamp the cluster count to 2-12; no roster -> default.
return min(max(len(who), 2), 12) if who else default return min(max(len(who), 2), 12) if who else default
@@ -24,66 +36,131 @@ def run(name, speakers=0, threshold=0.85):
speakers = speakers or roster_size(name) speakers = speakers or roster_size(name)
# Imported here so the module loads without sherpa-onnx installed. # Imported here so the module loads without sherpa-onnx installed.
import sherpa_onnx import sherpa_onnx
src = db.out_dir(name) / "audio.opus"
source_path = db.out_dir(name) / "audio.opus"
# Decode audio to 16 kHz mono float32 (sherpa input format). # 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", "-"], pcm_bytes = subprocess.run(
capture_output=True, check=True).stdout [
audio = np.frombuffer(raw, np.float32) "ffmpeg",
"-v",
"error",
"-i",
str(source_path),
"-vn",
"-ac",
"1",
"-ar",
"16000",
"-f",
"f32le",
"-",
],
capture_output=True,
check=True,
).stdout
audio = np.frombuffer(pcm_bytes, np.float32)
# Pyannote segmentation + speaker embedding + clustering. # Pyannote segmentation + speaker embedding + clustering.
sd = sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig( diarizer = sherpa_onnx.OfflineSpeakerDiarization(
sherpa_onnx.OfflineSpeakerDiarizationConfig(
segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig( segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")), pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(
num_threads=THREADS), model=str(MODEL_DIR / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS), ),
num_threads=THREADS,
),
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(
model=str(MODEL_DIR / "emb.onnx"), num_threads=THREADS
),
# num_clusters > 0 fixes the speaker count and overrides threshold. # num_clusters > 0 fixes the speaker count and overrides threshold.
clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold), clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold),
# Drop blips under 0.3 s and merge gaps under 0.5 s. # Drop blips under 0.3 s and merge gaps under 0.5 s.
min_duration_on=0.3, min_duration_off=0.5)) min_duration_on=0.3,
min_duration_off=0.5,
)
)
# Last printed decile, so progress prints every 10 %. # Last printed decile, so progress prints every 10 %.
t0, last = time.time(), [-1] start_time, last_decile = time.time(), [-1]
def progress(done, total): # sherpa calls this per processed chunk; print every 10 % def progress(done, total): # sherpa calls this per processed chunk; print every 10 %
pct = done * 100 // max(total, 1) percent = 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) if percent // 10 > last_decile[0]:
last_decile[0] = percent // 10
print(
f"diarize {percent}% ({done}/{total}, {time.time() - start_time:.0f} s)", flush=True
)
# Update DB progress every 20 chunks (and at the end) to limit writes. # 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") if done % 20 == 0 or done == total:
db.tick(name, done, total, "impronte vocali dei segmenti")
return 0 return 0
# Status for the GUI before the slow segmentation starts. # Status for the GUI before the slow segmentation starts.
db.tick(name, 0, 0, "segmentazione dell'audio (~1-2 min)") db.tick(name, 0, 0, "segmentazione dell'audio (~1-2 min)")
# Run diarization; segments come back sorted by start time. # 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()] segments = [
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True) (segment.start, segment.end, segment.speaker)
for segment in diarizer.process(audio, callback=progress).sort_by_start_time()
]
print(
len(segments),
"segments,",
len({segment[2] for segment in segments}),
f"speakers ({time.time() - start_time:.0f} s)",
flush=True,
)
lines = [] lines = []
# Parse transcript lines '[mm:ss] text' into (seconds, text). # Parse transcript lines '[mm:ss] text' into (seconds, text).
for l in (db.out_dir(name) / "transcript.txt").read_text(encoding="utf-8").splitlines(): for line in (db.out_dir(name) / "transcript.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l) match = re.match(r"\[(\d+):(\d+)\] (.*)", line)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3])) if match:
lines.append((int(match[1]) * 60 + int(match[2]), match[3]))
# order: first-appearance numbering of speakers, for 'Speaker N' labels. # order: first-appearance numbering of speakers, for 'Speaker N' labels.
out, order = [], {} labelled, order = [], {}
for i, (t, text) in enumerate(lines): for index, (time_s, text) in enumerate(lines):
# A line lasts until the next line starts; the last line is assumed 5 s. # 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 next_time = lines[index + 1][0] if index + 1 < len(lines) else time_s + 5
ov = {} overlap_by_speaker = {}
# Total overlap of each diarized segment with this line's window. # Total overlap of each diarized segment with this line's window.
for s, e, sp in segs: for seg_start, seg_end, speaker in segments:
o = min(e, t1) - max(s, t) overlap = min(seg_end, next_time) - max(seg_start, time_s)
if o > 0: ov[sp] = ov.get(sp, 0) + o if overlap > 0:
overlap_by_speaker[speaker] = overlap_by_speaker.get(speaker, 0) + overlap
# Pick the speaker with the most overlap (None if no overlap). # Pick the speaker with the most overlap (None if no overlap).
sp = max(ov, key=ov.get) if ov else None speaker = (
max(overlap_by_speaker, key=overlap_by_speaker.get) if overlap_by_speaker else None
)
# Number speakers by first appearance in the text. # Number speakers by first appearance in the text.
if sp is not None: order.setdefault(sp, len(order) + 1) if speaker is not None:
order.setdefault(speaker, len(order) + 1)
# same speaker continues: one paragraph, but cut every 60 s so the timestamps stay usable (one 11-min paragraph # 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) # stamped 28:52 made every model end the report there)
if out and out[-1][1] == sp and t - out[-1][0] < 60: out[-1][2] += " " + text if labelled and labelled[-1][1] == speaker and time_s - labelled[-1][0] < 60:
else: out.append([t, sp, text]) labelled[-1][2] += " " + text
else:
labelled.append([time_s, speaker, text])
# labels by first appearance in the text; clusters never seen in text get the following numbers # labels by first appearance in the text; clusters never seen in text get the following numbers
for s in sorted(segs): for segment in sorted(segments):
order.setdefault(s[2], len(order) + 1) order.setdefault(segment[2], len(order) + 1)
# Save raw diarized segments as JSON. # Save pcm_bytes diarized segments as JSON.
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps( (db.out_dir(name) / "diar_segments.json").write_text(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8") json.dumps(
[
{"start": seg_start, "end": seg_end, "label": f"Speaker {order[speaker]}"}
for seg_start, seg_end, speaker in segments
]
),
encoding="utf-8",
)
# Replace DB transcript lines with speaker-labelled ones. # 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]) db.replace_lines(
name,
[
(time_s, f"Speaker {order[speaker]}" if speaker is not None else None, text)
for time_s, speaker, text in labelled
],
)
# Count of speakers actually present in the text. # Count of speakers actually present in the text.
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None})) db.upsert_recording(
print("saved", len(out), "speaker-labelled lines") name, speakers=len({speaker for _, speaker, _ in labelled if speaker is not None})
)
print("saved", len(labelled), "speaker-labelled lines")
+221 -79
View File
@@ -1,7 +1,16 @@
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow.""" """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
import contextlib
import json
import os
import re
import shutil
import subprocess
# report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address. # report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address.
import db, llama, report import db
import llama
import report
# twg CLI: from PATH, else the default per-user install location. # 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") TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
@@ -19,21 +28,45 @@ PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
# Retries once through the proxy when the failure looks like a network/proxy error. # Retries once through the proxy when the failure looks like a network/proxy error.
def _twg(*args, timeout=120): def _twg(*args, timeout=120):
# Child env without Python home vars that would confuse twg. # 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")} env = {
key: value
for key, value in os.environ.items()
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
}
for attempt in range(2): for attempt in range(2):
r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env) result = 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. # JSON mode: parse stdout; twg may instead print a YAML envelope pointing at a spooled file.
if "-o" in args and "json" in args: if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON try:
except ValueError: out = None return json.loads(
result.stdout
) # rovo exits 3 on partial results but still prints JSON
except ValueError:
output = None
# twg >= 1.3 spools large results to a file and prints a YAML envelope: output_files: stdout: "<path>" # twg >= 1.3 spools large results to a file and prints a YAML envelope: output_files: stdout: "<path>"
if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)): if match := re.search(r'^\s*stdout:\s*"(.+?\.json)"', result.stdout, re.M):
try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read()) try:
except (OSError, ValueError): pass return json.loads(open(match[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError):
pass
# Plain-text mode: stdout only on success. # Plain-text mode: stdout only on success.
else: out = r.stdout if r.returncode == 0 else None else:
output = result.stdout if result.returncode == 0 else None
# Stop unless this is the first attempt and stderr looks like a network/proxy error. # 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 if (
output is not None
or attempt
or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", result.stderr)
):
return output
# Second attempt goes through the proxy. # Second attempt goes through the proxy.
env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY} env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY}
@@ -41,115 +74,224 @@ def _twg(*args, timeout=120):
# Gather candidate docs for a meeting: queries, Confluence/Jira search, Jira key lookups, LLM relevance scoring. # 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). # Returns the docs.json payload; raises on hard failure (run() catches it).
def _run(name): def _run(name):
if not os.path.exists(TWG): raise FileNotFoundError("twg not found") if not os.path.exists(TWG):
raise FileNotFoundError("twg not found")
# Per-meeting output directory. # Per-meeting output directory.
d = db.out_dir(name) meeting_dir = 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 meta = [
json.loads(entry["text"])
for entry in db.events(name, "meta")
if entry["who_key"] != "video"
] # Teams topic only, never a shot guess
title = (meta[-1].get("title") or "") if meta else "" 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 [] shots = (
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else [] json.loads((meeting_dir / "shots.json").read_text(encoding="utf-8"))
if (meeting_dir / "shots.json").exists()
else []
)
glossary = (
json.loads((meeting_dir / "glossary.json").read_text(encoding="utf-8"))
if (meeting_dir / "glossary.json").exists()
else []
)
from shots import CONTENT_KINDS from shots import CONTENT_KINDS
# Titles of lead content screens: deduped, max 30. # 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] screens = list(
tx = db.out_dir(name) / "transcript.txt" dict.fromkeys(
txt = tx.read_text(encoding="utf-8") if tx.exists() else "" shot["title"]
for shot in shots
if shot.get("lead") and shot["kind"] in CONTENT_KINDS and shot.get("title")
)
)[:30]
transcript_file = db.out_dir(name) / "transcript.txt"
transcript = transcript_file.read_text(encoding="utf-8") if transcript_file.exists() else ""
# Meeting description for the LLM: title, screen titles, glossary, first 800 words of transcript. # 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])}" desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(glossary[:40])}\nTrascrizione (inizio): {' '.join(transcript.split()[:800])}"
# Title is always a query; add up to 4 LLM-generated ones. # Title is always a query; add up to 4 LLM-generated ones.
queries = [title] if title else [] 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)] queries += [
query
for query in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4]
if isinstance(query, str)
]
# Case-insensitive de-dup of queries. # Case-insensitive de-dup of queries.
queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1] queries = list({query.lower(): query for query in reversed(queries)}.values())[::-1]
# Candidates keyed by URL across all queries. # Candidates keyed by URL across all queries.
cand = {} candidates = {}
for q in queries: for query in queries:
# Confluence: up to 6 hits per query; Jira: up to 4. # Confluence: up to 6 hits per query; Jira: up to 4.
for app, lim in (("confluence", 6), ("jira", 4)): for source_app, limit in (("confluence", 6), ("jira", 4)):
for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []: for item in (
_twg(
"rovo",
"search",
query,
"--app",
source_app,
"--limit",
str(limit),
"-o",
"json",
)
or {}
).get("items") or []:
# Skip results without a URL or already seen. # Skip results without a URL or already seen.
u = it.get("url") url = item.get("url")
if not u or u in cand: continue if not url or url in candidates:
continue
# Jira key from /browse/KEY-N URLs; Confluence page id from /pages/ID URLs. # 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) jira_match = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", url)
cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None, confluence_match = re.search(r"/pages/(\d+)", url)
"title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False} candidates[url] = {
items = list(cand.values()) "source": "jira" if "/browse/" in url else "confluence",
"key": jira_match[1] if jira_match else None,
"id": confluence_match[1] if confluence_match else None,
"title": item.get("title") or "",
"url": url,
"status": None,
"snippet": (item.get("snippet") or "")[:400],
"mentioned": False,
}
items = list(candidates.values())
# Text to scan for ticket keys: transcript plus shot OCR text. # Text to scan for ticket keys: transcript plus shot OCR text.
blob = [txt] + [s.get("text") or "" for s in shots] text_blocks = [transcript] + [shot.get("text") or "" for shot in shots]
# Ticket keys found in the content (valid format), then keys already on candidates. # 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 = [
keys += [k for k in (e["key"] for e in items) if k and k not in keys] key
for key in dict.fromkeys(
ticket for block in text_blocks for ticket in report.TICKET.findall(block)
)
if KEY.match(key)
]
keys += [key for key in (entry["key"] for entry in items) if key and key not in keys]
# Keys literally mentioned in the meeting content. # 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)}) mentioned = {
key
for key in keys
if key in {ticket for block in text_blocks for ticket in report.TICKET.findall(block)}
}
# Jira lookup: summary + status for keys, one batch of up to 26. # Jira lookup: summary + status for keys, one batch of up to 26.
known = {} known = {}
# Only call twg when there are keys. # Only call twg when there are keys.
if keys[:20 + 6]: if keys[: 20 + 6]:
r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {} response = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for it in (r.get("data") or {}).get("items") or []: for item in (response.get("data") or {}).get("items") or []:
if it.get("ok") and it.get("data"): if item.get("ok") and item.get("data"):
x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "") data = item["data"]
known[data["key"]] = (
data.get("summary") or "",
(data.get("status") or {}).get("name") or "",
)
# Apply Jira summary/status to candidates that have a key. # Apply Jira summary/status to candidates that have a key.
for e in items: for entry in items:
if e["key"] in known: e["title"], e["status"] = known[e["key"]] if entry["key"] in known:
entry["title"], entry["status"] = known[entry["key"]]
# Add mentioned Jira tickets not already in items. # Add mentioned Jira tickets not already in items.
have = {e["key"] for e in items if e["key"]} have = {entry["key"] for entry in items if entry["key"]}
for k in keys: for key in keys:
if k in known and k in mentioned and k not in have: if key in known and key in mentioned and key 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}) items.append(
{
"source": "jira",
"key": key,
"id": None,
"title": known[key][0],
"url": f"{report.JIRA_BROWSE}/{key}",
"status": known[key][1],
"snippet": "",
"mentioned": True,
}
)
# Flag items mentioned in the meeting and resolved in Jira. # 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) for entry in items:
entry["mentioned"] = entry["mentioned"] or bool(
entry["key"] in mentioned and entry["key"] in known
)
# Relevance: LLM scores non-mentioned items; missing score = 0. # Relevance: LLM scores non-mentioned items; missing score = 0.
scores = {} scores = {}
rel = [e for e in items if not e["mentioned"]] unscored = [entry for entry in items if not entry["mentioned"]]
# Only score non-mentioned items, if any. # Only score non-mentioned items, if any.
if rel: if unscored:
# Numbered candidate list appended to the meeting description. # 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)) prompt = (
# Score indices refer to positions in rel. desc
for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []: + "\n\nDOCUMENTI:\n"
try: scores[int(s["i"])] = int(s["score"]) + "\n".join(
except (KeyError, TypeError, ValueError): pass f"[{index}] {entry['title']} — {entry['snippet'][:300]}"
for index, entry in enumerate(unscored)
)
)
# Score indices refer to positions in unscored.
for score_row in (report.chat(SYS_R, prompt, 800) or {}).get("scores") or []:
with contextlib.suppress(KeyError, TypeError, ValueError):
scores[int(score_row["i"])] = int(score_row["score"])
# Non-mentioned items keep the LLM score (0 if missing). # Non-mentioned items keep the LLM score (0 if missing).
for i, e in enumerate(rel): e["score"] = scores.get(i, 0) for index, entry in enumerate(unscored):
entry["score"] = scores.get(index, 0)
# Mentioned items score 3 unless already set. # Mentioned items score 3 unless already set.
for e in items: for entry in items:
e.setdefault("score", 3 if e["mentioned"] else 0) entry.setdefault("score", 3 if entry["mentioned"] else 0)
# Keep mentioned items plus those scored >= 2, best first. # 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"]) keep = sorted(
[entry for entry in items if entry["mentioned"] or entry["score"] >= 2],
key=lambda entry: -entry["score"],
)
# Cap per source: 8 Confluence; Jira: up to 6 non-mentioned plus all mentioned. # 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] confluence_items = [entry for entry in keep if entry["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"]] jira_items = [entry for entry in keep if entry["source"] == "jira" and not entry["mentioned"]][
keep = conf + jira :6
] + [entry for entry in keep if entry["mentioned"]]
keep = confluence_items + jira_items
# Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body. # Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body.
for e in keep: for entry in keep:
if e["source"] == "confluence" and e["id"]: if entry["source"] == "confluence" and entry["id"]:
b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or "" body = (
_twg(
"confluence",
"content",
"get",
entry["id"],
"--detail",
"full",
"--format",
"md",
"--body-only",
)
or ""
)
# twg prefixes the body with a "Content loaded." banner line; drop it. # twg prefixes the body with a "Content loaded." banner line; drop it.
lines = b.splitlines() lines = body.splitlines()
if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:] if lines and lines[0].strip() == "+ Content loaded.":
e["body"] = "\n".join(lines)[:6000] lines = lines[1:]
else: e["body"] = f"{e['key']} {e['title']} ({e['status']})" entry["body"] = "\n".join(lines)[:6000]
else:
entry["body"] = f"{entry['key']} {entry['title']} ({entry['status']})"
# Stable index used to reference docs from report.py. # Stable index used to reference docs from report.py.
for i, e in enumerate(keep): e["i"] = i for index, entry in enumerate(keep):
entry["i"] = index
# People names: checkbox lines in bodies, multi-word only, deduped. # People names: checkbox lines in bodies, multi-word only, deduped.
people = [] people = []
for e in keep: for entry in keep:
for m in PEOPLE.finditer(e["body"]): for match in PEOPLE.finditer(entry["body"]):
n = db.norm_name(m[1]) person = db.norm_name(match[1])
if " " in n and n not in people: people.append(n) if " " in person and person not in people:
people.append(person)
return {"queries": queries, "items": keep, "people": people, "error": None} 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. # Entry point. Never fails the flow: errors are recorded in docs.json (error field) instead of raised.
def run(name): def run(name):
try: out = _run(name) try:
except Exception as e: output = _run(name)
print("docs failed:", repr(e), flush=True) except Exception as error:
out = {"queries": [], "items": [], "people": [], "error": repr(e)[:300]} print("docs failed:", repr(error), flush=True)
(db.out_dir(name) / "docs.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8") output = {"queries": [], "items": [], "people": [], "error": repr(error)[:300]}
(db.out_dir(name) / "docs.json").write_text(
json.dumps(output, ensure_ascii=False, indent=1), encoding="utf-8"
)
+6 -6
View File
@@ -1,13 +1,13 @@
// Make Teams see Edge instead of Opera: rewrite UA + client-hint request headers. // 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. // 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; const userAgent = navigator.userAgent;
// Chrome major version taken from the UA; falls back to 130 if the UA has no Chrome token. // 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 chromeMajor = (userAgent.match(/Chrome\/(\d+)/) || [])[1] || "130";
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`; const edgeUA = userAgent.replace(/ OPR\/[\d.]+/, "") + ` Edg/${chromeMajor}.0.0.0`;
// Sec-CH-UA brand list matching the Edge UA; "Not_A Brand" is a GREASE placeholder brand. // 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"`; const brands = `"Microsoft Edge";v="${chromeMajor}", "Chromium";v="${chromeMajor}", "Not_A Brand";v="24"`;
// Helper: builds one declarativeNetRequest header operation. // Helper: builds one declarativeNetRequest header operation.
const set = (header, value) => ({ header, operation: "set", value }); const headerSet = (header, value) => ({ header, operation: "set", value });
// Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start. // Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start.
chrome.declarativeNetRequest.updateDynamicRules({ chrome.declarativeNetRequest.updateDynamicRules({
@@ -19,7 +19,7 @@ chrome.declarativeNetRequest.updateDynamicRules({
// Rewrite the outgoing request headers. // Rewrite the outgoing request headers.
action: { action: {
type: "modifyHeaders", type: "modifyHeaders",
requestHeaders: [set("User-Agent", edgeUA), set("Sec-CH-UA", brands)], requestHeaders: [headerSet("User-Agent", edgeUA), headerSet("Sec-CH-UA", brands)],
}, },
condition: { condition: {
// Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft. // Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft.
+2 -2
View File
@@ -1,6 +1,6 @@
// Run in mic.html (a normal tab): asks for mic permission once so offscreen.js can use it later without a prompt. // 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 }) navigator.mediaDevices.getUserMedia({ audio: true })
// Stop the probe tracks at once: only the permission grant was needed, not the audio. // 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."); }) .then(stream => { stream.getTracks().forEach(track => track.stop()); document.body.append(" granted."); })
// Show the outcome in the page (the error text if the user denied or the call failed). // Show the outcome in the page (the error text if the user denied or the call failed).
.catch(e => document.body.append(" " + e)); .catch(error => document.body.append(" " + error));
+45 -45
View File
@@ -1,79 +1,79 @@
// Offscreen document: records the Teams tab (tabCapture) and uploads 10 s WebM chunks to the local server. // 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. // Local server endpoint (server.py); must match start.js port 18765.
const API = "http://127.0.0.1:18765"; const API = "http://127.0.0.1:18765";
let rec, ctx, tab, mic, q = Promise.resolve(), name; let recorder, audioContext, tabStream, micStream, uploadQueue = Promise.resolve(), recordingName;
// state: idle | recording | transcribing | done | error ; popup polls it // state: idle | recording | transcribing | done | error ; popup polls it
const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" }; const recorderState = { 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. // Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored.
chrome.runtime.onMessage.addListener((m, _s, send) => { chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (m.to !== "off") return; if (message.to !== "off") return;
if (m.cmd === "status") send(S); if (message.cmd === "status") sendResponse(recorderState);
// start is async: reply with ok, or with the error text (also stored in S for the popup). // start is async: reply with ok, or with the error text (also stored in recorderState 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) }); }); if (message.cmd === "start") start(message.id, message.tabId).then(() => sendResponse({ ok: true }), error => { recorderState.state = "error"; recorderState.text = String(error); sendResponse({ err: String(error) }); });
// teams.js events are re-based to seconds since recording start; events from before start are dropped. // 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 }); } if (message.cmd === "events") { for (const event of message.events) if (event.ts >= recorderState.t0) recorderState.ev.push({ t: (event.ts - recorderState.t0) / 1000, kind: event.kind, who_key: event.who_key, who: event.who, text: event.text }); }
// Stop: MediaRecorder.onstop handles the finalisation. // Stop: MediaRecorder.onstop handles the finalisation.
if (m.cmd === "stop") { rec.stop(); send({ ok: true }); } if (message.cmd === "stop") { recorder.stop(); sendResponse({ ok: true }); }
// Keep the message channel open for the async replies above. // Keep the message channel open for the async replies above.
return true; return true;
}); });
// Send buffered Teams events to the server; on failure count it so the popup can warn. // Send buffered Teams events to the server; on failure count it so the popup can warn.
async function flushEv() { async function flushEv() {
if (!S.ev.length) return; if (!recorderState.ev.length) return;
const b = S.ev.splice(0); const batch = recorderState.ev.splice(0);
try { try {
const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) }); const response = await fetch(`${API}/events?name=${recordingName}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(batch) });
if (!r.ok) throw 0; if (!response.ok) throw 0;
S.evSent += b.length; recorderState.evSent += batch.length;
} catch { S.failed++; } } catch { recorderState.failed++; }
} }
// Start recording the given tab (id from tabCapture.getMediaStreamId). // Start recording the given tab (id from tabCapture.getMediaStreamId).
async function start(id, tabId) { async function start(streamId, tabId) {
name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); recordingName = "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. // 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 } }; const captureConstraint = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: streamId } };
tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src }); tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: captureConstraint });
// Mixer: tab audio + optional mic are mixed into one destination track. // Mixer: tab audio + optional mic are mixed into one destination track.
ctx = new AudioContext(); audioContext = new AudioContext();
const dest = ctx.createMediaStreamDestination(); const dest = audioContext.createMediaStreamDestination();
const t = ctx.createMediaStreamSource(tab); const tabSource = audioContext.createMediaStreamSource(tabStream);
t.connect(dest); tabSource.connect(dest);
t.connect(ctx.destination); // tabCapture mutes the tab; play it back tabSource.connect(audioContext.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. // 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 try { // needs one-time grant via mic.html
mic = await navigator.mediaDevices.getUserMedia({ audio: true }); micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
ctx.createMediaStreamSource(mic).connect(dest); audioContext.createMediaStreamSource(micStream).connect(dest);
} catch { mic = null; } } catch { micStream = null; }
// Output stream: tab video + mixed audio. // Output stream: tab video + mixed audio.
const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]); const outStream = new MediaStream([...tabStream.getVideoTracks(), ...dest.stream.getAudioTracks()]);
// VP8 video + Opus audio at 1 Mbps video, a format the server's ffmpeg pipeline accepts. // 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 }); recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
// Each 10 s chunk is uploaded in order through the q promise chain. // Each 10 s chunk is uploaded in order through the uploadQueue promise chain.
rec.ondataavailable = e => { recorder.ondataavailable = event => {
// Chain the upload on q so chunks reach the server in order; count success or failure, then flush events. // Chain the upload on uploadQueue 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); uploadQueue = uploadQueue.then(() => fetch(`${API}/chunk?name=${recordingName}`, { method: "POST", body: event.data })).then(() => recorderState.chunks++, () => recorderState.failed++).then(flushEv);
}; };
// Stop path: wait for uploads, release the capture, then ask the server to transcribe. // Stop path: wait for uploads, release the capture, then ask the server to transcribe.
rec.onstop = async () => { recorder.onstop = async () => {
S.state = "transcribing"; S.t1 = Date.now(); recorderState.state = "transcribing"; recorderState.t1 = Date.now();
try { try {
// Wait for all queued chunk uploads to finish before asking for transcription. // Wait for all queued chunk uploads to finish before asking for transcription.
await q; await uploadQueue;
await flushEv(); await flushEv();
// Release tab/mic capture devices and the audio context. // Release tab/mic capture devices and the audio context.
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop())); [tabStream, micStream].forEach(stream => stream && stream.getTracks().forEach(track => track.stop()));
ctx.close(); audioContext.close();
// Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text. // 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" }); const response = await fetch(`${API}/stop?name=${recordingName}`, { method: "POST" });
S.text = await r.text(); S.state = r.ok ? "done" : "error"; recorderState.text = await response.text(); recorderState.state = response.ok ? "done" : "error";
} catch (e) { S.text = "server down or failed: " + e; S.state = "error"; } } catch (error) { recorderState.text = "server down or failed: " + error; recorderState.state = "error"; }
rec = null; recorder = null;
}; };
// Reset per-session state and record the start time; events are kept in S.ev until sent. // Reset per-session state and record the start time; events are kept in recorderState.ev until sent.
Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId }); Object.assign(recorderState, { state: "recording", name: recordingName, t0: Date.now(), chunks: 0, failed: 0, mic: !!micStream, text: "", ev: [], evSent: 0, tabId });
// 10 s timeslice: MediaRecorder emits a chunk every 10 s. // 10 s timeslice: MediaRecorder emits a chunk every 10 s.
rec.start(10000); recorder.start(10000);
} }
+26 -26
View File
@@ -1,67 +1,67 @@
// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder. // Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
// Shorthand for getElementById. // Shorthand for getElementById.
const $ = id => document.getElementById(id); const byId = elementId => document.getElementById(elementId);
// Forward a command to the offscreen document (addressed with to:"off"). // Forward a command to the offscreen document (addressed with to:"off").
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg }); const sendToOffscreen = message => chrome.runtime.sendMessage({ to: "off", ...message });
// Format milliseconds as m:ss. // 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")}`; }; const formatElapsed = milliseconds => { const totalSeconds = Math.floor(milliseconds / 1000); return `${Math.floor(totalSeconds / 60)}:${String(totalSeconds % 60).padStart(2, "0")}`; };
// Last error shown when there is no offscreen document to report it. // Last error shown when there is no offscreen document to report it.
let S = { state: "idle" }, lastErr = ""; let recorderState = { state: "idle" }, lastError = "";
// Refresh the button and status line from state S. // Refresh the button and status line from state recorderState.
function render() { function render() {
const go = $("go"), st = $("st"); const goButton = byId("go"), statusLine = byId("st");
// Pipeline busy after stop: no new start until it finishes. // Pipeline busy after stop: no new start until it finishes.
go.disabled = S.state === "transcribing"; goButton.disabled = recorderState.state === "transcribing";
// Button doubles as Stop while recording. // Button doubles as Stop while recording.
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start"; goButton.textContent = recorderState.state === "recording" ? "Stop + transcribe" : "Start";
// Status line text per recorder state. // Status line text per recorder state.
st.textContent = { statusLine.textContent = {
idle: "idle - open a Teams tab and press Start", 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}`, recording: `REC ${formatElapsed(Date.now() - recorderState.t0)} | ${recorderState.chunks} chunks uploaded${recorderState.failed ? ` | ${recorderState.failed} FAILED (server down?)` : ""} | mic ${recorderState.mic ? "on" : "OFF (grant it)"} | eventi call: ${recorderState.evSent || 0}`,
transcribing: `invio alla pipeline...`, transcribing: `invio alla pipeline...`,
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`, done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
error: "ERROR (see below)", error: "ERROR (see below)",
}[S.state]; }[recorderState.state];
// Show the transcript/result text when there is one. // Show the transcript/result text when there is one.
if (S.text) $("txt").textContent = S.text; if (recorderState.text) byId("txt").textContent = recorderState.text;
} }
// Poll the recorder state every second. // Poll the recorder state every second.
async function poll() { async function poll() {
// Offscreen doc exists: ask it for its state. Otherwise show the last error, or idle. // 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" }; if (await chrome.offscreen.hasDocument()) recorderState = (await sendToOffscreen({ cmd: "status" })) || recorderState; else recorderState = lastError ? { state: "error", text: lastError } : { state: "idle" };
render(); render();
} }
// Start / Stop click handler. // Start / Stop click handler.
$("go").onclick = async () => { byId("go").onclick = async () => {
// Stop path: first ask teams.js to stop its scanners. // Stop path: first ask teams.js to stop its scanners.
if (S.state === "recording") { if (recorderState.state === "recording") {
// Tell the Teams content script to stop (errors ignored: the tab may be gone). // 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(() => {}); if (recorderState.tabId != null) await chrome.tabs.sendMessage(recorderState.tabId, { cmd: "cap-stop" }).catch(() => {});
// Give teams.js's final event batch time to reach the offscreen doc before the recorder stops. // 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 new Promise(resolve => setTimeout(resolve, 300));
await off({ cmd: "stop" }); return poll(); await sendToOffscreen({ cmd: "stop" }); return poll();
} }
// Clear the previous error before a new attempt. // Clear the previous error before a new attempt.
lastErr = ""; lastError = "";
try { try {
// Tab the user is looking at when the button is pressed. // Tab the user is looking at when the button is pressed.
const [t] = await chrome.tabs.query({ active: true, currentWindow: true }); const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
// The popup itself is an extension page; it can't be recorded. // 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."); if (activeTab.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. // Stream id that the offscreen document later passes to getUserMedia.
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id }); const streamId = await chrome.tabCapture.getMediaStreamId({ targetTabId: activeTab.id });
// Create the offscreen document once; it stays alive while recording. // Create the offscreen document once; it stays alive while recording.
if (!(await chrome.offscreen.hasDocument())) if (!(await chrome.offscreen.hasDocument()))
await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" }); await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" });
const r = await off({ cmd: "start", id, tabId: t.id }); const response = await sendToOffscreen({ cmd: "start", id: streamId, tabId: activeTab.id });
if (r?.err) throw new Error(r.err); if (response?.err) throw new Error(response.err);
// Tell teams.js to start its scanners; ignored if the content script is not on this tab. // 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(() => {}); chrome.tabs.sendMessage(activeTab.id, { cmd: "cap-start" }).catch(() => {});
// Any failure is shown in the status line. // Any failure is shown in the status line.
} catch (e) { lastErr = String(e); } } catch (error) { lastError = String(error); }
render(); poll(); render(); poll();
}; };
+21 -21
View File
@@ -1,44 +1,44 @@
// MAIN world, document_start: navigator.* reports Edge instead of Opera. // MAIN world, document_start: navigator.* reports Edge instead of Opera.
(() => { (() => {
// Original UA string from the page (Opera). // Original UA string from the page (Opera).
const ua = navigator.userAgent; const originalUA = navigator.userAgent;
// Only patch Opera; other browsers are left as-is. // Only patch Opera; other browsers are left as-is.
if (!/OPR\//.test(ua)) return; if (!/OPR\//.test(originalUA)) return;
// Chrome major version, same logic as background.js. // Chrome major version, same logic as background.js.
const v = (ua.match(/Chrome\/(\d+)/) || [])[1] || "130"; const chromeMajor = (originalUA.match(/Chrome\/(\d+)/) || [])[1] || "130";
// Same UA rewrite as background.js: drop OPR/, add Edg/. // Same UA rewrite as background.js: drop OPR/, add Edg/.
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`; const edgeUA = originalUA.replace(/ OPR\/[\d.]+/, "") + ` Edg/${chromeMajor}.0.0.0`;
// Replace any Opera brand entry with Microsoft Edge, keeping its version. // 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)); const fixBrands = brandList => brandList.map(entry => (/opera/i.test(entry.brand) ? { brand: "Microsoft Edge", version: entry.version } : entry));
// Getter-only property definer; configurable so it can be redefined. // Getter-only property definer; configurable so it can be redefined.
const def = (o, k, g) => Object.defineProperty(o, k, { get: g, configurable: true }); const defineGetter = (object, key, getter) => Object.defineProperty(object, key, { get: getter, configurable: true });
// Override on Navigator.prototype so page scripts reading navigator.userAgent see Edge. // Override on Navigator.prototype so page scripts reading navigator.userAgent see Edge.
def(Navigator.prototype, "userAgent", () => edgeUA); defineGetter(Navigator.prototype, "userAgent", () => edgeUA);
// appVersion is the UA without the leading "Mozilla/". // appVersion is the UA without the leading "Mozilla/".
def(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, "")); defineGetter(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
// userAgentData (Client Hints) exists only in Chromium-based browsers. // userAgentData (Client Hints) exists only in Chromium-based browsers.
const d = navigator.userAgentData; const uaData = navigator.userAgentData;
// Older builds without UA-CH: nothing more to patch. // Older builds without UA-CH: nothing more to patch.
if (!d) return; if (!uaData) return;
// Brand list with Opera replaced by Edge. // Brand list with Opera replaced by Edge.
const brands = fix(d.brands); const brands = fixBrands(uaData.brands);
// Keep the original function bound to the real object. // Keep the original function bound to the real object.
const hev = d.getHighEntropyValues.bind(d); const originalHighEntropy = uaData.getHighEntropyValues.bind(uaData);
// Replacement userAgentData object exposing the same fields as the original. // Replacement userAgentData object exposing the same fields as the original.
const patched = { const patched = {
brands, brands,
mobile: d.mobile, mobile: uaData.mobile,
platform: d.platform, platform: uaData.platform,
// High-entropy values also carry brands and fullVersionList: patch them too. // High-entropy values also carry brands and fullVersionList: patch them too.
getHighEntropyValues: async (h) => { getHighEntropyValues: async hints => {
const r = await hev(h); const result = await originalHighEntropy(hints);
if (r.brands) r.brands = fix(r.brands); if (result.brands) result.brands = fixBrands(result.brands);
if (r.fullVersionList) r.fullVersionList = fix(r.fullVersionList); if (result.fullVersionList) result.fullVersionList = fixBrands(result.fullVersionList);
return r; return result;
}, },
// toJSON is used when the object is serialised; must match the patched fields. // toJSON is used when the object is serialised; must match the patched fields.
toJSON: () => ({ brands, mobile: d.mobile, platform: d.platform }), toJSON: () => ({ brands, mobile: uaData.mobile, platform: uaData.platform }),
}; };
// Installed on the prototype, same as userAgent above. // Installed on the prototype, same as userAgent above.
def(Navigator.prototype, "userAgentData", () => patched); defineGetter(Navigator.prototype, "userAgentData", () => patched);
})(); })();
+32 -32
View File
@@ -28,26 +28,26 @@ let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = n
const norm = raw => { const norm = raw => {
raw = (raw || "").trim(); raw = (raw || "").trim();
// Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed. // Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed.
const m = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/); const match = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!m) return raw; if (!match) return raw;
// Reorder to "First Last" and title-case words that are fully uppercase. // 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(" "); return `${match[2]} ${match[1]}`.split(/\s+/).map(word => (word.length > 1 && word === word.toUpperCase() ? word[0] + word.slice(1).toLowerCase() : word)).join(" ");
}; };
// Walk up from an element to the participant tile (the ancestor containing a name tag). // 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; }; const tileOf = element => { while (element && !element.querySelector(SEL.nametag)) element = element.parentElement; return element; };
// Stable participant key: the nearest ancestor data-tid containing "@" (an id), else the name text. // Stable participant key: the nearest ancestor data-tid containing "@" (an id), else the name text.
const keyOf = tile => { const keyOf = tile => {
for (let e = tile; e; e = e.parentElement) if ((e.dataset?.tid || "").includes("@")) return e.dataset.tid; for (let node = tile; node; node = node.parentElement) if ((node.dataset?.tid || "").includes("@")) return node.dataset.tid;
return tile.querySelector(SEL.nametag)?.textContent.trim() || ""; return tile.querySelector(SEL.nametag)?.textContent.trim() || "";
}; };
// Display name from a tile's name tag. // Display name from a tile's name tag.
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent); const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
// Name of the local user, read from the self-video tile. // Name of the local user, read from the self-video tile.
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; }; const selfName = () => { const selfTile = document.querySelector(SEL.self); return selfTile ? nameOf(selfTile) : ""; };
// Queue an event with a wall-clock timestamp; sent later by send(). // 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 }); 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. // Wrap timer callbacks so one exception does not kill the interval.
const guard = f => () => { try { f(); } catch (e) { console.error("[teams-whisper]", e); } }; const guard = callback => () => { try { callback(); } catch (error) { console.error("[teams-whisper]", error); } };
// Send queued events to the offscreen document; errors ignored (the recorder may be closed). // 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(() => { }); }; const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
// All participant tiles currently in the DOM. // All participant tiles currently in the DOM.
@@ -68,18 +68,18 @@ function present() {
// Dedupe by key (a participant can have more than one tile). // Dedupe by key (a participant can have more than one tile).
const seen = new Map(); const seen = new Map();
// The self tile's name comes from the self-video element. // 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) }); for (const tile of tiles()) seen.set(keyOf(tile), { key: keyOf(tile), who: tile.closest(SEL.self) ? selfName() : nameOf(tile) });
// Roster snapshot payload. // Roster snapshot payload.
emit("present", "", "", JSON.stringify([...seen.values()])); emit("present", "", "", JSON.stringify([...seen.values()]));
} }
// Emit one "active" event for each participant whose speaking outline is on. // Emit one "active" event for each participant whose speaking outline is on.
function active() { function active() {
// Speaking outlines in the DOM. // Speaking outlines in the DOM.
for (const el of document.querySelectorAll(SEL.speaking)) { for (const element of document.querySelectorAll(SEL.speaking)) {
const t = tileOf(el); if (!t) continue; const tile = tileOf(element); if (!tile) continue;
// The local user speaking is recorded under the key "self". // The local user speaking is recorded under the key "self".
if (t.closest(SEL.self) || t.matches(SEL.self)) emit("active", "self", selfName()); if (tile.closest(SEL.self) || tile.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(t), nameOf(t)); else emit("active", keyOf(tile), nameOf(tile));
} }
} }
// Screen share: detect the sharer from the banner aria-label and emit start/stop on change. // Screen share: detect the sharer from the banner aria-label and emit start/stop on change.
@@ -88,10 +88,10 @@ function share() {
const names = tiles().map(nameOf); const names = tiles().map(nameOf);
let cur = ""; let cur = "";
// Scan all aria-labels for the share banner. // Scan all aria-labels for the share banner.
for (const el of document.querySelectorAll("[aria-label]")) { for (const element of document.querySelectorAll("[aria-label]")) {
const m = el.getAttribute("aria-label").match(SEL.shareAria); const match = element.getAttribute("aria-label").match(SEL.shareAria);
// Prefer a roster name the banner text starts with (labels can be truncated); else use the raw text. // 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; } if (match) { cur = names.find(name => name && match[2].startsWith(name)) || match[2]; break; }
} }
// No change since last check. // No change since last check.
if (cur === lastShare) return; if (cur === lastShare) return;
@@ -102,33 +102,33 @@ function share() {
} }
// Captions, chat and raised hands, each emitted once. // Captions, chat and raised hands, each emitted once.
function messages() { function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) { if (SEL.caption) for (const element of document.querySelectorAll(SEL.caption)) {
// Author row sets the speaker for the text rows that follow it. // Author row sets the speaker for the text rows that follow it.
if (el.getAttribute("data-tid") === "author") { capAuthor = norm(el.textContent); continue; } if (element.getAttribute("data-tid") === "author") { capAuthor = norm(element.textContent); continue; }
// caption text grows while spoken: emit once it was unchanged for a full tick // caption text grows while spoken: emit once it was unchanged for a full tick
// Caption text of this row. // Caption text of this row.
const text = el.textContent.trim(), s = seenCap.get(el) || {}; const text = element.textContent.trim(), seenState = seenCap.get(element) || {};
// Already emitted this row. // Already emitted this row.
if (s.done) continue; if (seenState.done) continue;
// Unchanged since last tick: treat as final and emit once. // Unchanged since last tick: treat as final and emit once.
if (text && s.text === text) { s.done = true; emit("caption", "", capAuthor, text); } if (text && seenState.text === text) { seenState.done = true; emit("caption", "", capAuthor, text); }
s.text = text; seenCap.set(el, s); seenState.text = text; seenCap.set(element, seenState);
} }
// Chat messages (inactive while SEL.chatMsg is null); each element is counted once. // 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 (SEL.chatMsg) for (const element of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el); if (seenChat.has(element)) continue; seenChat.add(element);
const text = el.querySelector(SEL.chatText)?.textContent.trim(); const text = element.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(el.querySelector(SEL.chatAuthor)?.textContent), text); if (text) emit("chat", "", norm(element.querySelector(SEL.chatAuthor)?.textContent), text);
} }
// Hand raises (inactive while SEL.hand is null); emit only new raises. // Hand raises (inactive while SEL.hand is null); emit only new raises.
if (SEL.hand) { if (SEL.hand) {
// Hands raised this tick. // Hands raised this tick.
const now = new Set(); const now = new Set();
for (const el of document.querySelectorAll(SEL.hand)) { for (const element of document.querySelectorAll(SEL.hand)) {
const t = tileOf(el); if (!t) continue; const tile = tileOf(element); if (!tile) continue;
const k = keyOf(t); now.add(k); const participantKey = keyOf(tile); now.add(participantKey);
// New raise since the last tick. // New raise since the last tick.
if (!raised.has(k)) emit("hand", k, nameOf(t)); if (!raised.has(participantKey)) emit("hand", participantKey, nameOf(tile));
} }
// Keep only hands still up. // Keep only hands still up.
raised = now; raised = now;
@@ -160,7 +160,7 @@ function start() {
} }
// Start/stop commands sent by popup.js directly to this tab. // Start/stop commands sent by popup.js directly to this tab.
chrome.runtime.onMessage.addListener(m => { chrome.runtime.onMessage.addListener(message => {
if (m.cmd === "cap-start") start(); if (message.cmd === "cap-start") start();
if (m.cmd === "cap-stop") stop(); if (message.cmd === "cap-stop") stop();
}); });
+199 -78
View File
@@ -4,8 +4,10 @@
# /// # ///
# ponytail: ctranslate2 4.8 links cublas64_12 (matches the nvidia-*-cu12 wheels); bump all three together when it moves to CUDA 13 # 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]""" """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). # Prefect pipeline entry point. Env vars below (lines 8-16) must be set before prefect is imported (line 21).
import os import os
# Talk to the local Prefect server started by server.py; setdefault keeps a user override. # 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") 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. # Bypass the corporate proxy for localhost, or Prefect API calls get routed out.
@@ -16,186 +18,305 @@ os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false"
os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper()) 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 os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI
# stdlib only: CLI args, JSON, paths, exit codes. # stdlib only: CLI args, JSON, paths, exit codes.
import argparse, json, sys import argparse
import json
import sys
from pathlib import Path from pathlib import Path
# Pipeline stage modules living next to this file.
import audio
import db
import diarize
import docs
import llama
import memory
import report
import shots
import speakers
import transcribe
from prefect import flow, task from prefect import flow, task
from prefect.runtime import flow_run from prefect.runtime import flow_run
from prefect.task_runners import ThreadPoolTaskRunner 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 HERE = Path(__file__).parent
# Stage order. --from picks a start point; go() compares indices into this list. # Stage order. --from picks a start point; should_run() compares indices into this list.
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render", "title"] 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. # 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): def step_status(name, stage):
# key per model for the LLM steps: their speed (and so the ETA) depends on it # 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) db.step(
name,
stage,
f"{stage}@{llama.current(stage == 'shots')}" if stage in ("shots", "report") else stage,
)
# One Prefect task per stage: set status, then call the stage's run(). # One Prefect task per stage: set status, then call the stage's run().
@task(name="audio") @task(name="audio")
def t_audio(name): step_status(name, "audio"); audio.run(name) def audio_task(name):
step_status(name, "audio")
audio.run(name)
@task(name="transcribe") @task(name="transcribe")
def t_transcribe(name, model, device, status=True): def transcribe_task(name, model, device, status=True):
if status: step_status(name, "transcribing") if status:
step_status(name, "transcribing")
transcribe.run(name, model=model, device=device) transcribe.run(name, model=model, device=device)
@task(name="diarize") @task(name="diarize")
def t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speakers=n) def diarize_task(name, speaker_count):
step_status(name, "diarizing")
diarize.run(name, speakers=speaker_count)
@task(name="speakers") @task(name="speakers")
def t_speakers(name): step_status(name, "identifying"); speakers.run(name) def speakers_task(name):
step_status(name, "identifying")
speakers.run(name)
# shots/docs/report call LLM servers that can fail transiently: retry once after 10 s. # shots/docs/report call LLM servers that can fail transiently: retry once after 10 s.
@task(name="shots", retries=1, retry_delay_seconds=10) @task(name="shots", retries=1, retry_delay_seconds=10)
def t_shots(name, status=True): def shots_task(name, status=True):
if status: step_status(name, "shots") if status:
step_status(name, "shots")
shots.run(name) shots.run(name)
@task(name="docs", retries=1, retry_delay_seconds=10) @task(name="docs", retries=1, retry_delay_seconds=10)
def t_docs(name): step_status(name, "docs"); docs.run(name) def docs_task(name):
step_status(name, "docs")
docs.run(name)
@task(name="report", retries=1, retry_delay_seconds=10) @task(name="report", retries=1, retry_delay_seconds=10)
def t_report(name): step_status(name, "report"); report.run(name) def report_task(name):
step_status(name, "report")
report.run(name)
@task(name="memory") @task(name="memory")
def t_memory(name): step_status(name, "memory"); memory.run(name) def memory_task(name):
step_status(name, "memory")
memory.run(name)
# Owns one llama-server process per run; switching profile (vision <-> text) restarts it. # Owns one llama-server process per run; switching profile (vision <-> text) restarts it.
class Llama: class Llama:
"""Start llama-server in vision (shots) or text (report) profile; switching restarts it. Terminate in close() only if we started it.""" """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
def __init__(self, name):
self.name, self.process, self.vision = name, None, None
def ensure(self, vision=True): def ensure(self, vision=True):
if self.p and self.vision != vision: self.close() if self.process and self.vision != vision:
self.close()
self.vision = vision self.vision = vision
log = db.logs(self.name) / ("llama.log" if vision else "llama_text.log") log = db.logs(self.name) / ("llama.log" if vision else "llama_text.log")
try: try:
p = llama.start(vision=vision, log=log) process = llama.start(vision=vision, log=log)
except Exception: except Exception as error:
# llama.log with 'out of memory' means another CUDA app holds VRAM; tell the user the fix. # 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"): 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 RuntimeError(
"GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'"
) from error
raise raise
# Keep the process we started earlier; llama.start() returns None when a server is already running. # Keep the process we started earlier; llama.start() returns None when a server is already running.
self.p = self.p or p self.process = self.process or process
def close(self): 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 if self.process and self.process.poll() is None:
self.p = None self.process.terminate()
self.process.wait() # wait: port must be free before a profile switch
self.process = None
# Device: GUI/bench file wins, else cuda. Unknown values fall back to cuda. # Device: GUI/bench file wins, else cuda. Unknown values fall back to cuda.
def default_device(): def default_device():
try: try:
d = (db.GLOBAL / "transcribe_device.txt").read_text().strip() device_name = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
return d if d in ("cuda", "npu") else "cuda" return device_name if device_name in ("cuda", "npu") else "cuda"
except OSError: except OSError:
return "cuda" return "cuda"
# Up to 3 threads; ordering comes from explicit .result() waits, not from the runner. # 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)) @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): 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() 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) # True if stage is at or after the requested start (--from).
def should_run(stage):
return STEPS.index(stage) >= STEPS.index(start_from)
# Owns the llama-server process; always closed in the finally block. # Owns the llama-server process; always closed in the finally block.
L = Llama(name) llama_server = Llama(name)
try: try:
# Link the DB row to this Prefect run so the GUI can find it. # 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.upsert_recording(name, flow_run_id=str(flow_run.id))
db.progress_start(name, start_from) db.progress_start(name, start_from)
# shots run every time unless the GUI toggle "Salta schermate" is on # shots run every time unless the GUI toggle "Salta schermate" is on
# Resume: reuse shots already extracted by an earlier run. # Resume: reuse shots already extracted by an earlier run.
sj = db.out_dir(name) / "shots.json" shots_json_path = db.out_dir(name) / "shots.json"
try: done = json.loads(sj.read_text(encoding="utf-8")) try:
except (OSError, ValueError): done = [] previous_shots = json.loads(shots_json_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
previous_shots = []
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate" no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
skip_shots = no_shots skip_shots = no_shots
# Toggle on with no prior shots: write empty placeholders so downstream steps find their files. # Toggle on with no prior shots: write empty placeholders so downstream steps find their files.
if no_shots and not done: if no_shots and not previous_shots:
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]") for file_name in ("shots.json", "glossary.json"):
(db.out_dir(name) / file_name).write_text("[]")
db.replace_shots(name, []) db.replace_shots(name, [])
if skip_shots and go("shots"): print("shots skipped") if skip_shots and should_run("shots"):
print("shots skipped")
# Title/render restart: re-run only text-only post-processing, no vision model needed. # Title/render restart: re-run only text-only post-processing, no vision model needed.
if start_from == "title": if start_from == "title":
L.ensure(vision=False) llama_server.ensure(vision=False)
report.retitle(name) report.retitle(name)
memory.run(name, link=False) memory.run(name, link=False)
elif start_from == "render": elif start_from == "render":
memory.run(name, link=False) memory.run(name, link=False)
else: else:
if go("audio"): t_audio(name) if should_run("audio"):
audio_task(name)
# Speaker labelling: diarize, then name mapping. # 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) def speaker_chain():
return (
[diarize_task(name, speakers), speakers_task(name)]
if should_run("diarize")
else ([speakers_task(name)] if should_run("speakers") else None)
)
# NPU path: transcribe on the NPU while shots run on the GPU VLM at the same time. # 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: if (
device == "npu"
and should_run("transcribe")
and should_run("shots")
and not skip_shots
):
db.set_status(name, "transcribing") db.set_status(name, "transcribing")
L.ensure() llama_server.ensure()
f_t = t_transcribe.submit(name, model, "npu", False) transcribe_future = transcribe_task.submit(name, model, "npu", False)
f_s = t_shots.submit(name, False) shots_future = shots_task.submit(name, False)
# Wait for NPU transcription; shots keep running meanwhile. # Wait for NPU transcription; shots keep running meanwhile.
try: try:
f_t.result() transcribe_future.result()
except Exception as e: except Exception as error:
# Only the NPU failure is handled here; anything else is a real error. # Only the NPU failure is handled here; anything else is a real error.
if "NPU failed" not in repr(e): raise if "NPU failed" not in repr(error):
f_s.result(); L.close() raise
shots_future.result()
llama_server.close()
print("NPU failed, transcribed on cuda") print("NPU failed, transcribed on cuda")
t_transcribe(name, model, "cuda") transcribe_task(name, model, "cuda")
# Shots already finished above; clear the handle. # Shots already finished above; clear the handle.
spk_chain(); L.ensure(); f_s = None speaker_chain()
llama_server.ensure()
shots_future = None
else: else:
spk_chain() speaker_chain()
# Shots still running in parallel; wait for them before text stages. # Shots still running in parallel; wait for them before text stages.
if f_s is not None: f_s.result() if shots_future is not None:
shots_future.result()
else: else:
# Sequential path (CUDA, or NPU without shots). # Sequential path (CUDA, or NPU without shots).
if go("transcribe"): t_transcribe(name, model, device) if should_run("transcribe"):
spk_chain() transcribe_task(name, model, device)
if go("shots") and not skip_shots: L.ensure(); t_shots(name) speaker_chain()
L.ensure(vision=False) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile if should_run("shots") and not skip_shots:
if go("docs"): t_docs(name) llama_server.ensure()
if go("report"): t_report(name) shots_task(name)
llama_server.ensure(
vision=False
) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
if should_run("docs"):
docs_task(name)
if should_run("report"):
report_task(name)
# Memory update: always runs as the final stage. # Memory update: always runs as the final stage.
t_memory(name) memory_task(name)
db.step(name, "done") db.step(name, "done")
except Exception as e: except Exception as error:
# Record the failure for the GUI, then re-raise so Prefect marks the run failed. # Record the failure for the GUI, then re-raise so Prefect marks the run failed.
db.set_status(name, "error", repr(e)[:500]) db.set_status(name, "error", repr(error)[:500])
raise raise
finally: finally:
L.close() llama_server.close()
# Benchmark both transcribers on the same audio and store the choice for default_device(). # Benchmark both transcribers on the same audio and store the choice for default_device().
def bench(name): def bench(name):
d = db.out_dir(name) out_dir = db.out_dir(name)
# A failed NPU run is recorded as None so the comparison below picks CUDA. # 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") try:
except Exception as e: print("npu error:", e); npu_s = None npu_s = transcribe.run(name, device="npu", out_path=out_dir / "bench_npu.txt")
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt") except Exception as error:
print("npu error:", error)
npu_s = None
cuda_s = transcribe.run(name, device="cuda", out_path=out_dir / "bench_cuda.txt")
# NPU is picked unless it failed or is more than 3x slower than CUDA (deliberate tolerance, not fastest-wins). # 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" chosen_device = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
# Persist for later runs (read by default_device). # Persist for later runs (read by default_device).
(db.GLOBAL / "transcribe_device.txt").write_text(dev) (db.GLOBAL / "transcribe_device.txt").write_text(chosen_device)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}") print(f"npu_s={npu_s} cuda_s={cuda_s} device={chosen_device}")
if __name__ == "__main__": if __name__ == "__main__":
if sys.argv[1:] == ["--prefect-server"]: # server.py: run Prefect from this cached env (an ephemeral --with env needs PyPI) if sys.argv[1:] == [
"--prefect-server"
]: # server.py: run Prefect from this cached env (an ephemeral --with env needs PyPI)
import subprocess import subprocess
sys.exit(subprocess.call([sys.executable, "-m", "prefect", "server", "start", "--host", "127.0.0.1", "--port", "4200"]))
sys.exit(
subprocess.call(
[
sys.executable,
"-m",
"prefect",
"server",
"start",
"--host",
"127.0.0.1",
"--port",
"4200",
]
)
)
sys.stdout.reconfigure(encoding="utf-8") sys.stdout.reconfigure(encoding="utf-8")
ap = argparse.ArgumentParser() parser = argparse.ArgumentParser()
ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS) parser.add_argument("name")
ap.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster"); ap.add_argument("--device", choices=["cuda", "npu"]) parser.add_argument("--from", dest="start", default="audio", choices=STEPS)
ap.add_argument("--bench-npu", action="store_true") parser.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster")
a = ap.parse_args() parser.add_argument("--device", choices=["cuda", "npu"])
parser.add_argument("--bench-npu", action="store_true")
args = parser.parse_args()
# --bench-npu is a one-off benchmark; it does not run the pipeline. # --bench-npu is a one-off benchmark; it does not run the pipeline.
if a.bench_npu: bench(a.name) if args.bench_npu:
else: meeting(a.name, a.start, a.speakers, device=a.device) bench(args.name)
else:
meeting(args.name, args.start, args.speakers, device=args.device)
+562 -156
View File
@@ -1,265 +1,625 @@
# llama.py: starts llama-server (local GGUF chat/vision/embedding), routes chat to local or cloud models, installs omp and downloads models. # 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 import functools
import hashlib
import json
import os
import shutil
import socket
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path from pathlib import Path
# Paths relative to this file: bin/ (llama-server, omp), models/ (GGUF), out/ (GUI state). # Paths relative to this file: bin/ (llama-server, omp), models/ (GGUF), out/ (GUI state).
HERE = Path(__file__).parent HERE = Path(__file__).parent
SERVER = HERE / "bin" / "llama-server.exe" SERVER = HERE / "bin" / "llama-server.exe"
MD = HERE / "models" MODELS_DIR = HERE / "models"
CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>" CHOICE_FILE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>"
# Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02. # Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02.
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop _KV_ARGS = [
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster "-ctk",
"q8_0",
"-ctv",
"q8_0",
"-fa",
"on",
"-np",
"1",
] # KV q8: no measurable loss; V q4 made the 4B loop
_IMAGE_ARGS = [
"--image-min-tokens",
"1024",
"--image-max-tokens",
"1536",
] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch)) # key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch))
# Values below are the 4 GB profile; _fit() strips -ngl/-ot/--cpu-moe on >= 7 GiB GPUs. # Values below are the 4 GB profile; _fit() strips -ngl/-ot/--cpu-moe on >= 7 GiB GPUs.
MODELS = { MODELS = {
# MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention # MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s). # layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
"qwen35b": ("Qwen3.6 35B-A3B (RAM)", MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf", "qwen35b": (
["--mmproj-offload", *_IMG, "--cpu-moe", "-ngl", "30", "-c", "16384", *_Q], "Qwen3.6 35B-A3B (RAM)",
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", "--reasoning-budget", "1024", *_Q]), MODELS_DIR / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf",
MODELS_DIR / "mmproj-BF16.gguf",
["--mmproj-offload", *_IMAGE_ARGS, "--cpu-moe", "-ngl", "30", "-c", "16384", *_KV_ARGS],
[
"--cpu-moe",
"-ngl",
"99",
"-c",
"16384",
"-ub",
"2048",
"--reasoning-budget",
"1024",
*_KV_ARGS,
],
),
# Hybrid attention -> 16k KV is only ~0.3 GB. Q4_K_S: best boxes/entities vs IQ4_XS/Q4_K_M/UD-Q4_K_XL on 8 sample shots. # Hybrid attention -> 16k KV is only ~0.3 GB. Q4_K_S: best boxes/entities vs IQ4_XS/Q4_K_M/UD-Q4_K_XL on 8 sample shots.
# Vision: encoder on GPU, FFN of the last 13/32 layers in RAM to make room: shot 36 -> 22 s (CPU encoder was ~19 s/image), # Vision: encoder on GPU, FFN of the last 13/32 layers in RAM to make room: shot 36 -> 22 s (CPU encoder was ~19 s/image),
# gen only 30 -> 25 tok/s; 12 is the limit (10 OOMs), 13 leaves margin. Text: everything on GPU. # gen only 30 -> 25 tok/s; 12 is the limit (10 OOMs), 13 leaves margin. Text: everything on GPU.
"qwen4b": ("Qwen3.5 4B (VRAM)", MD / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf", MD / "qwen3.5-4b" / "mmproj-BF16.gguf", "qwen4b": (
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q], "Qwen3.5 4B (VRAM)",
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]), MODELS_DIR / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf",
MODELS_DIR / "qwen3.5-4b" / "mmproj-BF16.gguf",
[
"--mmproj-offload",
*_IMAGE_ARGS,
"-ngl",
"99",
"-ot",
r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU",
"-c",
"16384",
*_KV_ARGS,
],
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_KV_ARGS],
),
} }
# Ports on 127.0.0.1: chat completion server and bge-m3 embedding server. # Ports on 127.0.0.1: chat completion server and bge-m3 embedding server.
PORT = 18081 PORT = 18081
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082 EMBED, EMBED_PORT = MODELS_DIR / "bge-m3-Q8_0.gguf", 18082
# Cached: nvidia-smi is slow and the GPU does not change while the app runs. # Cached: nvidia-smi is slow and the GPU does not change while the app runs.
@functools.cache @functools.cache
def vram_mib(): def vram_mib():
"""Largest NVIDIA GPU's total VRAM in MiB; 0 without NVIDIA driver.""" """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. # 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"], try:
capture_output=True, text=True, timeout=10).stdout.split()) return max(
except (OSError, ValueError, subprocess.SubprocessError): return 0 int(value)
for value 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
_TUNED = {"-ngl": 1, "-ot": 1, "--cpu-moe": 0} # 4 GB placement flags -> number of values they take _TUNED = {"-ngl": 1, "-ot": 1, "--cpu-moe": 0} # 4 GB placement flags -> number of values they take
def _fit(args, vision): def _fit(args, vision):
"""GPUs >= 7 GiB: drop the 4 GB hand-tuned layer/expert placement so llama.cpp --fit (default on) fills VRAM. """GPUs >= 7 GiB: drop the 4 GB hand-tuned layer/expert placement so llama.cpp --fit (default on) fills VRAM.
Vision keeps 3 GiB margin: --fit sizes only the LLM, the mmproj encoder loads after it.""" Vision keeps 3 GiB margin: --fit sizes only the LLM, the mmproj encoder loads after it."""
if vram_mib() < 7168: return args if vram_mib() < 7168:
out, it = [], iter(args) return args
for a in it: kept_args, arg_iter = [], iter(args)
if a in _TUNED: for argument in arg_iter:
for _ in range(_TUNED[a]): next(it) if argument in _TUNED:
else: out.append(a) for _ in range(_TUNED[argument]):
return out + (["-fitt", "3072"] if vision else []) next(arg_iter)
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost else:
kept_args.append(argument)
return kept_args + (["-fitt", "3072"] if vision else [])
_open = urllib.request.build_opener(
urllib.request.ProxyHandler({})
).open # corp proxy must not see localhost
PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, cloud LLMs) PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, cloud LLMs)
# key -> (label, model id, vision, provider). Vision=False: report/docs/memory/ask only (BYOK italdesign/ models reject images). # key -> (label, model id, vision, provider). Vision=False: report/docs/memory/ask only (BYOK italdesign/ models reject images).
REMOTE = { REMOTE = {
"cp-haiku": ("Claude Haiku 5.5 (Copilot, crediti)", "claude-haiku-5.5", True, "github-copilot"), "cp-haiku": ("Claude Haiku 5.5 (Copilot, crediti)", "claude-haiku-5.5", True, "github-copilot"),
"cp-kimi": ("Kimi K2.5 (italdesign BYOK)", "italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5", False, "github-copilot"), "cp-kimi": (
"cp-deepseek": ("DeepSeek V3.2 (italdesign BYOK)", "italdesign/Bedrock_Mantle/deepseek.v3.2", False, "github-copilot"), "Kimi K2.5 (italdesign BYOK)",
"cp-sonnet": ("Claude Sonnet 5.5 (Copilot, crediti)", "claude-sonnet-5.5", False, "github-copilot"), "italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5",
"cp-gemini": ("Gemini 3.8 Flash (Copilot, crediti)", "gemini-3.8-flash", False, "github-copilot"), False,
"an-haiku": ("Claude Haiku 5.5 (Anthropic, abbonamento)", "claude-haiku-5-5", True, "anthropic"), "github-copilot",
"an-sonnet": ("Claude Sonnet 5.5 (Anthropic, abbonamento)", "claude-sonnet-5-5", True, "anthropic"), ),
"cp-deepseek": (
"DeepSeek V3.2 (italdesign BYOK)",
"italdesign/Bedrock_Mantle/deepseek.v3.2",
False,
"github-copilot",
),
"cp-sonnet": (
"Claude Sonnet 5.5 (Copilot, crediti)",
"claude-sonnet-5.5",
False,
"github-copilot",
),
"cp-gemini": (
"Gemini 3.8 Flash (Copilot, crediti)",
"gemini-3.8-flash",
False,
"github-copilot",
),
"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. # 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"} _COPILOT_HEADERS = {
_ctx = ssl.create_default_context(); _ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT # corp TLS proxy CA lacks critical basicConstraints "Editor-Version": "vscode/1.107.1",
_NO_PROXY = "localhost,127.0.0.1,.audi.vwg,.vwgroup.com,.vwg,.italdesign.it" # same list as $PROFILE "Editor-Plugin-Version": "copilot-chat/0.26.7",
"Copilot-Integration-Id": "copilot-developer-cli",
}
_ssl_context = ssl.create_default_context()
_ssl_context.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]. # Cache of the proxy probe: [timestamp, proxy URL or None].
_PX = [0.0, None] _proxy_probe = [0.0, None]
def proxy(): 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.""" """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: if time.time() - _proxy_probe[0] > 300:
# Reachability probe only: a TCP connect to the proxy host, no HTTP request. # 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 try:
except OSError: px = None socket.create_connection(("zproxy.idg.audi.vwg", 9400), timeout=2).close()
_PX[:] = [time.time(), px] proxy_url = PROXY
return _PX[1] except OSError:
proxy_url = None
_proxy_probe[:] = [time.time(), proxy_url]
return _proxy_probe[1]
# One opener per proxy setting; the proxy URL is the cache key. # One opener per proxy setting; the proxy URL is the cache key.
@functools.cache @functools.cache
def _opener(px): def _opener(proxy_url):
return urllib.request.build_opener(urllib.request.ProxyHandler({"https": px, "http": px} if px else {}), urllib.request.HTTPSHandler(context=_ctx)).open return urllib.request.build_opener(
urllib.request.ProxyHandler({"https": proxy_url, "http": proxy_url} if proxy_url else {}),
urllib.request.HTTPSHandler(context=_ssl_context),
).open
def _ropen(): def _ropen():
"""Opener for internet calls: through the corp proxy when reachable, else direct (ProxyHandler({}) ignores stale env proxies, like $PROFILE's else branch).""" """Opener for internet calls: through the corp proxy when reachable, else direct (ProxyHandler({}) ignores stale env proxies, like $PROFILE's else branch)."""
return _opener(proxy()) return _opener(proxy())
def omp_env(): 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.""" """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. # 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")} child_env = {
key: value
for key, value in os.environ.items()
if key.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. # 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. # 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") if proxy_url := proxy():
return env child_env.update(
HTTP_PROXY=proxy_url,
HTTPS_PROXY=proxy_url,
PI_PROXY=proxy_url,
NO_PROXY=_NO_PROXY,
NODE_TLS_REJECT_UNAUTHORIZED="0",
)
return child_env
# Local models whose GGUF file is present on disk. # Local models whose GGUF file is present on disk.
def _local(): return [k for k, m in MODELS.items() if m[1].exists()] def _local():
return [key for key, spec in MODELS.items() if spec[1].exists()]
# Installed local models, plus cloud models (vision=True keeps only those accepting images). # 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 available(vision=True):
def label(k): return (MODELS.get(k) or REMOTE[k])[0] return _local() + [key for key, spec in REMOTE.items() if spec[2] or not vision]
def label(key):
return (MODELS.get(key) or REMOTE[key])[0]
def current(vision=True): 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) """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).""" 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. # CHOICE holds "<vision key> <text key>"; an empty file gives [""] so fallbacks apply.
ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""] keys = (CHOICE_FILE.read_text().split() if CHOICE_FILE.exists() else []) or [""]
k = ks[0] if vision else ks[-1] # a single key (old format) applies to both key = keys[0] if vision else keys[-1] # a single key (old format) applies to both
if k in available(vision): return k if key in available(vision):
loc = _local() return key
local_keys = _local()
# 4B fits fully in VRAM: shots near 35B quality at much higher speed (see MODELS). # 4B fits fully in VRAM: shots near 35B quality at much higher speed (see MODELS).
if vision and "qwen4b" in loc: return "qwen4b" if vision and "qwen4b" in local_keys:
return (loc or available(vision))[0] return "qwen4b"
return (local_keys or available(vision))[0]
OMP_LOCAL = (
HERE / "bin" / "omp.exe"
) # Pinokio-local install (llama.py install-omp); wins over a PATH omp so the install's own copy is always the one used
def omp_exe():
return str(OMP_LOCAL) if OMP_LOCAL.exists() else shutil.which("omp")
_token_cache = {} # provider -> (token, api base, fetched at)
OMP_LOCAL = HERE / "bin" / "omp.exe" # Pinokio-local install (llama.py install-omp); wins over a PATH omp so the install's own copy is always the one used
def omp_exe(): return str(OMP_LOCAL) if OMP_LOCAL.exists() else shutil.which("omp")
_TOK = {} # provider -> (token, api base, fetched at)
def _token(provider): 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.""" """(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) cached = _token_cache.get(provider)
# Reuse the cached token for 5 min instead of spawning omp on every call. # 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] if cached and time.time() - cached[2] < 300:
exe = omp_exe() return cached[:2]
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio") omp_path = omp_exe()
if not omp_path:
raise RuntimeError("omp non installato: esegui Install da Pinokio")
# --raw: bare token, or JSON {token, apiEndpoint}; 60 s guards against a hung omp. # --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()) result = subprocess.run(
[omp_path, "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. # 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]}") if result.returncode:
raise RuntimeError(
f"{provider}: login necessario (Pinokio → Cloud login). {result.stderr.strip()[:200]}"
)
# omp prints a JSON object {token, apiEndpoint} or a bare token; accept both. # 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} stdout_text = result.stdout.strip()
data = json.loads(stdout_text) if stdout_text.startswith("{") else {"token": stdout_text}
# Fallback API base when omp does not report apiEndpoint. # 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") base = data.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). # 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] _token_cache[provider] = (data["token"], base, time.time())
return _token_cache[provider][:2]
# Cache for omp_status(): [timestamp, status dict]. # Cache for omp_status(): [timestamp, status dict].
_ST = [0.0, None] _omp_status_cache = [0.0, None]
def omp_status(): 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). """{'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).
ponytail: a revoked Copilot token only shows up on the next API call (its expiresAt is years away).""" ponytail: a revoked Copilot token only shows up on the next API call (its expiresAt is years away)."""
if time.time() - _ST[0] < 60: return _ST[1] if time.time() - _omp_status_cache[0] < 60:
s = {"exe": omp_exe()} return _omp_status_cache[1]
for p in ("github-copilot", "anthropic"): status = {"exe": omp_exe()}
for provider in ("github-copilot", "anthropic"):
# Drop the cached token so every provider is re-checked for real. # Drop the cached token so every provider is re-checked for real.
_TOK.pop(p, None) _token_cache.pop(provider, None)
try: _token(p); s[p] = None try:
except Exception as e: s[p] = str(e) _token(provider)
_ST[:] = [time.time(), s]; return s status[provider] = None
except Exception as err:
status[provider] = str(err)
_omp_status_cache[:] = [time.time(), status]
return status
# Headers Anthropic requires for subscription OAuth (mirrors Claude Code's client). # 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"} _ANTHROPIC_HEADERS = {
def _anthropic(body, model, tok, timeout): "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, token, timeout):
"""OpenAI chat body -> Anthropic Messages (subscription OAuth needs the Claude Code identity first, as omp/pi send) -> OpenAI-shaped response.""" """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. # 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."}], [] system, msgs = (
for m in body["messages"]: [{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude."}],
[],
)
for message in body["messages"]:
# Anthropic takes system as blocks, so system messages are collected separately. # Anthropic takes system as blocks, so system messages are collected separately.
if m["role"] == "system": system.append({"type": "text", "text": m["content"]}); continue if message["role"] == "system":
c = m["content"] system.append({"type": "text", "text": message["content"]})
if isinstance(c, list): # shots.py: text + data-URL jpeg continue
content = message["content"]
if isinstance(content, list): # shots.py: text + data-URL jpeg
# OpenAI content parts -> Anthropic blocks; images arrive as data URLs. # OpenAI content parts -> Anthropic blocks; images arrive as data URLs.
c = [{"type": "text", "text": p["text"]} if p["type"] == "text" else content = [
{"type": "text", "text": part["text"]}
if part["type"] == "text"
# data:<mime>;base64,<data>: [5:] strips "data:", the mime is before ";". # 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] else {
msgs.append({"role": m["role"], "content": c}) "type": "image",
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) "source": {
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_AHDR} "type": "base64",
"media_type": part["image_url"]["url"][5:].split(";")[0],
"data": part["image_url"]["url"].split(",", 1)[1],
},
}
for part in content
]
msgs.append({"role": message["role"], "content": content})
request_body = {
"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)
headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
**_ANTHROPIC_HEADERS,
}
# Request goes through _ropen() so the corp proxy applies when reachable. # 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)) try:
except urllib.error.HTTPError as e: raise RuntimeError(f"Anthropic {model}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e data = json.load(
_ropen()(
urllib.request.Request(
"https://api.anthropic.com/v1/messages",
json.dumps(request_body).encode(),
headers,
),
timeout=timeout,
)
)
except urllib.error.HTTPError as err:
raise RuntimeError(
f"Anthropic {model}: HTTP {err.code} {err.read()[:300].decode(errors='replace')}"
) from err
# Re-wrap in OpenAI shape so report/ask/memory callers need no Anthropic branch. # 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")}}], return {
"usage": {"prompt_tokens": d["usage"]["input_tokens"], "completion_tokens": d["usage"]["output_tokens"]}} "choices": [
{
"message": {
"content": "".join(
block.get("text", "")
for block in data["content"]
if block["type"] == "text"
)
}
}
],
"usage": {
"prompt_tokens": data["usage"]["input_tokens"],
"completion_tokens": data["usage"]["output_tokens"],
},
}
def post(body, vision, timeout): 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.""" """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. # Local llama-server unless the GUI picked a cloud (REMOTE) model.
# GUI choice decides local vs cloud; REMOTE holds the cloud model metadata. # GUI choice decides local vs cloud; REMOTE holds the cloud model metadata.
k = current(vision); r = REMOTE.get(k) key = current(vision)
if not r: remote = REMOTE.get(key)
if not remote:
# Local llama-server, OpenAI-compatible endpoint. # 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"}) request = urllib.request.Request(
return json.load(_open(req, timeout=timeout)) f"http://127.0.0.1:{PORT}/v1/chat/completions",
json.dumps({**body, "model": key}).encode(),
{"Content-Type": "application/json"},
)
return json.load(_open(request, timeout=timeout))
# Cloud: token and API base from omp. # Cloud: token and API base from omp.
tok, base = _token(r[3]) token, api_base = _token(remote[3])
# chat_template_kwargs is llama.cpp-specific; cloud APIs would reject it. # 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]} body = {
if r[3] == "anthropic": return _anthropic(body, r[1], tok, timeout) **{field: value for field, value in body.items() if field != "chat_template_kwargs"},
"model": remote[1],
}
if remote[3] == "anthropic":
return _anthropic(body, remote[1], token, timeout)
# Copilot needs this header to accept image inputs. # Copilot needs this header to accept image inputs.
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR, **({"Copilot-Vision-Request": "true"} if vision else {})} headers = {
try: return json.load(_ropen()(urllib.request.Request(base + "/chat/completions", json.dumps(body).encode(), h), timeout=timeout)) "Authorization": "Bearer " + token,
except urllib.error.HTTPError as e: "Content-Type": "application/json",
if e.code == 400: raise # callers retry 400 without response_format **_COPILOT_HEADERS,
raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e **({"Copilot-Vision-Request": "true"} if vision else {}),
}
try:
return json.load(
_ropen()(
urllib.request.Request(
api_base + "/chat/completions", json.dumps(body).encode(), headers
),
timeout=timeout,
)
)
except urllib.error.HTTPError as err:
if err.code == 400:
raise # callers retry 400 without response_format
raise RuntimeError(
f"Copilot {remote[1]}: HTTP {err.code} {err.read()[:300].decode(errors='replace')}"
) from err
def stream(body, timeout): def stream(body, timeout):
"""Like post() for text calls, but yields the reply text as it is generated (OpenAI SSE: local llama-server and Copilot). """Like post() for text calls, but yields the reply text as it is generated (OpenAI SSE: local llama-server and Copilot).
Anthropic is not streamed here: its whole reply is yielded at once.""" Anthropic is not streamed here: its whole reply is yielded at once."""
k = current(False); r = REMOTE.get(k) key = current(False)
if r and r[3] == "anthropic": yield content(post(body, False, timeout), "ask"); return remote = REMOTE.get(key)
if not r: if remote and remote[3] == "anthropic":
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k, "stream": True}).encode(), {"Content-Type": "application/json"}); op = _open yield content(post(body, False, timeout), "ask")
return
if not remote:
request = urllib.request.Request(
f"http://127.0.0.1:{PORT}/v1/chat/completions",
json.dumps({**body, "model": key, "stream": True}).encode(),
{"Content-Type": "application/json"},
)
opener = _open
else: else:
tok, base = _token(r[3]) token, api_base = _token(remote[3])
b = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1], "stream": True} cloud_body = {
req = urllib.request.Request(base + "/chat/completions", json.dumps(b).encode(), {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR}); op = _ropen() **{field: value for field, value in body.items() if field != "chat_template_kwargs"},
with op(req, timeout=timeout) as f: "model": remote[1],
for line in f: "stream": True,
}
request = urllib.request.Request(
api_base + "/chat/completions",
json.dumps(cloud_body).encode(),
{
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
**_COPILOT_HEADERS,
},
)
opener = _ropen()
with opener(request, timeout=timeout) as response:
for line in response:
# SSE lines look like b"data: {json}"; the stream ends with "data: [DONE]". # SSE lines look like b"data: {json}"; the stream ends with "data: [DONE]".
if not line.startswith(b"data: "): continue if not line.startswith(b"data: "):
d = line[6:].strip() continue
if d == b"[DONE]": break payload = line[6:].strip()
ch = json.loads(d).get("choices") if payload == b"[DONE]":
if ch and ch[0].get("delta", {}).get("content"): yield ch[0]["delta"]["content"] break
choices = json.loads(payload).get("choices")
if choices and choices[0].get("delta", {}).get("content"):
yield choices[0]["delta"]["content"]
# Persist the GUI choice as "<vision key> <text key>" in out/_global/llm.txt (read by current()). # 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 choose(vision_key, text_key):
CHOICE_FILE.write_text(f"{vision_key} {text_key}")
def content(resp, what): def content(resp, what):
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints).""" """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. # llama.cpp reports timings; cloud APIs report usage instead.
t = resp.get("timings") or {} timings = resp.get("timings") or {}
# Reasoning models: count thinking words for the speed log only. # Reasoning models: count thinking words for the speed log only.
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split()) 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, " if timings:
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) print(
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) f"llm {what}: prompt {timings.get('prompt_n', 0)} tok @ {timings.get('prompt_per_second', 0):.0f} t/s, "
f"gen {timings.get('predicted_n', 0)} tok @ {timings.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"] return resp["choices"][0]["message"]["content"]
# Health probe: llama-server answers /health once the model is loaded. # Health probe: llama-server answers /health once the model is loaded.
def up(port=PORT): def up(port=PORT):
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True try:
except Exception: return False _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. # Launch llama-server on port and wait until /health answers. Returns the Popen, or None if already up.
def _spawn(args, port, log): def _spawn(args, port, log):
# Already serving on this port: reuse it instead of starting a second copy. # Already serving on this port: reuse it instead of starting a second copy.
if up(port): return None 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. # 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) process = subprocess.Popen(
[str(SERVER), *args, "--port", str(port)],
stdout=open(log, "w"), # noqa: SIM115
stderr=subprocess.STDOUT, # noqa: SIM115
)
# Poll every 2 s for up to 20 min: large models take minutes to load. # Poll every 2 s for up to 20 min: large models take minutes to load.
for _ in range(600): for _ in range(600):
if up(port): return p if up(port):
return process
# Server exited (bad args, out of memory): fail now instead of waiting out the timeout. # 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}" assert process.poll() is None, f"llama-server died, see {log}"
time.sleep(2) time.sleep(2)
raise TimeoutError("llama-server not ready") raise TimeoutError("llama-server not ready")
def start(vision=True, port=PORT, log="llama.log"): 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.""" """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. # Cloud choice from the GUI: no local server to start.
if current(vision) in REMOTE: return None if current(vision) in REMOTE:
return None
# MODELS entry: (label, model, mmproj, vision args, text args). # MODELS entry: (label, model, mmproj, vision args, text args).
_, model, mmproj, vargs, targs = MODELS[current(vision)] _, model, mmproj, vision_args, text_args = MODELS[current(vision)]
# Vision: mmproj for images. Text: no mmproj. --jinja applies the model's chat template. # 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) return _spawn(
[
"-m",
str(model),
*(
["--mmproj", str(mmproj), *_fit(vision_args, True)]
if vision
else _fit(text_args, False)
),
"--jinja",
],
port,
log,
)
def start_embed(log="embed.log"): def start_embed(log="embed.log"):
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running.""" """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") 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. # 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) 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). # 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" OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
@@ -307,47 +667,93 @@ MODELS_YML = """providers:
headers: *copilot_headers headers: *copilot_headers
""" """
def install_omp(): def install_omp():
"""omp into bin/ unless one is already available; seed ~/.omp/agent/models.yml (Copilot BYOK models) only if absent.""" """omp into bin/ unless one is already available; seed ~/.omp/agent/models.yml (Copilot BYOK models) only if absent."""
if omp_exe(): print("omp already available:", omp_exe()) if omp_exe():
print("omp already available:", omp_exe())
else: else:
OMP_LOCAL.parent.mkdir(exist_ok=True) OMP_LOCAL.parent.mkdir(exist_ok=True)
ua = {"User-Agent": "teams-whisper-install"} # the build API answers 403 to python-urllib's default UA headers = {
j = json.load(_ropen()(urllib.request.Request(OMP_BUILD, headers=ua), timeout=60)); part = OMP_LOCAL.with_suffix(".part"); h = hashlib.sha256() "User-Agent": "teams-whisper-install"
} # the build API answers 403 to python-urllib's default UA
build_info = json.load(
_ropen()(urllib.request.Request(OMP_BUILD, headers=headers), timeout=60)
)
part = OMP_LOCAL.with_suffix(".part")
digest = hashlib.sha256()
# Stream into .part while hashing; rename only after the sha256 check passes. # 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: with (
while b := r.read(1 << 20): h.update(b); f.write(b) _ropen()(
if h.hexdigest() != j["file"]["sha256"].lower(): part.unlink(); raise RuntimeError("omp download: checksum mismatch") urllib.request.Request(build_info["download"], headers=headers), timeout=900
part.replace(OMP_LOCAL); print("omp", j["build"]["version"], "->", OMP_LOCAL) ) as response,
y = Path.home() / ".omp" / "agent" / "models.yml" open(part, "wb") as out_file,
if y.exists(): print("kept existing", y) ):
else: y.parent.mkdir(parents=True, exist_ok=True); y.write_text(MODELS_YML, encoding="utf-8"); print("written", y) while chunk := response.read(1 << 20):
digest.update(chunk)
out_file.write(chunk)
if digest.hexdigest() != build_info["file"]["sha256"].lower():
part.unlink()
raise RuntimeError("omp download: checksum mismatch")
part.replace(OMP_LOCAL)
print("omp", build_info["build"]["version"], "->", OMP_LOCAL)
models_yml = Path.home() / ".omp" / "agent" / "models.yml"
if models_yml.exists():
print("kept existing", models_yml)
else:
models_yml.parent.mkdir(parents=True, exist_ok=True)
models_yml.write_text(MODELS_YML, encoding="utf-8")
print("written", models_yml)
def login(provider, if_needed=False): 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).""" """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() omp_path = omp_exe()
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio") if not omp_path:
raise RuntimeError("omp non installato: esegui Install da Pinokio")
# if_needed: skip the interactive login when a token is already available. # if_needed: skip the interactive login when a token is already available.
if if_needed: if if_needed:
try: _token(provider); print(provider, "already logged in"); return try:
except RuntimeError: pass _token(provider)
subprocess.run([exe, "login", provider], env=omp_env()) # inherits stdin/stdout: device code / browser URL shown in the Pinokio terminal print(provider, "already logged in")
return
except RuntimeError:
pass
subprocess.run(
[omp_path, "login", provider], env=omp_env()
) # inherits stdin/stdout: device code / browser URL shown in the Pinokio terminal
def download(url, dest):
def download(source_url, dest):
"""Proxy-aware, resumable file download (Pinokio's fs.download goes direct and fails where corp DNS only resolves via the proxy; hf's own TLS stack rejects the corp CA). Skips an existing dest.""" """Proxy-aware, resumable file download (Pinokio's fs.download goes direct and fails where corp DNS only resolves via the proxy; hf's own TLS stack rejects the corp CA). Skips an existing dest."""
dest = Path(dest) dest = Path(dest)
if dest.exists(): print("kept", dest); return if dest.exists():
dest.parent.mkdir(parents=True, exist_ok=True); part = dest.with_name(dest.name + ".part") 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). # Resume: bytes already in .part; ask the server for the rest (Range header).
have = part.stat().st_size if part.exists() else 0 have = part.stat().st_size if part.exists() else 0
h = {"User-Agent": "teams-whisper-install", **({"Range": f"bytes={have}-"} if have else {})} headers = {
"User-Agent": "teams-whisper-install",
**({"Range": f"bytes={have}-"} if have else {}),
}
# Append only if the server honored Range (206); otherwise restart the file. # 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) with (
part.replace(dest); print("downloaded", dest) _ropen()(urllib.request.Request(source_url, headers=headers), timeout=900) as response,
open(part, "ab" if have and response.status == 206 else "wb") as out_file,
):
shutil.copyfileobj(response, out_file, 1 << 20)
part.replace(dest)
print("downloaded", dest)
# CLI entry point: `install-omp`, `login <provider> [--if-needed]`, `download <url> <dest>`. # CLI entry point: `install-omp`, `login <provider> [--if-needed]`, `download <url> <dest>`.
if __name__ == "__main__": if __name__ == "__main__":
a = sys.argv[1:] args = sys.argv[1:]
if a == ["install-omp"]: install_omp() if args == ["install-omp"]:
elif a[:1] == ["login"]: login(a[1], "--if-needed" in a) install_omp()
elif a[:1] == ["download"]: download(a[1], a[2]) elif args[:1] == ["login"]:
login(args[1], "--if-needed" in args)
elif args[:1] == ["download"]:
download(args[1], args[2])
+114 -49
View File
@@ -6,93 +6,158 @@
Usage: uv run meet.py [--screen] [--name meet_...] Usage: uv run meet.py [--screen] [--name meet_...]
Any Teams (desktop or web) works: loopback captures whatever plays on default speakers. Any Teams (desktop or web) works: loopback captures whatever plays on default speakers.
""" """
import argparse, subprocess, sys, time, wave, threading
import argparse
import subprocess
import time
import wave
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
import pyaudiowpatch as pa import pyaudiowpatch as pa
# CLI: --screen adds video, --name sets the folder under out/, --seconds auto-stops. # CLI: --screen adds video, --name sets the folder under out/, --seconds auto-stops.
ap = argparse.ArgumentParser() parser = argparse.ArgumentParser()
ap.add_argument("--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)") parser.add_argument(
ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S")) "--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)"
ap.add_argument("--seconds", type=float, help="auto-stop after N seconds") )
a = ap.parse_args() parser.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
out = Path(__file__).parent / "out" / a.name; out.mkdir(parents=True, exist_ok=True) # out/<name>/source.mp4 + source.wav parser.add_argument("--seconds", type=float, help="auto-stop after N seconds")
args = parser.parse_args()
out = Path(__file__).parent / "out" / args.name
out.mkdir(parents=True, exist_ok=True) # out/<name>/source.mp4 + source.wav
# Output rate: matches what transcription expects (16 kHz mono). # Output rate: matches what transcription expects (16 kHz mono).
SR = 16000 SAMPLE_RATE = 16000
# Downmix to mono, then resample to SAMPLE_RATE by linear interpolation (simple, fine for speech).
def to16k(samples, channels, sample_rate):
samples = samples.reshape(-1, channels).mean(axis=1)
count = int(len(samples) * SAMPLE_RATE / sample_rate)
return np.interp(
np.linspace(0, len(samples) - 1, count), np.arange(len(samples)), samples
).astype(np.float32)
# 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. # Capture system audio (WASAPI loopback = what plays on the speakers) and the default mic.
def record(): def record():
p = pa.PyAudio() audio_interface = pa.PyAudio()
# Loopback device and default mic device. # Loopback device and default mic device.
lb = p.get_default_wasapi_loopback() loopback_device = audio_interface.get_default_wasapi_loopback()
mic = p.get_device_info_by_index(p.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"]) mic_device = audio_interface.get_device_info_by_index(
bufs = {"sys": [], "mic": []} audio_interface.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"]
)
buffers = {"sys": [], "mic": []}
streams = [] streams = []
# One stream per source, at the device's own channel count and rate; converted to 16 kHz mono in the mix step. # 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)): for key, device in (("sys", loopback_device), ("mic", mic_device)):
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"]) channels, sample_rate = int(device["maxInputChannels"]), int(device["defaultSampleRate"])
# Callback appends raw PCM chunks; paContinue keeps the stream running. # 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) def callback(data, frame_count, time_info, status_flags, key=key):
buffers[key].append(data)
return (None, pa.paContinue)
# int16 PCM, 1024-frame buffers. # int16 PCM, 1024-frame buffers.
st = p.open(format=pa.paInt16, channels=ch, rate=sr, input=True, stream = audio_interface.open(
input_device_index=d["index"], frames_per_buffer=1024, stream_callback=cb) format=pa.paInt16,
streams.append((key, ch, sr, st)) channels=channels,
print(f"loopback: {lb['name']}\nmic: {mic['name']}") rate=sample_rate,
ff = None input=True,
input_device_index=device["index"],
frames_per_buffer=1024,
stream_callback=callback,
)
streams.append((key, channels, sample_rate, stream))
print(f"loopback: {loopback_device['name']}\nmic: {mic_device['name']}")
ffmpeg_process = None
# Optional screen capture: ffmpeg gdigrab at 15 fps, H.264 mp4. # Optional screen capture: ffmpeg gdigrab at 15 fps, H.264 mp4.
if a.screen: if args.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop", ffmpeg_process = subprocess.Popen(
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", [
str(out / "source.mp4")], stdin=subprocess.PIPE, "ffmpeg",
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) "-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") print("Recording... Ctrl+C to stop")
# Wait until Ctrl+C or the --seconds limit. # Wait until Ctrl+C or the --seconds limit.
try: try:
t0 = time.time() start_time = time.time()
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5) while not args.seconds or time.time() - start_time < args.seconds:
except KeyboardInterrupt: pass time.sleep(0.5)
except KeyboardInterrupt:
pass
# Send 'q' so ffmpeg finalises the mp4 cleanly. # Send 'q' so ffmpeg finalises the mp4 cleanly.
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait() if ffmpeg_process:
ffmpeg_process.stdin.write(b"q")
ffmpeg_process.stdin.flush()
ffmpeg_process.wait()
# Stop PortAudio. # Stop PortAudio.
p.terminate() audio_interface.terminate()
# Mix: decode each stream and convert to 16 kHz mono float in [-1, 1]. # Mix: decode each stream and convert to 16 kHz mono float in [-1, 1].
mix = [] mixed_sources = []
for key, ch, sr, st in streams: for key, channels, sample_rate, _stream in streams:
raw = np.frombuffer(b"".join(bufs[key]), dtype=np.int16).astype(np.float32) / 32768 raw = np.frombuffer(b"".join(buffers[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw): mix.append(to16k(raw[: len(raw) // ch * ch], ch, sr)) if len(raw):
mixed_sources.append(
to16k(raw[: len(raw) // channels * channels], channels, sample_rate)
)
# Pad shorter streams with silence and sum them. # Pad shorter streams with silence and sum them.
n = max(len(m) for m in mix) max_length = max(len(source) for source in mixed_sources)
y = sum(np.pad(m, (0, n - len(m))) for m in mix) mixed = sum(np.pad(source, (0, max_length - len(source))) for source in mixed_sources)
# Clip to avoid overflow when summing. # Clip to avoid overflow when summing.
y = np.clip(y, -1, 1) mixed = np.clip(mixed, -1, 1)
path = out / "source.wav" path = out / "source.wav"
# Write a 16-bit mono WAV. # Write a 16-bit mono WAV.
with wave.open(str(path), "wb") as w: with wave.open(str(path), "wb") as wav_file:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR) wav_file.setnchannels(1)
w.writeframes((y * 32767).astype(np.int16).tobytes()) wav_file.setsampwidth(2)
wav_file.setframerate(SAMPLE_RATE)
wav_file.writeframes((mixed * 32767).astype(np.int16).tobytes())
return path return path
# Save the DB row, then run the transcription/report pipeline (flow.py) as a child uv process. # Save the DB row, then run the transcription/report pipeline (flow.py) as a child uv process.
def finish(path): def finish(path):
import os import os
import db import db
now = time.strftime("%Y-%m-%d %H:%M:%S") now = time.strftime("%Y-%m-%d %H:%M:%S")
# Queued DB row with the start and end time. # Queued DB row with the start and end time.
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued") db.upsert_recording(
args.name, source="meet", started_at=start_timestamp, ended_at=now, status="queued"
)
# Drop inherited PYTHONHOME vars so the child uv/python picks its own interpreter. # 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")} env = {
key: value
for key, value in os.environ.items()
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
}
# Point the child at the local Prefect server; bypass the proxy for localhost. # 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") 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) subprocess.run(
["uv", "run", "--script", "flow.py", args.name], cwd=Path(__file__).parent, env=env
)
# Start timestamp stored in the DB row. # Start timestamp stored in the DB row.
T0 = time.strftime("%Y-%m-%d %H:%M:%S") start_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
# Record, then hand off to the pipeline. # Record, then hand off to the pipeline.
finish(record()) finish(record())
+197 -77
View File
@@ -4,9 +4,17 @@
# /// # ///
"""Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db. """Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db.
uv run --script memory.py --reindex""" uv run --script memory.py --reindex"""
import contextlib, json, re, sys, urllib.request
import contextlib
import json
import re
import sys
import urllib.request
import db
import llama
import numpy as np import numpy as np
import db, llama, report import report
# bge-m3 embeddings endpoint on the local embedding server. # bge-m3 embeddings endpoint on the local embedding server.
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings" API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
@@ -15,126 +23,209 @@ MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
# Direct opener bypassing the corp proxy (the embedding server is localhost). # Direct opener bypassing the corp proxy (the embedding server is localhost).
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
# Italian prompt: link current-meeting topics to earlier excerpts; JSON output. # 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"}]}. ' 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. ' '"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.') '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]. # 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 in testo semplice (niente JSON). Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.' SYS_ASK = "Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi in testo semplice (niente JSON). 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. # Valid link statuses; anything else from the LLM is dropped.
STATUSES = {"confermato", "cambiato", "aperto", "contesto"} STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
# Start the CPU embedding server for the block; stop it on exit only if this call started it. # Start the CPU embedding server for the block; stop it on exit only if this call started it.
@contextlib.contextmanager @contextlib.contextmanager
def embedder(log): def embedder(log_path):
p = llama.start_embed(log=log) embed_process = llama.start_embed(log=log_path)
try: yield try:
yield
finally: finally:
if p is not None: p.terminate() if embed_process is not None:
embed_process.terminate()
# Embed texts via the local embedding server, 32 per request, each cut to 2000 chars. # Embed texts via the local embedding server, 32 per request, each cut to 2000 chars.
def embed(texts): def embed(texts):
out = [] vectors = []
for i in range(0, len(texts), 32): for start in range(0, len(texts), 32):
body = {"input": [x[:2000] for x in texts[i:i + 32]], "model": "bge-m3"} body = {"input": [text[:2000] for text in texts[start : start + 32]], "model": "bge-m3"}
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600)) response = json.load(
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])] _open(
v = np.array(out, dtype=np.float32) urllib.request.Request(
API, json.dumps(body).encode(), {"Content-Type": "application/json"}
),
timeout=600,
)
)
vectors += [
item["embedding"] for item in sorted(response["data"], key=lambda item: item["index"])
]
matrix = np.array(vectors, dtype=np.float32)
# L2-normalize so dot products are cosine similarities. # L2-normalize so dot products are cosine similarities.
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9) return matrix / np.maximum(np.linalg.norm(matrix, axis=1, keepdims=True), 1e-9)
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none. # Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
def _stamp(n): def _stamp(name):
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n) match = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", name)
return m[0] if m else "" return match[0] if match else ""
# Load memory rows matching pred and stack their vectors into an (n, dim) matrix. # Load memory rows matching pred and stack their vectors into an (n, dim) matrix.
def _rows(pred): def _rows(pred):
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k. # 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)] rows = [row for row in db.connect().execute("SELECT * FROM memory") if pred(row)]
if not rows: return [], None if not rows:
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1) return [], None
return rows, np.frombuffer(b"".join(row["vec"] for row in rows), np.float32).reshape(
len(rows), -1
)
# Summary entries may be dicts {"text": ...} or plain strings. # Summary entries may be dicts {"text": ...} or plain strings.
def _txt(x): return x["text"] if isinstance(x, dict) else str(x) def _summary_text(item):
return item["text"] if isinstance(item, dict) else str(item)
# Topic as one string: title (optional), summary, decisions, open questions. # Topic as one string: title (optional), summary, decisions, open questions.
def _topic_text(t, title=True): def _topic_text(topic, 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", [])) parts = (
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p) ([topic["title"]] if title else [])
+ [_summary_text(item) for item in topic.get("summary", [])]
+ list(topic.get("decisions", []))
+ list(topic.get("open_questions", []))
)
return (
". ".join(part for part in parts if part)
if title
else " ".join(part for part in parts if part)
)
# Embed one meeting's report items into the memory table (replaces its previous rows). # Embed one meeting's report items into the memory table (replaces its previous rows).
def index(name): def index(name):
# slugify matches the report's heading anchors. # slugify matches the report's heading anchors.
from markdown.extensions.toc import slugify from markdown.extensions.toc import slugify
rep = report._load(name, "report.json", None)
if rep is None: return report_json = report._load(name, "report.json", None)
rep, _ = report.named(name, rep) if report_json is None:
return
report_json, _ = report.named(name, report_json)
items = [] items = []
# One item per topic summary, decision, action and open question. # One item per topic summary, decision, action and open question.
for i, t in enumerate(rep["topics"], 1): for topic_index, topic in enumerate(report_json["topics"], 1):
# Shared fields of every item of this topic: (name, position, start, meeting, date, title, anchor). # 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), "-")) base = (
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])] name,
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])] topic_index,
its += [("open_question", x) for x in t.get("open_questions", [])] topic["start_s"],
items += [(base, k, x) for k, x in its if x] report_json["meeting_title"],
report_json["date"],
topic["title"],
slugify(report._head(topic_index, topic), "-"),
)
topic_items = [("topic", _topic_text(topic, False))] + [
("decision", decision) for decision in topic.get("decisions", [])
]
topic_items += [
(
"action",
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key)),
)
for action in topic.get("actions", [])
]
topic_items += [("open_question", question) for question in topic.get("open_questions", [])]
items += [(base, kind, text) for kind, text in topic_items if text]
# Nothing to index: clear the old rows for this meeting. # Nothing to index: clear the old rows for this meeting.
if not items: db.replace_memory(name, []); return if not items:
db.replace_memory(name, [])
return
# Prefix the title so each item's vector carries its topic context. # Prefix the title so each item's vector carries its topic context.
V = embed([f"{b[5]}: {x}" for b, _, x in items]) vectors = embed([f"{base[5]}: {text}" for base, _, text in items])
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)]) db.replace_memory(
name,
[
(*base[:2], kind, *base[2:], text, vector.tobytes())
for (base, kind, text), vector in zip(items, vectors, strict=False)
],
)
print(f"memory: indexed {len(items)} items") print(f"memory: indexed {len(items)} items")
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, text. # 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']}" def _prev_line(number, row):
return f"[{number}] {row['date']} «{row['meeting']}» — {row['topic']} ({row['kind']}): {row['text']}"
# Link this meeting's topics to earlier meetings; results go into report.json. # Link this meeting's topics to earlier meetings; results go into report.json.
def _link(name): def _link(name):
rep = report._load(name, "report.json", None) report_json = report._load(name, "report.json", None)
if rep is None: return if report_json is None:
named_rep, _ = report.named(name, rep) return
named_report, _ = report.named(name, report_json)
# Stamp of this meeting, from its folder name. # Stamp of this meeting, from its folder name.
cur = _stamp(name) current_stamp = _stamp(name)
# Only strictly earlier meetings; stamps sort lexicographically. # Only strictly earlier meetings; stamps sort lexicographically.
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur) rows, matrix = _rows(
lambda row: current_stamp and _stamp(row["name"]) and _stamp(row["name"]) < current_stamp
)
# Clear old links so re-running the step does not accumulate them. # Clear old links so re-running the step does not accumulate them.
for t in rep["topics"]: t["previous"] = [] for topic in report_json["topics"]:
topic["previous"] = []
if rows: if rows:
# Query vectors: each current topic as title + content. # Query vectors: each current topic as title + content.
Q = embed([_topic_text(t) for t in named_rep["topics"]]) query_vectors = embed([_topic_text(topic) for topic in named_report["topics"]])
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized). # Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
S = Q @ M.T similarity = query_vectors @ matrix.T
for t, nt, s in zip(rep["topics"], named_rep["topics"], S): for topic, named_topic, similarities in zip(
report_json["topics"], named_report["topics"], similarity, strict=False
):
# Best K_TOPIC candidates above the MEM_MIN similarity threshold. # 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] top = [
if not top: continue index
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", [])) for index in np.argsort(-similarities)[:K_TOPIC]
if similarities[index] >= MEM_MIN
]
if not top:
continue
actions = "; ".join(
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key))
for action in named_topic.get("actions", [])
)
# Prompt: current topic, then numbered earlier excerpts the model may cite as [n]. # 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" user = (
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n" f"ARGOMENTO: {named_topic['title']}\nSINTESI: {' '.join(_summary_text(item) for item in named_topic.get('summary', []))}\nDECISIONI: {'; '.join(named_topic.get('decisions', []))}\n"
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1))) f"AZIONI: {actions}\nDOMANDE APERTE: {'; '.join(named_topic.get('open_questions', []))}\n\nPRECEDENTI:\n"
+ "\n".join(_prev_line(number, rows[index]) for number, index in enumerate(top, 1))
)
# report.chat returns parsed JSON or None; None -> no links. # report.chat returns parsed JSON or None; None -> no links.
r = report.chat(SYS_M, user, 1500) or {} response = report.chat(SYS_M, user, 1500) or {}
# Cap at 4 links per topic (matches the prompt). # Cap at 4 links per topic (matches the prompt).
for l in (r.get("links") or [])[:4]: for link in (response.get("links") or [])[:4]:
# Validate LLM output: ref in range, known status, non-empty text. # Validate LLM output: ref in range, known status, non-empty text.
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip() try:
except (KeyError, TypeError, ValueError): continue ref, status, text = int(link["ref"]), link["status"], str(link["text"]).strip()
if 1 <= ref <= len(top) and st in STATUSES and tx: except (KeyError, TypeError, ValueError):
p = rows[top[ref - 1]] continue
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"], if 1 <= ref <= len(top) and status in STATUSES and text:
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]}) previous = rows[top[ref - 1]]
topic["previous"].append(
{
"text": text,
"status": status,
"name": previous["name"],
"meeting": previous["meeting"],
"date": previous["date"],
"topic": previous["topic"],
"anchor": previous["anchor"],
"t": previous["t"],
}
)
# Write links into report.json; run() re-renders from it. # 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") (db.out_dir(name) / "report.json").write_text(
json.dumps(report_json, ensure_ascii=False, indent=1), encoding="utf-8"
)
def run(name, link=True): def run(name, link=True):
@@ -143,27 +234,55 @@ def run(name, link=True):
# Embedder lives for linking and indexing; its log sits with the meeting logs. # Embedder lives for linking and indexing; its log sits with the meeting logs.
with embedder(db.logs(name) / "embed.log"): with embedder(db.logs(name) / "embed.log"):
if link: if link:
try: _link(name) try:
except Exception as e: print("memory link skipped:", repr(e)) _link(name)
except Exception as error:
print("memory link skipped:", repr(error))
index(name) index(name)
except Exception as e: print("memory index skipped:", repr(e)) except Exception as error:
print("memory index skipped:", repr(error))
# Render even when the memory steps failed. # Render even when the memory steps failed.
report.render(name) report.render(name)
# Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n]. # Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n].
# Generator: first {"sources": [...]}, then {"t": text delta} events as the model writes. # Generator: first {"sources": [...]}, then {"t": text delta} events as the model writes.
def ask_stream(q): def ask_stream(question):
# Cosine search over the normalized matrix; keep the best K_ASK excerpts. # Cosine search over the normalized matrix; keep the best K_ASK excerpts.
rows, M = _rows(lambda r: True) rows, matrix = _rows(lambda row: True)
if not rows: yield {"sources": []}; yield {"t": "Nessuna riunione indicizzata."}; return if not rows:
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK] yield {"sources": []}
rs = [rows[j] for j in top] yield {"t": "Nessuna riunione indicizzata."}
yield {"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]} return
body = {"temperature": 0.2, "max_tokens": 1500, "chat_template_kwargs": {"enable_thinking": False}, top = np.argsort(-(matrix @ embed([question])[0]))[:K_ASK]
"messages": [{"role": "system", "content": SYS_ASK}, selected = [rows[index] for index in top]
{"role": "user", "content": f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1))}]} yield {
for d in llama.stream(body, 1800): yield {"t": d} "sources": [
{
"n": number,
**{
key: row[key]
for key in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")
},
}
for number, row in enumerate(selected, 1)
]
}
body = {
"temperature": 0.2,
"max_tokens": 1500,
"chat_template_kwargs": {"enable_thinking": False},
"messages": [
{"role": "system", "content": SYS_ASK},
{
"role": "user",
"content": f"DOMANDA: {question}\n\nESTRATTI:\n"
+ "\n".join(_prev_line(number, row) for number, row in enumerate(selected, 1)),
},
],
}
for delta in llama.stream(body, 1800):
yield {"t": delta}
if __name__ == "__main__": if __name__ == "__main__":
@@ -172,4 +291,5 @@ if __name__ == "__main__":
# CLI: rebuild the memory index for every meeting that has a report.json. # CLI: rebuild the memory index for every meeting that has a report.json.
if "--reindex" in sys.argv: if "--reindex" in sys.argv:
with embedder(db.GLOBAL / "embed.log"): with embedder(db.GLOBAL / "embed.log"):
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name) for path in sorted(db.OUT.glob("*/report.json")):
index(path.parent.name)
+749 -310
View File
File diff suppressed because it is too large Load Diff
+137 -80
View File
@@ -2,10 +2,17 @@
# dependencies = [] # dependencies = []
# /// # ///
"""Quality gate for meeting reports. uv run --script review.py <name> [<name>...]; exit 1 if any fails. No network/LLM.""" """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 base64
import json
import re
import struct
import sys
import db import db
# Shared helpers from report.py: ticket regex, key normaliser, name similarity. # Shared helpers from report.py: ticket regex, key normaliser, name similarity.
from report import TICKET, _key, _sim from report import _sim
from shots import CONTENT_KINDS from shots import CONTENT_KINDS
# Stopwords used by english() to tell English from Italian text. # Stopwords used by english() to tell English from Italian text.
@@ -14,135 +21,185 @@ 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. # True if text is mostly English: at least 3 English stopwords and more than Italian ones.
def english(s): def english(text):
w = re.findall(r"[a-zà-ú]+", str(s).lower()) words = re.findall(r"[a-zà-ú]+", str(text).lower())
e, i = sum(x in ENG for x in w), sum(x in ITA for x in w) english_count, italian_count = (
return e >= 3 and e > i sum(word in ENG for word in words),
sum(word in ITA for word in words),
)
return english_count >= 3 and english_count > italian_count
# Read image width from the JPEG SOF marker (0 if not found). # Read image width from the JPEG SOF marker (0 if not found).
def jpeg_w(p): def jpeg_w(path):
b = p.read_bytes(); i = 2 data = path.read_bytes()
while i < len(b): index = 2
while index < len(data):
# Skip non-marker bytes. # Skip non-marker bytes.
if b[i] != 0xFF: i += 1; continue if data[index] != 0xFF:
m = b[i + 1] index += 1
continue
marker = data[index + 1]
# SOF0-SOF2: frame header holds height, then width (2 bytes each). # 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] if marker in (0xC0, 0xC1, 0xC2):
return struct.unpack(">H", data[index + 7 : index + 9])[0]
# Jump over this segment using its length field. # Jump over this segment using its length field.
i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0] index += 2 + struct.unpack(">H", data[index + 2 : index + 4])[0]
return 0 return 0
# Run all quality rules on one meeting's outputs; print failures; True if none. # Run all quality rules on one meeting's outputs; print failures; True if none.
def review(name): def review(name):
d = db.out_dir(name) out_dir = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8")) report = json.loads((out_dir / "report.json").read_text(encoding="utf-8"))
md = (d / "report.md").read_text(encoding="utf-8") markdown_text = (out_dir / "report.md").read_text(encoding="utf-8")
html = (d / "report.html").read_text(encoding="utf-8") html_text = (out_dir / "report.html").read_text(encoding="utf-8")
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else [] shots = (
docs = json.loads((d / "docs.json").read_text(encoding="utf-8")) if (d / "docs.json").exists() else None json.loads((out_dir / "shots.json").read_text(encoding="utf-8"))
if (out_dir / "shots.json").exists()
else []
)
docs = (
json.loads((out_dir / "docs.json").read_text(encoding="utf-8"))
if (out_dir / "docs.json").exists()
else None
)
items = (docs or {}).get("items", []) items = (docs or {}).get("items", [])
fails = [] fails = []
# Record a failure with its rule code (R1-R12). # Record a failure with its rule code (R1-R12).
F = lambda code, detail: fails.append(f"FAIL {code} {str(detail)[:200]}") def fail(code, detail):
return fails.append(f"FAIL {code} {str(detail)[:200]}")
# R1: no generic 'Speaker N' labels left in the report. # 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", " ")) for match in re.finditer(r"\bSpeaker \d+\b", markdown_text):
fail("R1", markdown_text[max(0, match.start() - 40) : match.end() + 40].replace("\n", " "))
# R2: topic count between dur/900 and dur/150 (min 3 / 4), so long calls get more topics. # 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"] topics, duration = report["topics"], report["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") if not max(3, duration / 900) <= len(topics) <= max(4, duration / 150):
fail("R2", f"{len(topics)} topics for {duration / 60:.0f} min")
# R2: every topic except the last must span at least 2 min. # R2: every topic except the last must span at least 2 min.
for t in T[:-1]: for topic in topics[:-1]:
if t["end_s"] - t["start_s"] < 120: F("R2", f"short topic {t['title']} {t['end_s'] - t['start_s']}s") if topic["end_s"] - topic["start_s"] < 120:
for t in T: fail("R2", f"short topic {topic['title']} {topic['end_s'] - topic['start_s']}s")
for x in t["shown"]: for topic in topics:
for shown_time in topic["shown"]:
# R3: each shown timestamp must fall inside the topic span (+/-30 s). # R3: each shown timestamp must fall inside the topic span (+/-30 s).
m = re.search(r"(\d\d):(\d\d)", x) match = re.search(r"(\d\d):(\d\d)", shown_time)
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}") if (
not match
or not topic["start_s"] - 30
<= int(match[1]) * 60 + int(match[2])
<= topic["end_s"] + 30
):
fail("R3", f"{topic['title']}: {shown_time}")
byfile = {} shot_by_name = {}
# Index shots by file name and by cropped view name, for R4. # 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 for shot in shots:
shot_by_name[shot["file"]] = shot_by_name[shot.get("view") or shot["file"]] = shot
# R4: at most 2 images per section. # R4: at most 2 images per section.
for sec in re.split(r"\n(?=## )", md): for section in re.split(r"\n(?=## )", markdown_text):
imgs = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", sec) images = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", section)
if len(imgs) > 2: F("R4", f">2 images in {sec[:40]!r}") if len(images) > 2:
fail("R4", f">2 images in {section[:40]!r}")
# R4: every image used must be a content screen (CONTENT_KINDS). # R4: every image used must be a content screen (CONTENT_KINDS).
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", md) used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", markdown_text)
for f in used: for file_name in used:
if byfile.get(f, {}).get("kind") not in CONTENT_KINDS: F("R4", f"{f} kind {byfile.get(f, {}).get('kind')}") if shot_by_name.get(file_name, {}).get("kind") not in CONTENT_KINDS:
fail("R4", f"{file_name} kind {shot_by_name.get(file_name, {}).get('kind')}")
# R4: if cropping was applied, every image must be a cropped view_ file. # 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): if any((shot.get("view") or "").startswith("view_") for shot in shots):
for f in used: for file_name in used:
if not f.startswith("view_"): F("R4", f"uncropped image {f}") if not file_name.startswith("view_"):
fail("R4", f"uncropped image {file_name}")
# R5: collect all prose fields to check for English. # R5: collect all prose fields to check for English.
texts = list(rep["tldr"]) texts = list(report["tldr"])
for t in T: for topic in topics:
texts += [x["text"] if isinstance(x, dict) else x for x in t["summary"]] + [x["text"] for x in t.get("from_docs", [])] texts += [item["text"] if isinstance(item, dict) else item for item in topic["summary"]] + [
texts += [s.get("summary") or "" for s in t["shots"]] item["text"] for item in topic.get("from_docs", [])
for x in texts: ]
if english(x): F("R5", x) texts += [shot.get("summary") or "" for shot in topic["shots"]]
for text in texts:
if english(text):
fail("R5", text)
# R6: read the participants section (table rows or comma list). # R6: read the participants section (table rows or comma list).
sec = re.search(r"## Partecipanti\n(.*?)(?=\n## )", md, re.S) section = re.search(r"## Partecipanti\n(.*?)(?=\n## )", markdown_text, re.S)
people = [] people = []
for l in (sec[1].splitlines() if sec else []): for line in section[1].splitlines() if section else []:
if l.startswith("|"): if line.startswith("|"):
c = l.split("|")[1].strip() cell = line.split("|")[1].strip()
if c not in ("Partecipante", "") and not c.startswith("-"): people.append(c) if cell not in ("Partecipante", "") and not cell.startswith("-"):
elif l.strip() and not l.startswith("*"): people += [x.strip() for x in l.split(",")] people.append(cell)
elif line.strip() and not line.startswith("*"):
people += [name_part.strip() for name_part in line.split(",")]
# R6: no initials or truncated names. # R6: no initials or truncated names.
for p in people: for person in people:
if re.fullmatch(r"[A-Z]{1,3}", p) or "..." in p or "…" in p: F("R6", f"initials/truncated {p}") if re.fullmatch(r"[A-Z]{1,3}", person) or "..." in person or "…" in person:
fail("R6", f"initials/truncated {person}")
# R6: no two participants that look like the same person (similarity >= 0.82). # R6: no two participants that look like the same person (similarity >= 0.82).
for i, a in enumerate(people): for index, first in enumerate(people):
for b in people[i + 1:]: for second in people[index + 1 :]:
if _sim(a, b) >= 0.82: F("R6", f"{a} ~ {b}") if _sim(first, second) >= 0.82:
fail("R6", f"{first} ~ {second}")
# R7: share segments must be >= 20 s and not split by a gap of <= 60 s. # R7: share segments must be >= 20 s and not split by a gap of <= 60 s.
S = rep["shares"] shares = report["shares"]
for s in S: for share in shares:
if s["end"] - s["start"] < 20: F("R7", f"short share {s}") if share["end"] - share["start"] < 20:
for a, b in zip(S, S[1:]): fail("R7", f"short share {share}")
if a["who"] == b["who"] and b["start"] - a["end"] <= 60: F("R7", f"mergeable {a['who']} {a['end']}->{b['start']}") for previous, current in zip(shares, shares[1:], strict=False):
if previous["who"] == current["who"] and current["start"] - previous["end"] <= 60:
fail("R7", f"mergeable {previous['who']} {previous['end']}->{current['start']}")
# R8: ticket keys from the report's Ticket section. # R8: ticket keys from the report's Ticket section.
rs = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", md, re.S) ticket_section = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", markdown_text, re.S)
# R8: allowed keys: Jira-verified when docs ran, else keys from references. # 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 allowed_keys = (
else {x["key"] for x in rep["references"]["tickets"]}) {item["key"] for item in items if item["source"] == "jira" and item.get("mentioned")}
for k in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", rs[1] if rs else ""): if docs is not None
if k not in ok: F("R8", f"ticket {k}") else {item["key"] for item in report["references"]["tickets"]}
)
for key in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", ticket_section[1] if ticket_section else ""):
if key not in allowed_keys:
fail("R8", f"ticket {key}")
# R8: no raw number or e-mail lists. # R8: no raw number or e-mail lists.
if "Numeri a schermo" in md or "**Email**" in md: F("R8", "numbers/email lists present") if "Numeri a schermo" in markdown_text or "**Email**" in markdown_text:
fail("R8", "numbers/email lists present")
# R9: docs section must exist and citation links must point to fetched docs. # R9: docs section must exist and citation links must point to fetched docs.
if items: if items:
if "## Documentazione correlata" not in md: F("R9", "missing Documentazione correlata") if "## Documentazione correlata" not in markdown_text:
urls = {x["url"] for x in items} fail("R9", "missing Documentazione correlata")
urls = {item["url"] for item in items}
# Citation icon links in the markdown. # Citation icon links in the markdown.
for u in re.findall(r"\[📄\]\(([^ )]+)", md): for url in re.findall(r"\[📄\]\(([^ )]+)", markdown_text):
if u not in urls: F("R9", f"citation url not in docs {u}") if url not in urls:
fail("R9", f"citation url not in docs {url}")
# R10: HTML must embed images, not reference shots/ paths. # R10: HTML must embed images, not reference shots/ paths.
if 'src="shots/' in html: F("R10", "unembedded image") if 'src="shots/' in html_text:
for b in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html): fail("R10", "unembedded image")
for encoded in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html_text):
# R10: an embedded image under 5000 bytes is a placeholder. # R10: an embedded image under 5000 bytes is a placeholder.
if len(base64.b64decode(b)) <= 5000: F("R10", "tiny image") if len(base64.b64decode(encoded)) <= 5000:
fail("R10", "tiny image")
# R11: transcript must not be included in the report. # R11: transcript must not be included in the report.
if "## Trascrizione" in md: F("R11", "transcript present") if "## Trascrizione" in markdown_text:
for f in set(used): fail("R11", "transcript present")
for file_name in set(used):
# R12: cropped views must be at least 600 px wide. # 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") if file_name.startswith("view_") and jpeg_w(out_dir / "shots" / file_name) < 600:
fail("R12", f"{file_name} narrow {jpeg_w(out_dir / 'shots' / file_name)}px")
print("\n".join(f"[{name}] {x}" for x in fails)) print("\n".join(f"[{name}] {item}" for item in fails))
print(f"{name}: " + ("PASS" if not fails else f"{len(fails)} failures")) print(f"{name}: " + ("PASS" if not fails else f"{len(fails)} failures"))
return not fails return not fails
if __name__ == "__main__": if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8") sys.stdout.reconfigure(encoding="utf-8")
sys.exit(0 if all([review(n) for n in sys.argv[1:]]) else 1) sys.exit(0 if all(review(name) for name in sys.argv[1:]) else 1)
+1007 -392
View File
File diff suppressed because it is too large Load Diff
+378 -125
View File
@@ -1,40 +1,124 @@
"""Screen content extraction: scene-change keyframes -> local VLM reads each into structured JSON.""" """Screen content extraction: scene-change keyframes -> local VLM reads each into structured JSON."""
import base64, collections, json, re, subprocess, urllib.error, urllib.request
import db, llama import base64
import collections
import json
import re
import subprocess
import urllib.error
import urllib.request
import db
import llama
# Fallback result when a frame can't be read: all schema keys present, neutral values. # 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} 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). # 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"} CONTENT_KINDS = {
"slide",
"code",
"terminal",
"browser",
"document",
"spreadsheet",
"diagram",
"dashboard",
"ticket",
}
# Crop frames to the model-reported shared-content box (see _view). # Crop frames to the model-reported shared-content box (see _view).
CROP_BOX = True CROP_BOX = True
# Allowed values for 'kind'; also the grammar enum in SCHEMA. # Allowed values for 'kind'; also the grammar enum in SCHEMA.
KINDS = ["slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket", "chat", "video_tiles", "other"] KINDS = [
# Schema shorthands: _S bounded string, _N nullable string, _L bounded string list. "slide",
_S, _N, _L = {"type": "string", "maxLength": 300}, {"type": ["string", "null"], "maxLength": 200}, {"type": "array", "items": {"type": "string", "maxLength": 120}, "maxItems": 25} "code",
"terminal",
"browser",
"document",
"spreadsheet",
"diagram",
"dashboard",
"ticket",
"chat",
"video_tiles",
"other",
]
# Schema shorthands: _BOUNDED_STR bounded string, _NULLABLE_STR nullable string, _STR_LIST bounded string list.
_BOUNDED_STR, _NULLABLE_STR, _STR_LIST = (
{"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) # json_schema -> llama.cpp grammar: valid JSON + valid kind every time (small models broke JSON / looped to max_tokens)
SCHEMA = {"type": "object", "additionalProperties": False, SCHEMA = {
"required": ["kind", "title", "app", "summary", "text", "entities", "people", "presenter", "meeting_title", "content_box"], "type": "object",
"properties": {"kind": {"enum": KINDS}, "title": _N, "app": _N, "summary": _S, "text": {"type": "string", "maxLength": 1500}, # bounds stop the 4B looping on table rows "additionalProperties": False,
"entities": {"type": "object", "additionalProperties": False, "required": ["systems", "tickets", "urls", "numbers", "terms"], "required": [
"properties": {k: _L for k in ("systems", "tickets", "urls", "numbers", "terms")}}, "kind",
"people": _L, "presenter": _N, "meeting_title": _N, "title",
"content_box": {"anyOf": [{"type": "array", "items": {"type": "integer"}, "minItems": 4, "maxItems": 4}, {"type": "null"}]}}} "app",
"summary",
"text",
"entities",
"people",
"presenter",
"meeting_title",
"content_box",
],
"properties": {
"kind": {"enum": KINDS},
"title": _NULLABLE_STR,
"app": _NULLABLE_STR,
"summary": _BOUNDED_STR,
"text": {"type": "string", "maxLength": 1500}, # bounds stop the 4B looping on table rows
"entities": {
"type": "object",
"additionalProperties": False,
"required": ["systems", "tickets", "urls", "numbers", "terms"],
"properties": dict.fromkeys(
("systems", "tickets", "urls", "numbers", "terms"), _STR_LIST
),
},
"people": _STR_LIST,
"presenter": _NULLABLE_STR,
"meeting_title": _NULLABLE_STR,
"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 # 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. # (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. # 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,' 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' '"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' "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"
'- kind: type of the shared content; video_tiles ONLY if no screen is shared (just participant videos), chat for a chat panel.\n' "- kind: type of the shared content; video_tiles ONLY if no screen is shared (just participant videos), chat for a chat panel.\n"
'- title: the visible heading of the shared content: slide title, page/document title, active browser tab title or window title (e.g. "Sprint Review Q3 - Backlog"). null only if no title is readable.\n' '- title: the visible heading of the shared content: slide title, page/document title, active browser tab title or window title (e.g. "Sprint Review Q3 - Backlog"). null only if no title is readable.\n'
'- app: application or website shown (e.g. "Confluence", "Grafana", "Excel").\n' '- app: application or website shown (e.g. "Confluence", "Grafana", "Excel").\n'
'- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori) e perché conta. Inizia direttamente con il contenuto.\n' "- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori) e perché conta. Inizia direttamente con il contenuto.\n"
'- text: important visible text copied verbatim (headings, bullets, table rows with values, code lines, errors, form values), max 1500 characters, keep line breaks.\n' "- text: important visible text copied verbatim (headings, bullets, table rows with values, code lines, errors, form values), max 1500 characters, keep line breaks.\n"
'- entities.systems: every product/tool/service/platform name visible (e.g. GitLab, Grafana, Azure, PostgreSQL); tickets: issue keys like ABC-123; urls; numbers: business figures with their label; terms: technical words useful for a glossary.\n' "- entities.systems: every product/tool/service/platform name visible (e.g. GitLab, Grafana, Azure, PostgreSQL); tickets: issue keys like ABC-123; urls; numbers: business figures with their label; terms: technical words useful for a glossary.\n"
'- people: full names (first and last) on video tiles/name tags, never initials. presenter: name in a "Contenuto condiviso da"/"Content shared by" label. meeting_title: the Teams meeting name (Teams window title bar or meeting header, never the title of the shared content); null if not visible.\n' '- people: full names (first and last) on video tiles/name tags, never initials. presenter: name in a "Contenuto condiviso da"/"Content shared by" label. meeting_title: the Teams meeting name (Teams window title bar or meeting header, never the title of the shared content); null if not visible.\n'
'- 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' "- 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.') "Never invent: use null or [] when absent."
)
# Jira-style issue key, e.g. ABC-123 (2-10 char project prefix). # 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") TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
@@ -46,13 +130,31 @@ EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
# Send one keyframe to the VLM. json_mode=False drops response_format for servers that reject it. # Send one keyframe to the VLM. json_mode=False drops response_format for servers that reject it.
def _ask(path, json_mode=True): def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode() image_b64 = 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" 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}, "chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT}, "messages": [
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]} {
"role": "user",
"content": [
{"type": "text", "text": PROMPT},
{
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64," + image_b64},
},
],
}
],
}
# Constrain output with the schema; plain json_object when no schema is set. # 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"} 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}") return llama.content(llama.post(body, True, 900), f"shot {path.name}")
@@ -62,170 +164,321 @@ def read_shot(path):
# Retry once: VLM replies are sometimes malformed. # Retry once: VLM replies are sometimes malformed.
for _ in range(2): for _ in range(2):
try: try:
try: t = _ask(path, json_mode) try:
except urllib.error.HTTPError as e: text = _ask(path, json_mode)
if e.code != 400 or not json_mode: raise except urllib.error.HTTPError as err:
json_mode = False; t = _ask(path, False) if err.code != 400 or not json_mode:
raise
json_mode = False
text = _ask(path, False)
# Drop reasoning blocks some models emit before the JSON. # Drop reasoning blocks some models emit before the JSON.
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S) text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
# Keep only the outermost {...} in case of surrounding text. # Keep only the outermost {...} in case of surrounding text.
d = json.loads(t[t.find("{"):t.rfind("}") + 1]) parsed = json.loads(text[text.find("{") : text.rfind("}") + 1])
if isinstance(d, dict): return {**EMPTY, **d} if isinstance(parsed, dict):
except (ValueError, KeyError, IndexError): pass # IndexError: cloud returned empty "choices" (content filter / transient) return {**EMPTY, **parsed}
except (ValueError, KeyError, IndexError):
pass # IndexError: cloud returned empty "choices" (content filter / transient)
return dict(EMPTY) return dict(EMPTY)
# Deduplicate case-insensitively, keep order, drop empties. # Deduplicate case-insensitively, keep order, drop empties.
def _dedupe(xs): def _dedupe(items):
seen, out = set(), [] seen, unique = set(), []
for x in xs: for item in items:
x = str(x).strip() item = str(item).strip()
if x and x.lower() not in seen: seen.add(x.lower()); out.append(x) if item and item.lower() not in seen:
return out seen.add(item.lower())
unique.append(item)
return unique
# Merge regex-found tickets/URLs/e-mails into the model's entities; edits d in place. # Merge regex-found tickets/URLs/e-mails into the model's entities; edits d in place.
def _augment(d): def _augment(shot):
ent = d.get("entities") if isinstance(d.get("entities"), dict) else {} entities = shot.get("entities") if isinstance(shot.get("entities"), dict) else {}
blob = f"{d.get('text') or ''} {d.get('summary') or ''}" blob = f"{shot.get('text') or ''} {shot.get('summary') or ''}"
for k in ("systems", "tickets", "urls", "numbers", "terms"): ent[k] = list(ent.get(k) or []) for key in ("systems", "tickets", "urls", "numbers", "terms"):
ent["tickets"] += TICKET.findall(blob) entities[key] = list(entities.get(key) or [])
ent["urls"] += URL.findall(blob) entities["tickets"] += TICKET.findall(blob)
ent["emails"] = EMAIL.findall(blob) entities["urls"] += URL.findall(blob)
d["entities"] = {k: _dedupe(v) for k, v in ent.items()} entities["emails"] = EMAIL.findall(blob)
d["people"] = _dedupe(d.get("people") or []) shot["entities"] = {key: _dedupe(values) for key, values in entities.items()}
shot["people"] = _dedupe(shot.get("people") or [])
def _bars(video, dur): def _bars(video, duration):
"""ffmpeg crop filter trimming black side bars, or None. dur: seconds (webm has no container duration).""" """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. # 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)], width = int(
capture_output=True, text=True).stdout.strip() or 0) 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. # 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", "-"], result = subprocess.run(
capture_output=True, text=True) [
m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr) "ffmpeg",
"-ss",
str(duration / 2),
"-i",
str(video),
"-vf",
"cropdetect=24:16:0",
"-frames:v",
"60",
"-f",
"null",
"-",
],
capture_output=True,
text=True,
)
crop_matches = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", result.stderr)
# Reject if the detected width is under half the frame (not a side-bar case). # 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 if not crop_matches or not width or int(crop_matches[-1][0]) < 0.5 * width:
return "crop=" + ":".join(m[-1]) return None
return "crop=" + ":".join(crop_matches[-1])
def _view(path, box): def _view(path, content_box):
"""Crop the shared content out of a keyframe; returns the file name to display.""" """Crop the shared content out of a keyframe; returns the file name to display."""
from PIL import Image from PIL import Image
# Fall back to the full frame when no usable box was returned. # 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 if (
im = Image.open(path); W, H = im.size not CROP_BOX
or not isinstance(content_box, list)
or len(content_box) != 4
or not all(isinstance(value, (int, float)) for value in content_box)
):
return path.name
image = Image.open(path)
width, height = image.size
# Model boxes are 0-1000 normalised; any value >1000 means pixel coordinates. # 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) scale_x, scale_y = (1, 1) if max(content_box) > 1000 else (width / 1000, height / 1000)
x1, x2 = sorted((box[0] * sx, box[2] * sx)); y1, y2 = sorted((box[1] * sy, box[3] * sy)) left, right = sorted((content_box[0] * scale_x, content_box[2] * scale_x))
top, bottom = sorted((content_box[1] * scale_y, content_box[3] * scale_y))
# 1% padding so text at the edge is not cut. # 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) left, right = max(0, left - width * 0.01), min(width, right + width * 0.01)
top, bottom = max(0, top - height * 0.01), min(height, bottom + height * 0.01)
# Ignore crops under 25% of the frame in either direction. # Ignore crops under 25% of the frame in either direction.
if x2 - x1 < .25 * W or y2 - y1 < .25 * H: return path.name if right - left < 0.25 * width or bottom - top < 0.25 * height:
out = path.with_name(f"view_{path.stem}.jpg") return path.name
im.crop((int(x1), int(y1), int(x2), int(y2))).convert("RGB").save(out, quality=90) crop_path = path.with_name(f"view_{path.stem}.jpg")
return out.name image.crop((int(left), int(top), int(right), int(bottom))).convert("RGB").save(
crop_path, quality=90
)
return crop_path.name
def _times(video, scene, bars=None): 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. # 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", result = subprocess.run(
(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) "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. # Timestamps (seconds) parsed from showinfo output.
return [float(m) for m in re.findall(r"pts_time:([\d.]+)", r.stderr)] return [float(match) for match in re.findall(r"pts_time:([\d.]+)", result.stderr)]
# Extract scene-change keyframes, dedupe, read each with the VLM, write shots.json and glossary, derive share/presence events. # 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): def run(name, max_frames=60, scene=0.05):
import imagehash import imagehash
from PIL import Image from PIL import Image
d = db.out_dir(name)
out_dir = db.out_dir(name)
# media() returns (audio, video); index 1 is the video. # media() returns (audio, video); index 1 is the video.
video = db.media(name)[1] video = db.media(name)[1]
# No video: write empty outputs and stop. # No video: write empty outputs and stop.
if video is None: if video is None:
db.replace_shots(name, []) db.replace_shots(name, [])
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]") (out_dir / "shots.json").write_text("[]")
(out_dir / "glossary.json").write_text("[]")
return return
sd = d / "shots" shots_dir = out_dir / "shots"
sd.mkdir(exist_ok=True) shots_dir.mkdir(exist_ok=True)
# Clear frames from a previous run. # Clear frames from a previous run.
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink() for frame_path in [*shots_dir.glob("shot_*.jpg"), *shots_dir.glob("view_*.jpg")]:
frame_path.unlink()
db.tick(name, 0, 0, "estrazione dei fotogrammi dal video") db.tick(name, 0, 0, "estrazione dei fotogrammi dal video")
kept = [] # (t, path, hash) kept = [] # (t, path, hash)
# Duration from DB, used for the black-bar detection. # 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) bars = _bars(
for t in _times(video, scene, bars): video,
p = sd / f"shot_{int(t)//60:02d}m{int(t)%60:02d}s.jpg" (
if any(k[1] == p for k in kept): continue # same second as a kept frame db.connect()
subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(t), "-i", str(video), "-frames:v", "1", .execute("SELECT duration_s FROM recordings WHERE name=?", (name,))
*(["-vf", bars] if bars else []), "-q:v", "3", str(p)], check=True) .fetchone()
if not p.exists(): continue or [0]
h = imagehash.phash(Image.open(p)) )[0]
or 0,
)
for timestamp in _times(video, scene, bars):
frame_path = shots_dir / f"shot_{int(timestamp) // 60:02d}m{int(timestamp) % 60:02d}s.jpg"
if any(kept_frame[1] == frame_path for kept_frame in kept):
continue # same second as a kept frame
subprocess.run(
[
"ffmpeg",
"-y",
"-v",
"error",
"-ss",
str(timestamp),
"-i",
str(video),
"-frames:v",
"1",
*(["-vf", bars] if bars else []),
"-q:v",
"3",
str(frame_path),
],
check=True,
)
if not frame_path.exists():
continue
phash = imagehash.phash(Image.open(frame_path))
# pHash distance <=8 = near-duplicate of the last kept frame: drop it. # pHash distance <=8 = near-duplicate of the last kept frame: drop it.
if kept and h - kept[-1][2] <= 8: p.unlink(); continue if kept and phash - kept[-1][2] <= 8:
kept.append((t, p, h)) frame_path.unlink()
continue
kept.append((timestamp, frame_path, phash))
# Too many frames: keep evenly spaced ones up to max_frames. # Too many frames: keep evenly spaced ones up to max_frames.
if len(kept) > max_frames: if len(kept) > max_frames:
keep = sorted({round(i * (len(kept) - 1) / (max_frames - 1)) for i in range(max_frames)}) keep = sorted(
for i, k in enumerate(kept): {round(index * (len(kept) - 1) / (max_frames - 1)) for index in range(max_frames)}
if i not in keep: k[1].unlink() )
kept = [kept[i] for i in keep] for index, kept_frame in enumerate(kept):
if index not in keep:
kept_frame[1].unlink()
kept = [kept[index] for index in keep]
db.tick(name, 0, len(kept), "avvio del modello di visione") 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 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 server = llama.start(log=db.logs(name) / "llama.log") # None if already running
rows = [] rows = []
try: try:
for i, (t, p, _) in enumerate(kept): for index, (timestamp, frame_path, _) in enumerate(kept):
db.tick(name, i, len(kept), f"schermata {i + 1} di {len(kept)} ({int(t) // 60:02d}:{int(t) % 60:02d})") db.tick(
r = read_shot(p); _augment(r) name,
r["view"] = _view(p, r.pop("content_box", None)) index,
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True) len(kept),
f"schermata {index + 1} di {len(kept)} ({int(timestamp) // 60:02d}:{int(timestamp) % 60:02d})",
)
row = read_shot(frame_path)
_augment(row)
row["view"] = _view(frame_path, row.pop("content_box", None))
rows.append({"t": timestamp, "file": frame_path.name, **row})
print(f"{timestamp:6.1f}s {row['kind']} {(row['title'] or '')[:60]}", flush=True)
finally: finally:
# Stop only the server this function started. # Stop only the server this function started.
if srv: srv.terminate() if server:
server.terminate()
# Duration from DB; fall back to last frame time + 60 s. # 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] duration = (
if dur is None: dur = rows[-1]["t"] + 60 if rows else 0 db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
or [None]
)[0]
if duration is None:
duration = rows[-1]["t"] + 60 if rows else 0
prev = None prev = None
# lead=False when a row repeats the previous kind+title (continuation of the same topic). # lead=False when a row repeats the previous kind+title (continuation of the same topic).
for i, r in enumerate(rows): for index, row in enumerate(rows):
r["t_end"] = rows[i + 1]["t"] if i + 1 < len(rows) else dur row["t_end"] = rows[index + 1]["t"] if index + 1 < len(rows) else duration
key = (r["kind"], (r["title"] or "").lower()) if r["title"] else None key = (row["kind"], (row["title"] or "").lower()) if row["title"] else None
r["lead"] = not (key and key == prev) row["lead"] = not (key and key == prev)
prev = key prev = key
# Persist to file and DB. # Persist to file and DB.
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8") (out_dir / "shots.json").write_text(
json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8"
)
db.replace_shots(name, rows) db.replace_shots(name, rows)
# Glossary: terms appearing in the most frames (3-40 chars), top 150. # Glossary: terms appearing in the most frames (3-40 chars), top 150.
cnt = collections.Counter() term_counts = collections.Counter()
for r in rows: for row in rows:
e = r["entities"] entities = row["entities"]
for x in set(x for k in ("systems", "terms", "tickets") for x in e.get(k, []) if 3 <= len(x) <= 40): cnt[x] += 1 for item in {
(d / "glossary.json").write_text(json.dumps([w for w, _ in cnt.most_common(150)], ensure_ascii=False), encoding="utf-8") item
for category in ("systems", "terms", "tickets")
for item in entities.get(category, [])
if 3 <= len(item) <= 40
}:
term_counts[item] += 1
(out_dir / "glossary.json").write_text(
json.dumps([term for term, _ in term_counts.most_common(150)], ensure_ascii=False),
encoding="utf-8",
)
c = db.connect() connection = db.connect()
# Derive events only if the call has no roster presence events yet (avoid duplicates). # 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: if (
connection.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. # Replace any video-derived events from an earlier run.
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,)) connection.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
ev = [] events = []
# People shown on video tiles -> 'present' events. Names with a space and >4 chars only (skips initials). # People shown on video tiles -> 'present' events. Names with a space and >4 chars only (skips initials).
for r in rows: for row in rows:
ppl = [n for n in (db.norm_name(x) for x in r["people"]) if " " in n and len(n) > 4] present_names = [
if ppl: ev.append((r["t"], "present", "video", "", json.dumps([{"key": "video", "who": n} for n in ppl], ensure_ascii=False))) person
for person in (db.norm_name(item) for item in row["people"])
if " " in person and len(person) > 4
]
if present_names:
events.append(
(
row["t"],
"present",
"video",
"",
json.dumps(
[{"key": "video", "who": person} for person in present_names],
ensure_ascii=False,
),
)
)
last = None last = None
# Presenter changes -> share_start / share_stop pairs. # Presenter changes -> share_start / share_stop pairs.
for r in rows: for row in rows:
pr = db.norm_name(r["presenter"]) if r["presenter"] else None presenter_key = db.norm_name(row["presenter"]) if row["presenter"] else None
if pr != last: if presenter_key != last:
if last: ev.append((r["t"], "share_stop", "video", last, "")) if last:
if pr: ev.append((r["t"], "share_start", "video", pr, "")) events.append((row["t"], "share_stop", "video", last, ""))
last = pr if presenter_key:
if last: ev.append((dur, "share_stop", "video", last, "")) events.append((row["t"], "share_start", "video", presenter_key, ""))
db.add_events(name, ev) last = presenter_key
if last:
events.append((duration, "share_stop", "video", last, ""))
db.add_events(name, events)
+42 -23
View File
@@ -1,36 +1,55 @@
"""Map diarization labels to names seen in Teams call events.""" """Map diarization labels to names seen in Teams call events."""
import json import json
import db import db
# Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name. # Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name.
def run(name): def run(name):
p = db.out_dir(name) / "diar_segments.json" diar_path = db.out_dir(name) / "diar_segments.json"
ev = db.events(name, "active", "caption") events = db.events(name, "active", "caption")
if not p.exists() or not ev: return if not diar_path.exists() or not events:
segs = json.loads(p.read_text(encoding="utf-8")) return
iv = [] segments = json.loads(diar_path.read_text(encoding="utf-8"))
intervals = []
# Intervals where a person was speaking or captioned: 'active' is a 0.5 s point, 'caption' is +/-2 s around its timestamp. # 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: for event in events:
if not e["who"]: continue if not event["who"]:
a, b = (e["t"], e["t"] + 0.5) if e["kind"] == "active" else (e["t"] - 2, e["t"] + 2) continue
iv.append((a, b, e["who"])) start, end = (
(event["t"], event["t"] + 0.5)
if event["kind"] == "active"
else (event["t"] - 2, event["t"] + 2)
)
intervals.append((start, end, event["who"]))
# Total overlap seconds per (label, person). # Total overlap seconds per (label, person).
tot = {} totals = {}
for s in segs: for segment in segments:
d = tot.setdefault(s["label"], {}) label_totals = totals.setdefault(segment["label"], {})
for a, b, who in iv: for start, end, who in intervals:
o = min(b, s["end"]) - max(a, s["start"]) overlap = min(end, segment["end"]) - max(start, segment["start"])
if o > 0: d[who] = d.get(who, 0) + o if overlap > 0:
label_totals[who] = label_totals.get(who, 0) + overlap
# greedy one-to-one: strongest (label, person) overlap first, a person is never given to two labels # greedy one-to-one: strongest (label, person) overlap first, a person is never given to two labels
pairs = sorted(((ov, label, who) for label, d in tot.items() for who, ov in d.items()), reverse=True) pairs = sorted(
got, used = {}, set() (
for ov, label, who in pairs: (overlap, label, who)
if label in got or who in used: continue for label, label_totals in totals.items()
for who, overlap in label_totals.items()
),
reverse=True,
)
assigned, used_people = {}, set()
for overlap, label, who in pairs:
if label in assigned or who in used_people:
continue
# Accept only if overlap >= 5 s and >= 40 % of the label's total. # 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) if overlap >= 5 and overlap / sum(totals[label].values()) >= 0.4:
assigned[label] = (who, overlap)
used_people.add(who)
# Every label gets a row, even unmatched ones (who=''). # Every label gets a row, even unmatched ones (who='').
for label in {s["label"] for s in segs}: for label in {segment["label"] for segment in segments}:
who, ov = got.get(label, ("", sum(tot.get(label, {}).values()))) who, overlap = assigned.get(label, ("", sum(totals.get(label, {}).values())))
# Store the mapping (source 'auto', with overlap seconds). # Store the mapping (source 'auto', with overlap seconds).
db.set_speaker_map(name, label, who, "auto", ov) db.set_speaker_map(name, label, who, "auto", overlap)
+125 -54
View File
@@ -1,8 +1,13 @@
"""Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu).""" """Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu)."""
import gc, json, subprocess, time
import gc
import json
import subprocess
import time
from pathlib import Path from pathlib import Path
import numpy as np
import db import db
import numpy as np
HERE = Path(__file__).parent HERE = Path(__file__).parent
# Pre-converted OpenVINO Whisper model; downloaded on first NPU use. # Pre-converted OpenVINO Whisper model; downloaded on first NPU use.
@@ -10,110 +15,176 @@ NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
# Log via Prefect when inside a flow; print otherwise. # Log via Prefect when inside a flow; print otherwise.
def _log(msg): def _log(message):
try: try:
from prefect import get_run_logger from prefect import get_run_logger
get_run_logger().info(msg)
get_run_logger().info(message)
except Exception: except Exception:
print(msg, flush=True) print(message, flush=True)
def aggregate(segs): def aggregate(segs):
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run. A segment repeated 3+ times in a row is a whisper loop (46x "Ciao."): keep 2.""" """(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run. A segment repeated 3+ times in a row is a whisper loop (46x "Ciao."): keep 2."""
lines, buf, start, end, last, rep = [], [], 0, 0, None, 0 lines, pending, start, end, previous_text, repeat_count = [], [], 0, 0, None, 0
def flush(): def flush():
if buf: if pending:
lines.append((int(start), " ".join(buf))); buf.clear() lines.append((int(start), " ".join(pending)))
for s, e, t in segs: pending.clear()
t = t.strip()
if not t: continue for seg_start, seg_end, raw_text in segs:
text = raw_text.strip()
if not text:
continue
# Count consecutive identical segments; the 3rd+ repeat is a whisper loop and is skipped. # Count consecutive identical segments; the 3rd+ repeat is a whisper loop and is skipped.
rep = rep + 1 if t == last else 0; last = t repeat_count = repeat_count + 1 if text == previous_text else 0
if rep >= 2: continue previous_text = text
if repeat_count >= 2:
continue
# A pause over 1 s starts a new line. # A pause over 1 s starts a new line.
if buf and s - end > 1: flush() if pending and seg_start - end > 1:
if not buf: start = s flush()
buf.append(t); end = e if not pending:
start = seg_start
pending.append(text)
end = seg_end
# End the line at sentence punctuation, or after 12 s. # End the line at sentence punctuation, or after 12 s.
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush() if text.endswith((".", "?", "!", "…")) or end - start > 12:
flush()
flush() flush()
return lines return lines
# Decode to 16 kHz mono float32 PCM via ffmpeg; the format whisper and the NPU pipeline expect. # Decode to 16 kHz mono float32 PCM via ffmpeg; the format whisper and the NPU pipeline expect.
def _decode(path): def _decode(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"], pcm_bytes = subprocess.run(
capture_output=True, check=True).stdout [
return np.frombuffer(raw, np.float32) "ffmpeg",
"-v",
"error",
"-i",
str(path),
"-vn",
"-ac",
"1",
"-ar",
"16000",
"-f",
"f32le",
"-",
],
capture_output=True,
check=True,
).stdout
return np.frombuffer(pcm_bytes, np.float32)
# Faster-whisper on CUDA (CPU fallback in common.load_model); returns (segments, device). tick(done, total) reports progress. # 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): def _cuda(audio, model, glossary, tick=lambda done, total: None):
import common import common
# Load the model; dev is 'cuda' or 'cpu'.
m, dev = common.load_model(model) # Load the model; used_device is 'cuda' or 'cpu'.
whisper_model, used_device = common.load_model(model)
# ponytail: >~20 hotwords crowd whisper's prompt -> dropped text + repetition loops (seen with 60) # 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 {} kwargs = (
{"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False}
if glossary
else {}
)
try: try:
# Italian forced; VAD (voice activity detection) skips silence. # Italian forced; VAD (voice activity detection) skips silence.
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw) segments, info = whisper_model.transcribe(
out = [] str(audio), language="it", vad_filter=True, **kwargs
)
collected = []
# Keep each segment, reporting progress by its end time. # 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) for segment in segments:
return out, dev collected.append((segment.start, segment.end, segment.text))
tick(segment.end, info.duration)
return collected, used_device
finally: finally:
# Free the model (VRAM) before returning, even on error. # Free the model (VRAM) before returning, even on error.
del m; gc.collect() del whisper_model
gc.collect()
# OpenVINO GenAI Whisper on the Intel NPU. Failure raises 'NPU failed' so flow.py can fall back to CUDA. # OpenVINO GenAI Whisper on the Intel NPU. Failure raises 'NPU failed' so flow.py can fall back to CUDA.
def _npu(audio): def _npu(audio):
try: try:
import openvino_genai as ov import openvino_genai
# First run: download the pre-converted model; if that fails, export it locally with optimum (slow). # First run: download the pre-converted model; if that fails, export it locally with optimum (slow).
if not NPU_MODEL_DIR.exists(): if not NPU_MODEL_DIR.exists():
from huggingface_hub import snapshot_download from huggingface_hub import snapshot_download
try: try:
snapshot_download("OpenVINO/whisper-large-v3-turbo-fp16-ov", local_dir=NPU_MODEL_DIR) snapshot_download(
"OpenVINO/whisper-large-v3-turbo-fp16-ov", local_dir=NPU_MODEL_DIR
)
except Exception: except Exception:
subprocess.run(["optimum-cli", "export", "openvino", "--model", "openai/whisper-large-v3-turbo", subprocess.run(
"--weight-format", "fp16", str(NPU_MODEL_DIR)], check=True) [
"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. # Load the pipeline on the NPU device.
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU") pipe = openvino_genai.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True) result = pipe.generate(
_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True
)
# Empty output counts as failure. # Empty output counts as failure.
if not res.chunks: raise RuntimeError("no chunks returned") if not result.chunks:
return [(c.start_ts, c.end_ts, c.text) for c in res.chunks] raise RuntimeError("no chunks returned")
except Exception as e: return [(chunk.start_ts, chunk.end_ts, chunk.text) for chunk in result.chunks]
raise RuntimeError(f"NPU failed: {e!r}") except Exception as error:
raise RuntimeError(f"NPU failed: {error!r}") from error
# Transcribe one meeting into transcript.txt and DB lines. out_path is used by --bench-npu to write a side file only. # 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): def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path | None = None):
audio = db.out_dir(name) / "audio.opus" audio = db.out_dir(name) / "audio.opus"
gl = db.out_dir(name) / "glossary.json" glossary_path = db.out_dir(name) / "glossary.json"
# Glossary from shots (used as whisper hotwords). # Glossary from shots (used as whisper hotwords).
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else [] glossary = (
t0 = time.time() json.loads(glossary_path.read_text(encoding="utf-8")) if glossary_path.exists() else []
)
start_time = time.time()
# NPU reports no progress; CUDA reports per segment. # NPU reports no progress; CUDA reports per segment.
if device == "npu": if device == "npu":
db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)") db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)")
segs, used = _npu(audio), "npu" segments, used_device = _npu(audio), "npu"
else: 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) def tick(done, total):
return db.tick(
name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio"
)
segments, used_device = _cuda(audio, model, glossary, tick)
# Group segments into timestamped lines. # Group segments into timestamped lines.
lines = aggregate(segs) lines = aggregate(segments)
# Format as [mm:ss] text, the format diarize.py parses. # 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) transcript_text = "\n".join(
for l in txt.splitlines(): _log(l) f"[{time_s // 60:02d}:{time_s % 60:02d}] {text}" for time_s, text in lines
secs = time.time() - t0 )
for line in transcript_text.splitlines():
_log(line)
elapsed_s = time.time() - start_time
# Benchmark mode: write to the given file only; leave the DB alone. # Benchmark mode: write to the given file only; leave the DB alone.
if out_path is not None: if out_path is not None:
out_path.write_text(txt, encoding="utf-8") out_path.write_text(transcript_text, encoding="utf-8")
return secs return elapsed_s
# Normal mode: persist transcript file and DB rows, and record which device was used. # 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.out_dir(name) / "transcript.txt").write_text(transcript_text, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines]) db.replace_lines(name, [(time_s, None, text) for time_s, text in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs) db.upsert_recording(name, transcribe_device=used_device, transcribe_s=elapsed_s)
return secs return elapsed_s
+102 -102
View File
@@ -1,112 +1,112 @@
// 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. // 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 (&, <, >, "). // Escape text for innerHTML (&, <, >, ").
const E=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c])); const E=value=>String(value??"").replace(/[&<>"]/g,char=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[char]));
// Seconds -> mm:ss (minutes can exceed 59; no hour form here). // 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")}; const fmt=seconds=>{seconds=Math.round(seconds);return String(Math.floor(seconds/60)).padStart(2,"0")+":"+String(seconds%60).padStart(2,"0")};
// Enter in the search box runs the search. // Enter in the search box runs the search.
q.onkeydown=e=>{if(e.key=="Enter")srch()}; q.onkeydown=event=>{if(event.key==="Enter")srch()};
// Enter in the Q&A box asks the question. // Enter in the Q&A box asks the question.
qa.onkeydown=e=>{if(e.key=="Enter")ask()}; qa.onkeydown=event=>{if(event.key==="Enter")ask()};
// Close button appended after results: clears the input and the result box. // Close button appended after results: clears the input and the result box.
const CLOSE=(i,o)=>`<div><button onclick="${i}.value='';${o}.innerHTML=''">✕ chiudi</button></div>`; const CLOSE=(target,output)=>`<div><button onclick="${target}.value='';${output}.innerHTML=''">✕ chiudi</button></div>`;
// Q&A: /ask_stream sends NDJSON events ({sources} first, then {t} text pieces); the answer is redrawn as it grows. The model may take minutes to load on first use. // Q&A: /ask_stream sends NDJSON events ({sources} first, then {t} text pieces); the answer is redrawn as it grows. 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>"; async function ask(){if(!qa.value)return;ar.innerHTML="<small>…avvio modelli / risposta (può richiedere qualche minuto)</small>";
const r=await fetch("/ask_stream?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return} const response=await fetch("/ask_stream?q="+encodeURIComponent(qa.value));if(!response.ok){ar.textContent=await response.text();return}
let src=[],txt="",buf="",fin=false; let src=[],txt="",buf="",fin=false;
// Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing. Sources list and close button appear when the stream ends. // Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing. Sources list and close button appear when the stream ends.
// Minimal markdown -> HTML (on escaped text): headings, bullet/numbered lists, **bold**, *italic*, `code`; blank-line separated paragraphs. // Minimal markdown -> HTML (on escaped text): headings, bullet/numbered lists, **bold**, *italic*, `code`; blank-line separated paragraphs.
const MD=t=>{let h="",ul=false;const il=s=>s.replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*(.+?)\*\*/g,"<b>$1</b>").replace(/(^|\W)\*([^*\s][^*]*?)\*/g,"$1<i>$2</i>"); const MD=text=>{let html="",ul=false;const inlineMd=str=>str.replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*(.+?)\*\*/g,"<b>$1</b>").replace(/(^|\W)\*([^*\s][^*]*?)\*/g,"$1<i>$2</i>");
for(const l of E(t).split("\n")){const m=l.match(/^\s*(?:[-*]|\d+\.) (.*)/);if(m){if(!ul){h+="<ul>";ul=true}h+="<li>"+il(m[1])+"</li>";continue} for(const line of E(text).split("\n")){const item=line.match(/^\s*(?:[-*]|\d+\.) (.*)/);if(item){if(!ul){html+="<ul>";ul=true}html+="<li>"+inlineMd(item[1])+"</li>";continue}
if(ul){h+="</ul>";ul=false}const g=l.match(/^#{1,6} (.*)/);if(g)h+="<h4>"+il(g[1])+"</h4>";else if(l.trim())h+="<p>"+il(l)+"</p>"} if(ul){html+="</ul>";ul=false}const heading=line.match(/^#{1,6} (.*)/);if(heading)html+="<h4>"+inlineMd(heading[1])+"</h4>";else if(line.trim())html+="<p>"+inlineMd(line)+"</p>"}
return h+(ul?"</ul>":"")}; return html+(ul?"</ul>":"")};
const lk=n=>{const s=src[n-1];return s?`<a href="/report?name=${encodeURIComponent(s.name)}#${encodeURIComponent(s.anchor)}" target=_blank title="${E(s.meeting)} — ${E(s.topic)}">${n}</a>`:n}; const lk=num=>{const source=src[num-1];return source?`<a href="/report?name=${encodeURIComponent(source.name)}#${encodeURIComponent(source.anchor)}" target=_blank title="${E(source.meeting)} — ${E(source.topic)}">${num}</a>`:num};
// [n], [1][2] and [1, 2] all become links; each number opens report.html at that source's section. // [n], [1][2] and [1, 2] all become links; each number opens report.html at that source's section.
const draw=()=>{ar.innerHTML=`<div class=md>`+MD(txt).replace(/\[(\d+(?:\s*[,;]\s*\d+)*)\]/g,(m,l)=>"["+l.replace(/\d+/g,lk)+"]")+"</div>"+ const draw=()=>{ar.innerHTML=`<div class=md>`+MD(txt).replace(/\[(\d+(?:\s*[,;]\s*\d+)*)\]/g,(match,group)=>"["+group.replace(/\d+/g,lk)+"]")+"</div>"+
(fin?(src.length?`<details><summary><small>Fonti (${src.length})</small></summary>`+src.map(s=>`<div><small>[${lk(s.n)}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} <a href="#" title="riproduci il video da qui" onclick="play('${s.name}',0,'${E(s.meeting+" "+s.date).replace(/'/g,"")}',${+s.t||0});return false">▶ ${fmt(s.t)}</a> (${s.kind}): ${E(s.text)}</small></div>`).join("")+"</details>":"")+CLOSE("qa","ar"):"")}; (fin?(src.length?`<details><summary><small>Fonti (${src.length})</small></summary>`+src.map(source=>`<div><small>[${lk(source.n)}] ${E(source.date)} ${E(source.meeting)} — ${E(source.topic)} <a href="#" title="riproduci il video da qui" onclick="play('${source.name}',0,'${E(source.meeting+" "+source.date).replace(/'/g,"")}',${+source.t||0});return false">▶ ${fmt(source.t)}</a> (${source.kind}): ${E(source.text)}</small></div>`).join("")+"</details>":"")+CLOSE("qa","ar"):"")};
const rd=r.body.getReader(),dc=new TextDecoder(); const rd=response.body.getReader(),dc=new TextDecoder();
for(;;){const {value,done}=await rd.read();if(done)break;buf+=dc.decode(value,{stream:true});const ls=buf.split("\n");buf=ls.pop(); for(;;){const {value,done}=await rd.read();if(done)break;buf+=dc.decode(value,{stream:true});const ls=buf.split("\n");buf=ls.pop();
for(const l of ls){const e=JSON.parse(l);if(e.sources)src=e.sources;else if(e.err)txt+="\n[errore: "+e.err+"]";else txt+=e.t}draw()} for(const line of ls){const event=JSON.parse(line);if(event.sources)src=event.sources;else if(event.err)txt+="\n[errore: "+event.err+"]";else txt+=event.t}draw()}
fin=true;draw()} fin=true;draw()}
// Search over speech and screen text (/search). // 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(); async function srch(){if(!q.value){sr.innerHTML="";return}const results=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. // 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("")+CLOSE("q","sr")} sr.innerHTML=results.speech.map(hit=>`<div>${E(hit[0])} ${fmt(hit[1])} ${E(hit[2]||"")}: ${E(hit[3])}</div>`).join("")+results.screen.map(hit=>`<div>🖥 <a href="/shot?name=${hit[0]}&file=shots/${hit[4]}" target=_blank>${E(hit[0])} ${fmt(hit[1])}</a> ${E(hit[2]||"")}: ${E(hit[3])}</div>`).join("")+CLOSE("q","sr")}
// Start a pipeline run from the chosen step (/run); 409 means it is already running. // 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()} async function run(name){const step=document.getElementById("f-"+name).value;const response=await fetch(`/run?name=${name}&from=${step}`,{method:"POST"});if(response.status===409)alert("già in esecuzione");tick()}
// Names of the checked recording rows (.mg checkboxes). // Names of the checked recording rows (.mg checkboxes).
const sel_=()=>[...document.querySelectorAll(".mg:checked")].map(x=>x.value); const sel_=()=>[...document.querySelectorAll(".mg:checked")].map(x=>x.value);
// Show the bulk bar only when something is checked, and show the selected count. // 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"}`} function upd(){const count=sel_().length;bulk.hidden=!count;bn.textContent=`${count} selezionat${count===1?"a":"e"}`}
// Check or uncheck all recording rows. // Check or uncheck all recording rows.
function selAll(v){document.querySelectorAll(".mg").forEach(x=>x.checked=!!v);upd()} function selAll(on){document.querySelectorAll(".mg").forEach(box=>box.checked=!!on);upd()}
// Run one POST per selected recording and collect failures into a single alert. // 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()}`)} async function bulk_(path,names,label){let bad=[];for(const name of names){const response=await fetch(`${path}${path.includes("?")?"&":"?"}name=${name}`,{method:"POST"});if(!response.ok)bad.push(`${name}: ${await response.text()}`)}
if(bad.length)alert(`${label}: ${names.length-bad.length}/${names.length} ok\n`+bad.join("\n"));tick()} 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. // Re-run the selected recordings from the step chosen in #bf.
function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")} function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")}
// Bulk delete of video files only; report, transcript and screenshots are kept. // 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? function bulkDrop(){const names=sel_();if(confirm(`Eliminare i file video di ${names.length} riunioni?
Report, trascrizione, audio e schermate restano, ma non potranno più essere rielaborate. Non si può annullare.`))bulk_("/drop_video",n,"elimina video")} Report, trascrizione, audio e schermate restano, ma non potranno più essere rielaborate. Non si può annullare.`))bulk_("/drop_video",names,"elimina video")}
// Bulk delete of whole recordings; asks for confirmation first. // Bulk delete of whole recordings; asks for confirmation first.
function bulkDel(){const n=sel_();if(confirm(`Eliminare definitivamente ${n.length} riunioni? function bulkDel(){const names=sel_();if(confirm(`Eliminare definitivamente ${names.length} riunioni?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))bulk_("/delete",n,"elimina")} Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))bulk_("/delete",names,"elimina")}
// Merge two or more checked recordings (same meeting restarted) into one. // 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()} async function mergeSel(){const names=sel_();if(names.length<2)return alert("spunta almeno 2 registrazioni");const response=await fetch("/merge?names="+names.join(","),{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Names whose speakers panel is open; kept across re-renders. // Names whose speakers panel is open; kept across re-renders.
const open_=new Set(); const open_=new Set();
// Toggle the speakers panel for one recording and re-render. // 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()} async function spk(name){editing=false;open_.has(name)?open_.delete(name):open_.add(name);tick()}
// Speakers panel: diarization label -> person mapping, with a datalist of candidate names. // 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(); async function panel(name){const data=await (await fetch("/speakers?name="+name)).json();
return `<tr class=sp><td colspan=7><datalist id="cand-${n}">${j.candidates.map(c=>`<option value="${E(c)}">`).join("")}</datalist>`+ return `<tr class=sp><td colspan=7><datalist id="cand-${name}">${data.candidates.map(candidate=>`<option value="${E(candidate)}">`).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("")+ data.rows.map(row=>`<div><b>${E(row.label)}</b> ${fmt(row.talk_s)} <input data-n="${name}" data-l="${E(row.label)}" list="cand-${name}" value="${E(row.person)}"> ${row.source}${row.source==="auto"&&row.overlap_s!=null?" "+Math.round(row.overlap_s)+"s":""}<br><small>${row.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>`} `<div class=sa><button class=pri onclick="saveSpk('${name}')">✓ Salva nomi</button><button onclick="spk('${name}')">✕ Chiudi</button></div>`}
// Read the label -> person inputs and save them (/speaker_map). // 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); async function saveSpk(name){const labels={};document.querySelectorAll(`input[data-n="${name}"]`).forEach(input=>labels[input.dataset.l]=input.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)} const response=await fetch("/speaker_map?name="+name,{method:"POST",body:JSON.stringify(labels)});editing=false;const text=await response.text();open_.delete(name);tick();alert(text)}
// Recompute the automatic title from the report. // 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()} async function retitle(name){const response=await fetch(`/run?name=${name}&from=title`,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
const sel={}; const sel={};
// Delete one recording after confirmation. // Delete one recording after confirmation.
async function del_(n,label){if(!confirm(`Eliminare definitivamente "${label}"? async function del_(name,label){if(!confirm(`Eliminare definitivamente "${label}"?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))return; 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()} const response=await fetch("/delete?name="+name,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Delete only the video file of one recording (report and transcript stay). // 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)? async function dropVid(name,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; 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()} const response=await fetch("/drop_video?name="+name,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Prompt for a new title; empty means automatic. The date suffix is stripped from the default text. // 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; async function setTitle(name,cur){const title=prompt("Titolo della riunione (vuoto = automatico)",cur.replace(/ — \d{4}-\d\d-\d\d.*$/,""));if(title===null)return;
const r=await fetch("/title?name="+n,{method:"POST",body:t});if(!r.ok)alert(await r.text());tick()} const response=await fetch("/title?name="+name,{method:"POST",body:title});if(!response.ok)alert(await response.text());tick()}
// "mm:ss" or "h:mm:ss" -> seconds. // "mm:ss" or "h:mm:ss" -> seconds.
const sec=s=>s.trim().split(":").reduce((a,x)=>a*60+(+x),0); const sec=str=>str.trim().split(":").reduce((acc,part)=>acc*60+(+part),0);
// Open the preview dialog for recording n; the video is streamed from /video. Optional at = seconds to start playing from (used by the Q&A sources). // Open the preview dialog for recording n; the video is streamed from /video. Optional at = seconds to start playing from (used by the Q&A sources).
function play(n,d,t,at){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);if(at>0){cv.currentTime=at;cv.play().catch(()=>{})}};cdlg.showModal()} function play(name,duration,title,start){cv.src="/video?name="+name;ctitle.textContent=title;cs.value="00:00";ce.value=duration?fmt(duration):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration);if(start>0){cv.currentTime=start;cv.play().catch(()=>{})}};cdlg.showModal()}
// Stop and unload the video so the file handle is released. // Stop and unload the video so the file handle is released.
function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()} function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()}
// Esc closes the dialog through the same cleanup. // Esc closes the dialog through the same cleanup.
cdlg.addEventListener("cancel",cclose); cdlg.addEventListener("cancel",cclose);
// Play from the start time; pause at the end time when one is set. // 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}}} function cplay(){cv.currentTime=sec(cs.value);cv.play();const endTime=sec(ce.value);cv.ontimeupdate=()=>{if(endTime>0&&cv.currentTime>=endTime){cv.pause();cv.ontimeupdate=null}}}
// Crop: inplace replaces the original (after confirm); otherwise a new meeting is created from the clip. // 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"); async function cgo(inplace){const start=sec(cs.value),end=sec(ce.value),name=new URL(cv.src).searchParams.get("name");
// Validate the interval: start >= 0 and end after start. // Validate the interval: start >= 0 and end after start.
if(!(a>=0&&b>a)){cmsg.textContent="intervallo non valido";return} if(!(start>=0&&end>start)){cmsg.textContent="intervallo non valido";return}
// Replacing the original is irreversible, so confirm first. // 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&&!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 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. // 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; 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. // 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); const iv=setInterval(async()=>{try{const percent=(await(await fetch("/crop_progress?name="+name,{method:"POST"})).json()).pct;if(percent!=null){cpr.value=percent;cmsg.textContent=`ritaglio in corso… ${Math.round(percent)}%`}}catch{/* poll failed: next tick retries */}},700);
// Blocking request: the server re-encodes the clip, which can take minutes. // 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; const response=await fetch(`/crop?name=${name}&start=${start}&end=${end}${inplace?"&inplace=1":""}`,{method:"POST"});clearInterval(iv);cgo_.disabled=cgi_.disabled=false;cpr.hidden=true;
// Show the result and refresh the table. // 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()} if(!response.ok){cmsg.textContent="errore: "+await response.text();return}cmsg.textContent=inplace?"✓ riunione ritagliata, rielaborazione avviata":"✓ creata nuova riunione, elaborazione avviata";tick()}
// Cancel a running or queued pipeline (after confirm). // 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()} async function stopRun(name){if(!confirm(`Fermare ${name}?`))return;await fetch("/cancel?name="+name,{method:"POST"});tick()}
// Save the screenshot-model and report-model choice on the server. // 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()} async function setLlm(){const response=await fetch(`/llm?shots=${llm.value}&report=${llmr.value}`,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Save the "skip screenshots" switch on the server. // Save the "skip screenshots" switch on the server.
async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()} async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()}
// Italian labels for pipeline steps. // Italian labels for pipeline steps.
@@ -114,107 +114,107 @@ const LBL={audio:"Audio",transcribing:"Trascrizione",diarizing:"Chi parla",ident
// What each step does, shown under the progress bar. // 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"}; 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". // 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"}; const dur=seconds=>{if(seconds==null||!isFinite(seconds))return"–";seconds=Math.max(0,Math.round(seconds));if(seconds<60)return seconds+" s";const minutes=Math.round(seconds/60);return minutes<60?minutes+" min":Math.floor(minutes/60)+" h "+String(minutes%60).padStart(2,"0")+" min"};
// Seconds from now -> local HH:MM. // Seconds from now -> local HH:MM.
const clock=s=>new Date(Date.now()+s*1000).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}); const clock=seconds=>new Date(Date.now()+seconds*1000).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});
// Per recording: last [timestamp, tokens decoded], used to compute tokens/s between ticks. // Per recording: last [timestamp, tokens decoded], used to compute tokens/s between ticks.
const LT={}; const LT={};
// LLM activity line: prompt reading vs token writing; idle time sets the severity colour. // 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; function live(name,prog){const l=prog.llm;let txt="",act=false;
// Model is busy: compare token counts with the previous tick. // 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; if(info&&info.is_processing){act=true;const key=name,prev=LT[key],now=Date.now(),decoded=info.n_decoded||0;
// Tokens/s from the delta since the previous tick. // 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`:""}`} if(decoded>0){const tps=prev&&decoded>prev[1]?(decoded-prev[1])/((now-prev[0])/1000):null;txt=`Il modello sta scrivendo: <b>${decoded}</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`; else txt=`Il modello sta leggendo il contesto: <b>${info.n_prompt_tokens_processed||0}</b> di ${info.n_prompt_tokens} token`;
// Store this sample for the next tick. // Store this sample for the next tick.
LT[k]=[now,d]} LT[key]=[now,decoded]}
// Severity by idle time: under 90 s ok, under 300 s warn, otherwise bad. // 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"; const idle=prog.idle,cls=act||idle<90?"":idle<300?"warn":"bad";
// Status text for the idle time. // 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`; 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>`} 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. // Progress panel for a recording: boot, queued, or running pipeline.
function progPanel(r){const p=r.prog; function progPanel(row){const prog=row.prog;
// Pipeline starting: the Python environment can take minutes on the first run. // 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>`; if(!prog&&row.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(row.boot||"in avvio…")}</span></div></div>`;
// Queued behind another run, or nothing to show. // 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>`:""; if(!prog)return row.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. // 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"); const pct=prog.pct!=null?Math.round(prog.pct*100):null,cur=prog.plan.find(stage=>stage.state==="run");
// Step chips: skipped / done with duration / running with fraction / pending with estimate. // 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(""); const chips=prog.plan.map(stage=>stage.state==="skip"?`<span class="st skip" title="non rieseguito">${LBL[stage.s]}</span>`:stage.state==="done"?`<span class="st ok">✓ ${LBL[stage.s]} · ${dur(stage.secs)}</span>`:stage.state==="run"?`<span class="st run">● ${LBL[stage.s]} · ${Math.round(stage.frac*100)}%</span>`:`<span class=st>${LBL[stage.s]} · ~${dur(stage.est)}</span>`).join("");
// Done-of-total counter and step label. // Done-of-total counter and step label.
const cnt=p.total?`${p.done} di ${p.total}`:"",step=LBL[p.step]||p.step; const cnt=prog.total?`${prog.done} di ${prog.total}`:"",step=LBL[prog.step]||prog.step;
// Panel markup: header, progress bars, step chips and live status. // Panel markup: header, progress bars, step chips and live status.
return `<tr><td colspan=7><div class=pg> 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> <div class=pgh><span><span class=big>${pct!=null?pct+"%":"…"}</span> &nbsp;<b>${step}</b> <span class=n>— ${E(prog.note||HOW[prog.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> <span class=eta>${prog.eta!=null?`fine prevista <b>~${clock(prog.eta)}</b> · mancano <b>${dur(prog.eta)}</b> · `:""}trascorso ${dur(prog.elapsed)}</span></div>
<div class="bar${pct==null?" ind":""}"><i style="width:${pct||0}%"></i></div> <div class="bar${pct==null?" ind":""}"><i style="width:${pct||0}%"></i></div>
<div class=steps>${chips}</div> <div class=steps>${chips}</div>
<div class="bar thin"><i style="width:${Math.round(p.frac*100)}%"></i></div> <div class="bar thin"><i style="width:${Math.round(prog.frac*100)}%"></i></div>
<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> <div class=sub><span>${step}: ${cnt?cnt+" · ":""}${Math.round(prog.frac*100)}%</span><span>${cur?`questo passo: ancora ~${dur(cur.left)} (in corso da ${dur(cur.secs)})`:""}</span></div>
${live(r.name,p)}</div>`} ${live(row.name,prog)}</div>`}
function pick(){up.click()} function pick(){up.click()}
// Upload with XHR so we get upload progress events. Target: POST /upload?filename=. // 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%"; function send(file){const xhr=new XMLHttpRequest(),t0=Date.now();ub.hidden=false;ubar.style.width="0%";utitle.textContent="Caricamento di "+file.name;ubig.textContent="0%";
// Update bar, percent, MB/s and ETA from upload progress. // 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); xhr.upload.onprogress=event=>{if(!event.lengthComputable)return;const fraction=event.loaded/event.total,elapsed=(Date.now()-t0)/1000,speed=event.loaded/Math.max(elapsed,.1);
ubar.style.width=(p*100).toFixed(1)+"%";ubig.textContent=Math.floor(p*100)+"%"; ubar.style.width=(fraction*100).toFixed(1)+"%";ubig.textContent=Math.floor(fraction*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)}`}; utxt.textContent=`${(event.loaded/1e6).toFixed(0)} di ${(event.total/1e6).toFixed(0)} MB · ${(speed/1e6).toFixed(1)} MB/s · mancano ${dur((event.total-event.loaded)/speed)}`};
// Upload finished on the client; the server now validates the file and starts processing. // 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…"}; xhr.upload.onload=()=>{utxt.textContent="File ricevuto: controllo del formato e avvio dell'elaborazione…"};
// Success: show the recording duration; hide the card after 6 s. // 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)} xhr.onload=()=>{if(xhr.status===200){const data=JSON.parse(xhr.responseText);ubig.textContent="✓";utxt.textContent=`Avviata l'elaborazione (${dur(data.duration_s)} di registrazione): segui l'avanzamento qui sotto`;setTimeout(()=>ub.hidden=true,6000)}
else{ubig.textContent="!";utxt.textContent="Errore: "+x.responseText}tick()}; else{ubig.textContent="!";utxt.textContent="Errore: "+xhr.responseText}tick()};
// Network error. // Network error.
x.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"}; xhr.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
// Cancel: abort the request and hide the card. // Cancel: abort the request and hide the card.
ucancel.onclick=()=>{x.abort();ub.hidden=true}; ucancel.onclick=()=>{xhr.abort();ub.hidden=true};
// File is sent as the raw request body. // File is sent as the raw request body.
x.open("POST","/upload?filename="+encodeURIComponent(f.name));x.send(f)} xhr.open("POST","/upload?filename="+encodeURIComponent(file.name));xhr.send(file)}
// File picker upload; reset the input so the same file can be picked again. // 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=""}; up.onchange=()=>{if(up.files[0])send(up.files[0]);up.value=""};
// Dragging over the page: highlight the drop zone. // Dragging over the page: highlight the drop zone.
addEventListener("dragover",e=>{e.preventDefault();document.body.classList.add("drag")}); addEventListener("dragover",event=>{event.preventDefault();document.body.classList.add("drag")});
// Leaving the window (no relatedTarget) clears the highlight. // Leaving the window (no relatedTarget) clears the highlight.
addEventListener("dragleave",e=>{if(!e.relatedTarget)document.body.classList.remove("drag")}); addEventListener("dragleave",event=>{if(!event.relatedTarget)document.body.classList.remove("drag")});
// Drop anywhere on the page: upload the first file. // 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)}); addEventListener("drop",event=>{event.preventDefault();document.body.classList.remove("drag");const file=event.dataTransfer.files[0];if(file)send(file)});
// Meetings per page and current page index (0-based); goPg changes page and re-renders. // Meetings per page and current page index (0-based); goPg changes page and re-renders.
const PS=100;let pg_=0; const PS=100;let pg_=0;
function goPg(d){pg_+=d;tick()} function goPg(delta){pg_+=delta;tick()}
// Refresh the whole UI from /status: header, LLM pickers, table. // 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":""; async function tick(){try{const data=await (await fetch("/status")).json();ab.disabled=data.ask_blocked;ab.title=data.ask_blocked?"pipeline in corso":"";
// Browser tab title shows the progress of the first running pipeline. // 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"; const runp=data.recs.map(row=>row.prog).filter(prog=>prog&&prog.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. // 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} for(const [select,index,prefix] of [[llm,0,"shots: "],[llmr,1,"report: "],[llma,1,""]])if(document.activeElement!==select){select.innerHTML=data.llms[index].map(([key,label])=>`<option value=${key}>${prefix}${E(label)}`).join("");select.value=data.llm[index];select.disabled=data.busy}
// Skip-screenshots switch; disabled while busy. // Skip-screenshots switch; disabled while busy.
skp.checked=j.skip_shots;skp.disabled=j.busy; skp.checked=data.skip_shots;skp.disabled=data.busy;
// omp login status: red and showing the error when logged out. // 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(" · "); const ompStatus=data.omp;omps.innerHTML=!ompStatus.exe?`<span style="color:var(--redf)">omp non installato</span>`:[["github-copilot","Copilot"],["anthropic","Anthropic"]].map(([key,label])=>`<span title="${E(ompStatus[key]||"login valido")}"${ompStatus[key]?' style="color:var(--redf)"':""}>${ompStatus[key]?"✗":"✓"} ${label}</span>`).join(" · ");
// Queue size in the header. // Queue size in the header.
qs.textContent=j.queue?`rielaborazione: ${j.queue} da completare`:""; qs.textContent=data.queue?`rielaborazione: ${data.queue} da completare`:"";
// Remember step-select values so they survive the re-render. // Remember step-select values so they survive the re-render.
document.querySelectorAll("select[id^=f-]").forEach(s=>sel[s.id]=s.value); document.querySelectorAll("select[id^=f-]").forEach(select=>sel[select.id]=select.value);
// Table header. // Table header.
let h="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>"; let html="<thead><tr><th>recording<th>status<th>duration<th>speakers<th>MB<th>links<th>actions</tr></thead>";
// Pagination: PS meetings per page; clamp the page if recordings were removed, then draw the pager. // Pagination: PS meetings per page; clamp the page if recordings were removed, then draw the pager.
const np=Math.max(1,Math.ceil(j.recs.length/PS));if(pg_>=np)pg_=np-1; const pages=Math.max(1,Math.ceil(data.recs.length/PS));if(pg_>=pages)pg_=pages-1;
pgr.innerHTML=np>1?`<button ${pg_?"":"disabled"} onclick="goPg(-1)">‹</button><span>pagina ${pg_+1} di ${np} (${j.recs.length} riunioni)</span><button ${pg_<np-1?"":"disabled"} onclick="goPg(1)">›</button>`:""; pgr.innerHTML=pages>1?`<button ${pg_?"":"disabled"} onclick="goPg(-1)">‹</button><span>pagina ${pg_+1} di ${pages} (${j.recs.length} riunioni)</span><button ${pg_<pages-1?"":"disabled"} onclick="goPg(1)">›</button>`:"";
// One tbody per recording on the current page; "running" when the status is done but the process is still alive. // One tbody per recording on the current page; "running" when the status is done but the process is still alive.
for(const r of j.recs.slice(pg_*PS,(pg_+1)*PS)){const st=r.running&&r.status=="done"?"running":r.status; for(const row of data.recs.slice(pg_*PS,(pg_+1)*PS)){
// Display title, falling back to the upload name. // Display title, falling back to the upload name.
const nm=r.title||r.upload; const nm=row.title||row.upload;
// Main row: checkbox, title and rename buttons; status badge with error text and time since last data. // 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} h+=`<tbody class=rec><tr class=main><td><input type=checkbox class=mg value="${row.name}">${nm?`<b>${E(nm)}</b><br><small>${row.name}</small>`:row.name} <button class=del title="modifica titolo" onclick="setTitle('${row.name}','${E(row.title||row.upload||"").replace(/'/g,"")}')">✎</button>${row.mb&&row.files.includes("report.html")?`<button class=del title="ricalcola titolo" onclick="retitle('${row.name}')">↻</button>`:""}<td><span class="b ${row.status}" title="${E(row.error)}">${row.status}</span>${row.receiving_age_s!=null&&row.status==="recording"?` <small>${row.receiving_age_s}s ago</small>`:""}${row.error?`<br><small>${E(row.error)}</small>`:""}<td>${row.duration_s?fmt(row.duration_s):""}<td>${row.speakers??""}<td>${row.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>${row.files.includes("report.html")?`<a href="/report?name=${row.name}" target=_blank>report</a><a href="/pdf?name=${row.name}" target=_blank>pdf</a>`:""}${row.flow_run_id?`<a href="http://127.0.0.1:4200/runs/flow-run/${row.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>`}`; <td>${row.mb?`<select id="f-${row.name}">${["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].map(step=>`<option>${step}`).join("")}</select><button onclick="run('${row.name}')">run</button>`:""}<button onclick="spk('${row.name}')">speakers</button>${row.mb?`<button title="anteprima e ritaglio" onclick="play('${row.name}',${row.duration_s||0},'${E(nm||row.name).replace(/'/g,"")}')">▶ video</button>`:""}${row.mb&&row.status==="done"&&!row.running?`<button title="elimina solo il file video: report, trascrizione e schermate restano, ma non si può più rielaborare" onclick="dropVid('${row.name}',${row.mb})">🎞 elimina video</button>`:""}${row.running||row.status==="queued"?`<button onclick="stopRun('${row.name}')">stop</button>`:`<button class=del title="elimina la riunione" onclick="del_('${row.name}','${E(nm||row.name).replace(/'/g,"")}')">🗑</button>`}`;
h+=progPanel(r); html+=progPanel(row);
if(open_.has(r.name))h+=await panel(r.name);h+="</tbody>"} if(open_.has(row.name))html+=await panel(row.name);html+="</tbody>"}
// Re-render only when not editing a speaker field and no table input has focus, so user input is kept. // 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){}} const ae=document.activeElement;if(!editing&&!(ae&&t.contains(ae)&&/^(INPUT|SELECT)$/.test(ae.tagName))){const ck=[...document.querySelectorAll(".mg:checked")].map(box=>box.value);t.innerHTML=html;for(const id in sel){const element=document.getElementById(id);if(element)element.value=sel[id]}document.querySelectorAll(".mg").forEach(box=>box.checked=ck.includes(box.value));upd()}}catch{/* poll failed: next tick retries */}}
// Set while typing in a speaker name input. // 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()}); let editing=false;t.addEventListener("input",event=>{if(event.target.dataset.n)editing=true});t.addEventListener("change",event=>{if(event.target.classList.contains("mg"))upd()});
// Initial load, then poll every 3 s. // Initial load, then poll every 3 s.
tick();setInterval(tick,3000); tick();setInterval(tick,3000);
+6 -6
View File
@@ -17,15 +17,15 @@ module.exports = {
// highest CUDA the driver supports ("CUDA Version: 13.0", newer drivers "CUDA UMD Version: 13.4" in nvidia-smi) -> llama.cpp build; no NVIDIA/driver -> CPU build // highest CUDA the driver supports ("CUDA Version: 13.0", newer drivers "CUDA UMD Version: 13.4" in nvidia-smi) -> llama.cpp build; no NVIDIA/driver -> CPU build
// CUDA 13 also needs compute capability >= 7.5 (Maxwell/Pascal/Volta dropped, even on R580+ drivers) // CUDA 13 also needs compute capability >= 7.5 (Maxwell/Pascal/Volta dropped, even on R580+ drivers)
method: async (req, ondata, kernel) => { method: async (req, ondata, kernel) => {
let m = null, cc = 0 let versionMatch = null, computeCap = 0
try { m = execFileSync("nvidia-smi", { encoding: "utf8" }).match(/CUDA (?:UMD )?Version:\s*(\d+)\.(\d+)/) } catch (e) {} try { versionMatch = execFileSync("nvidia-smi", { encoding: "utf8" }).match(/CUDA (?:UMD )?Version:\s*(\d+)\.(\d+)/) } catch { /* no NVIDIA driver */ }
// lowest GPU wins // lowest GPU wins
try { cc = Math.min(...execFileSync("nvidia-smi", ["--query-gpu=compute_cap", "--format=csv,noheader"], { encoding: "utf8" }).trim().split(/\r?\n/).map(Number)) } catch (e) {} try { computeCap = Math.min(...execFileSync("nvidia-smi", ["--query-gpu=compute_cap", "--format=csv,noheader"], { encoding: "utf8" }).trim().split(/\r?\n/).map(Number)) } catch { /* no NVIDIA GPU */ }
// nvidia-smi CUDA version as major*100+minor (13.4 -> 1304); 0 when there is no NVIDIA driver. // nvidia-smi CUDA version as major*100+minor (13.4 -> 1304); 0 when there is no NVIDIA driver.
const v = m ? +m[1] * 100 + +m[2] : 0 const cudaVersion = versionMatch ? +versionMatch[1] * 100 + +versionMatch[2] : 0
// CUDA 13 (>= 1300) with compute capability >= 7.5 -> cuda-13.4 build; CUDA >= 12.04 -> cuda-12.4; otherwise CPU build. // CUDA 13 (>= 1300) with compute capability >= 7.5 -> cuda-13.4 build; CUDA >= 12.04 -> cuda-12.4; otherwise CPU build.
const build = v >= 1300 && cc >= 7.5 ? "cuda-13.4" : v >= 1204 ? "cuda-12.4" : "cpu" const build = cudaVersion >= 1300 && computeCap >= 7.5 ? "cuda-13.4" : cudaVersion >= 1204 ? "cuda-12.4" : "cpu"
ondata({ raw: `CUDA: ${m ? m[1] + "." + m[2] : "none"}, compute ${cc || "?"} -> llama.cpp ${build}\r\n` }) ondata({ raw: `CUDA: ${versionMatch ? versionMatch[1] + "." + versionMatch[2] : "none"}, compute ${computeCap || "?"} -> llama.cpp ${build}\r\n` })
return { build } return { build }
} }
}, },
+6
View File
@@ -0,0 +1,6 @@
line-length = 100
target-version = "py311"
[lint]
select = ["E", "F", "W", "I", "N", "A", "B", "UP", "SIM", "C4"]
ignore = ["E501"] # long prompt/HTML string literals