Compare commits

...
Author SHA1 Message Date
Stefano Zini 430d909396 ext: /health check blocks recording when the backend is offline, strobing offline alarm in popup 2026-11-10 14:51:20 +01:00
Stefano Zini d802b06c88 ui: sortable processing-date column 2026-11-10 14:51:19 +01:00
Stefano Zini 4ee270c37b report: participants as small chips at the end, hidden in the PDF 2026-11-10 14:51:18 +01:00
Stefano Zini 3f020cd246 report: less repetition, cleaner shots, correct speakers
- docs/memory passes get the facts already reported, so topics stop repeating them
- regroup pass merges consecutive topics on the same subject
- shots: settle 1.5s after a scene change, yuvj444p, no duplicate screen per topic,
  click-to-zoom in report.html, OCR identifier misreads fixed by majority vote
- speakers: split diarized paragraphs where Teams captions change speaker
- talk time from those paragraphs, counting only detected speech
2026-11-10 14:23:59 +01:00
Stefano Zini b80207a186 Allow reprocessing after video drop: skip audio/shots steps lacking media, limit reprocess dropdown to docs+; plus pending ext/report/ui changes 2026-11-06 10:56:30 +01:00
Stefano Zini d1d71ddafc server: add /reveal route (open meeting folder in Explorer) 2026-11-05 17:18:00 +01:00
Stefano Zini da309ce47f pdf: white 9pt document-style print CSS, download named after report title; ui tweaks 2026-11-05 17:16:46 +01:00
Stefano Zini bc98e0d004 ext: state-driven toolbar icon, restyled popup 2026-11-05 17:16:46 +01:00
Stefano Zini 23c0a18974 UI: actions menu, title/reprocess dialogs, collapsible progress, pdf download, labels 2026-11-05 16:23:02 +01:00
Stefano Zini 82001d4ffb install: exit shell after copilot login check 2026-11-05 15:03:19 +01:00
Stefano Zini ca36bf3c60 ui: fix undefined h/j in tick() that left the meetings table empty 2026-11-05 15:03:12 +01:00
Stefano Zini ead33657c7 Apply ruff lint and rename cryptic identifiers to readable names 2026-11-05 09:09:20 +01:00
Stefano Zini 19de4654ff stram response, like ais 2026-11-05 08:50:19 +01:00
Stefano Zini d3c6816181 UI: close buttons for search/Q&A results, bulk bar above table, pagination (100/page) 2026-11-04 15:58:13 +01:00
Stefano Zini 56c7fe8bd5 README: document upload/delete/crop/cancel/llm endpoints and title step 2026-11-04 14:26:15 +01:00
Stefano Zini 82b72b6c28 Add explanatory comments across codebase 2026-11-04 14:23:18 +01:00
Stefano Zini b8aa5548a2 Allow ask during pipeline when text model is cloud 2026-11-04 14:16:25 +01:00
Stefano Zini c1fbcc1688 db/report/server/UI updates 2026-11-04 14:14:26 +01:00
Stefano Zini a741859140 Auto-scale hardware: CUDA 13 only on cc>=7.5, pin ctranslate2 4.8 (cu12), fp16-less GPUs, CPU threads, llama --fit on >=7 GiB GPUs, CPU-only embeddings 2026-11-04 14:14:26 +01:00
Stefano Zini 03ba83fba8 server: spawn flow/prefect with CREATE_NO_WINDOW so no console pops 2026-11-04 13:29:13 +01:00
Stefano Zini 0c75b592f7 gitignore: packaged extension test (ext.crx/ext.pem) 2026-11-04 13:14:59 +01:00
Stefano Zini 0c760ecabf UI: move page to app/ui, model select next to 'Chiedi alle riunioni'; server/shots tweaks 2026-11-04 13:14:46 +01:00
Stefano Zini 6fe1c6c10d install: skip llama.cpp download/extract when llama-server.exe exists 2026-11-04 11:32:06 +01:00
Stefano Zini 5341f6c704 Install downloads via proxy-aware llama.py download (fs.download/hf go direct or fail TLS behind corp proxy) 2026-11-04 11:24:54 +01:00
Stefano Zini 946f88c2ef Merge branch 'cloud-onprem' of C:/pinokio/api/teams-whisper-cloud 2026-11-04 11:16:29 +01:00
Stefano Zini 654825ad67 ext: spoof Edge UA/client hints for Teams 2026-11-04 10:55:14 +01:00
Stefano Zini d423e18f57 Cloud/on-prem install choice, omp auth (Copilot + Anthropic), omp status in GUI 2026-11-04 09:46:52 +01:00
Stefano Zini 71b0d39b2a Add 'skip shots' GUI toggle and crop progress bar 2026-11-04 09:06:37 +01:00
Stefano Zini 9a69b78ff7 Drop stray srv.log 2026-11-03 16:56:48 +01:00
Stefano Zini a0f94183eb Merge copilot-llm: remote Copilot models for shots/report 2026-11-03 16:56:45 +01:00
Stefano Zini ca4a61d17e Remote Copilot models (italdesign BYOK + AI credits) for shots/report 2026-11-03 16:55:59 +01:00
Stefano Zini f855768f1f One folder per meeting (out/<name>/source.*, transcript.txt, meta.json, logs/), out/_global; speaker transcript from DB; throwaway Edge profile; skip shots only when all images exist 2026-11-03 16:02:05 +01:00
pinokio a479853372 Add .gitignore, Update 3 files 2026-11-03 15:47:54 +01:00
Stefano Zini 68846600c1 Drop-video button (blocks reruns), manual title, striped recording groups, collapse whisper loops, fix report _clean name clash 2026-11-03 15:06:00 +01:00
Stefano Zini 0a66ae0c05 Auto speaker count from roster, one-to-one speaker map, clean LLM junk, merge recordings, Teams caption scraping 2026-11-03 14:28:58 +01:00
Stefano Zini 9763b4ffab Merge video-preview-crop: GUI video preview + time crop 2026-11-03 14:09:14 +01:00
Stefano Zini 2c0139db8f GUI: video preview + time crop (crop saved as new meeting) 2026-11-03 11:02:55 +01:00
Stefano Zini 7f4e6e73b6 Probe duration via demux fallback (webm N/A); run one flow at a time, queue the rest 2026-11-02 18:06:53 +01:00
39 changed files with 6409 additions and 1666 deletions
+10
View File
@@ -0,0 +1,10 @@
__pycache__/
*.pyc
app/bin/
app/models/
app/out/
app/env/
env/
logs/
app/ext.crx
app/ext.pem
+34 -4
View File
@@ -34,11 +34,21 @@ Click **Install**. It downloads ffmpeg, llama.cpp (CUDA 13), the diarization mod
Alternative without the extension (desktop Teams, system loopback + mic): `cd app && uv run meet.py [--screen]`, Ctrl+C to stop.
Data lives in `app/out` (recordings, reports, `meetings.db`). **Reset** deletes models/binaries only, never `app/out`.
Data lives in `app/out`. **Reset** deletes models/binaries only, never `app/out`. One folder per meeting, one owner per datum:
```
out/meetings.db live state + search indexes (lines, shots, topics, call events, speaker map, memory)
out/_global/ llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs
out/<name>/source.<ext> the only video/audio source (removed by "elimina video"; the CLI recorder writes source.wav + source.mp4)
audio.opus transcript.txt (raw whisper) diar_segments.json shots.json + shots/ glossary.json docs.json
report.json (+ .md .html .pdf renders) meta.json (manual title, upload filename) progress.json logs/
```
The speaker-labelled transcript is the `lines` table (names are applied when the report renders); there is no `.spk.txt`. The `speakers` step maps diarization labels to people from Teams events, then re-splits each paragraph where the Teams captions change speaker (diarization merges similar voices, so one paragraph often holds two speakers); talk time in the report comes from those paragraphs. A meeting without `source.<ext>` cannot be re-run at all (`/run` returns 409, the GUI hides the run controls).
Other CLI tools (from `app/`):
- `uv run --script flow.py <name> --from report` — rerun a meeting from a step (`audio transcribe diarize speakers shots docs report memory render`)
- `uv run --script flow.py <name> --from report` — rerun a meeting from a step (`audio transcribe diarize speakers shots docs report memory render title`)
- `uv run --script flow.py <name> --bench-npu` — benchmark NPU vs CUDA and remember the faster one
- `uv run --script memory.py --reindex` — rebuild cross-meeting memory
- `uv run --script review.py <name>` — report quality gate
@@ -50,16 +60,36 @@ Base URL `http://127.0.0.1:18765`.
| Method | Path | Params |
|---|---|---|
| GET | `/status` | all recordings + pipeline status |
| GET | `/health` | `ok` when the server is up (the extension checks it before recording) |
| GET | `/report` | `name` → report HTML |
| GET | `/pdf` | `name` → report PDF |
| GET | `/search` | `q` → full-text search over transcripts/topics |
| GET | `/ask` | `q` → answer from cross-meeting memory, with sources |
| GET | `/ask` | `q` → answer from cross-meeting memory, with sources (JSON) |
| GET | `/ask_stream` | `q` → same, as NDJSON: `{"sources":[...]}` first, then `{"t":"text piece"}` events as the model writes |
| POST | `/chunk` | `name`, body = webm chunk (append) |
| POST | `/events` | `name`, body = JSON array of Teams call events |
| POST | `/stop` | `name` → finalize recording, start pipeline |
| POST | `/run` | `name`, `from`, `speakers` → rerun pipeline |
| POST | `/run` | `name`, `from`, `speakers` → accoda la pipeline (una alla volta; 409 se già in coda/esecuzione) |
| POST | `/run_all` | `from` → rerun every recording one at a time, oldest first (API only) |
| POST | `/merge` | `names` = comma list of ≥2 `.webm` recordings of one call → `<first>_merged` (stream copy, events time-shifted), queued |
| POST | `/title` | `name`, body = manual title (empty = clear) |
| POST | `/drop_video` | `name` → delete the source file of a finished meeting (report, transcript, shots stay; reruns then return 409) |
| POST | `/speaker_map` | `name`, body = `{"Speaker 1": "Mario Rossi"}` → re-render |
| POST | `/upload` | `filename`, body = raw audio/video file → new `meet_<timestamp>` meeting (unsupported extension or empty body = 400) |
| POST | `/delete` | `name` → delete a meeting (409 while recording/queued/running) |
| POST | `/crop` | `name`, `start`, `end` (seconds), `inplace=1` optional → trim the source into a new meeting, or replace it in place |
| POST | `/cancel` | `name` → kill the running pipeline |
| POST | `/skip_shots` | `v=1` skip the screen-content step, otherwise clear the flag |
| POST | `/llm` | `shots`, `report` → choose installed models (400 if not installed, only while idle) |
Read-only helpers used by the GUI:
| Method | Path | Params |
|---|---|---|
| GET | `/shot` | `name`, `file` → screenshot JPEG |
| GET | `/video` | `name` → source media (Range supported) |
| GET | `/speakers` | `name` → speaker info |
| GET | `/crop_progress` | `name` → `{"pct": …}` while a crop runs |
### curl
+39 -11
View File
@@ -1,17 +1,45 @@
"""Cheap non-AI audio cleanup: mono 16k, highpass, loudnorm -> out/<name>/audio.opus."""
import subprocess
import db
# Convert the meeting's audio track to 16 kHz mono Opus (small, speech-optimised).
def run(name):
src = db.media(name)[0]
if src is None: raise FileNotFoundError(f"no audio source for {name}")
dst = db.out_dir(name) / "audio.opus"
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000",
"-af", "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11", "-c:a", "libopus", "-b:a", "24k", str(dst)],
capture_output=True, text=True)
if r.returncode: raise RuntimeError(r.stderr[-500:])
d = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(dst)],
capture_output=True, text=True, check=True).stdout.strip()
db.upsert_recording(name, duration_s=float(d))
return dst
source_path = db.media(name)[0]
# No audio track: nothing to convert.
if source_path is None:
raise FileNotFoundError(f"no audio source for {name}")
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.
"-af",
"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.
if result.returncode:
raise RuntimeError(result.stderr[-500:])
# Store the duration probed from the output file.
db.upsert_recording(name, duration_s=db.duration(output_path))
return output_path
+26 -11
View File
@@ -1,19 +1,34 @@
import glob, os, site
# Shared helpers: makes the CUDA DLLs findable and loads the Whisper model.
import glob
import os
import site
import numpy as np
# pip nvidia-* wheels ship cublas/cudnn DLLs; ctranslate2 needs them on PATH (Windows)
for sp in site.getsitepackages():
for b in glob.glob(os.path.join(sp, "nvidia", "*", "bin")):
os.add_dll_directory(b); os.environ["PATH"] = b + os.pathsep + os.environ["PATH"]
# Each nvidia/<lib>/bin folder from the pip wheels is added to the DLL search path and PATH.
for site_packages in site.getsitepackages():
for bin_dir in glob.glob(os.path.join(site_packages, "nvidia", "*", "bin")):
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.
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
from faster_whisper import WhisperModel
def load_model(name):
"""CUDA if it really works (probe one decode), else CPU int8."""
# Try CUDA first; the probe below forces the real CUDA libs to load now, so a missing DLL fails here.
try:
m = WhisperModel(name, device="cuda", compute_type="float16")
list(m.transcribe(np.zeros(16000, np.float32))[0])
return m, "cuda"
except Exception as e:
print("cuda failed, using cpu:", e, flush=True)
return WhisperModel(name, device="cpu", compute_type="int8"), "cpu"
whisper_model = WhisperModel(name, device="cuda", compute_type="default")
# One second of silence forces an actual decode, not just a model load.
list(whisper_model.transcribe(np.zeros(16000, np.float32))[0])
return whisper_model, "cuda"
except Exception as error:
print("cuda failed, using cpu:", error, flush=True)
# CPU fallback: int8 quantisation, CORES threads.
return WhisperModel(name, device="cpu", compute_type="int8", cpu_threads=CORES), "cpu"
+349 -98
View File
@@ -1,11 +1,26 @@
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
import json, re, sqlite3, time
import contextlib
import json
import re
import sqlite3
import subprocess
import time
from pathlib import Path
# Everything lives under out/ next to this file: the DB and per-meeting folders.
HERE = Path(__file__).parent
OUT = HERE / "out"
DB = OUT / "meetings.db"
GLOBAL = (
OUT / "_global"
) # llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs, edge profile
GLOBAL.mkdir(parents=True, exist_ok=True)
# SQLite schema, applied on every connect(). FTS5 tables back full-text search;
# unicode61 with remove_diacritics 2 so accented and unaccented words match.
# speaker_map.source: "manual" entries are never overwritten by automatic matches.
# memory.vec: bge-m3 float32 embedding bytes (decoded in memory.py).
SCHEMA = """
CREATE TABLE IF NOT EXISTS recordings(
name TEXT PRIMARY KEY, source TEXT, started_at TEXT, ended_at TEXT,
@@ -22,187 +37,423 @@ CREATE TABLE IF NOT EXISTS speaker_map(name TEXT, label TEXT, person TEXT, sourc
CREATE TABLE IF NOT EXISTS memory(name TEXT, idx INTEGER, kind TEXT, t REAL, meeting TEXT, date TEXT, topic TEXT, anchor TEXT, text TEXT, vec BLOB);
CREATE INDEX IF NOT EXISTS memory_name ON memory(name);
"""
STATUSES = ["recording", "queued", "audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory", "done", "error"]
# Pipeline statuses written to recordings.status, in run order.
STATUSES = [
"recording",
"queued",
"audio",
"transcribing",
"diarizing",
"identifying",
"shots",
"docs",
"report",
"memory",
"done",
"error",
]
# Event kinds accepted in call_events (Teams web-call signals).
EVENT_KINDS = {"meta", "active", "present", "share_start", "share_stop", "caption", "chat", "hand"}
# Open a connection and apply the schema. Each caller opens its own connection.
def connect() -> sqlite3.Connection:
OUT.mkdir(exist_ok=True)
c = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False)
c.execute("PRAGMA journal_mode=WAL")
c.row_factory = sqlite3.Row
c.executescript(SCHEMA)
return c
# Autocommit (isolation_level=None) so BEGIN/COMMIT below are explicit; wait up to 30 s on locks.
conn = sqlite3.connect(DB, isolation_level=None, timeout=30, check_same_thread=False)
# WAL: the GUI can read while the flow writes.
conn.execute("PRAGMA journal_mode=WAL")
conn.row_factory = sqlite3.Row
# Idempotent: every CREATE uses IF NOT EXISTS.
conn.executescript(SCHEMA)
return conn
def upsert_recording(name: str, **f):
c = connect()
cols = ["name", *f]
sets = ",".join(f"{k}=excluded.{k}" for k in f) or "name=name"
c.execute(f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) "
f"ON CONFLICT(name) DO UPDATE SET {sets}", [name, *f.values()])
# Insert or update a recordings row; only the kwargs given are written.
def upsert_recording(name: str, **fields):
conn = connect()
cols = ["name", *fields]
# Empty kwargs -> "name=name" no-op, keeps the ON CONFLICT clause valid SQL.
sets = ",".join(f"{column}=excluded.{column}" for column in fields) or "name=name"
conn.execute(
f"INSERT INTO recordings({','.join(cols)}) VALUES({','.join('?' * len(cols))}) "
f"ON CONFLICT(name) DO UPDATE SET {sets}",
[name, *fields.values()],
)
# Upsert status (and error) for a meeting; updated_at is SQLite UTC time.
def set_status(name: str, status: str, error: str | None = None):
c = connect()
c.execute("INSERT INTO recordings(name,status,error,updated_at) VALUES(?,?,?,datetime('now')) "
conn = connect()
conn.execute(
"INSERT INTO recordings(name,status,error,updated_at) VALUES(?,?,?,datetime('now')) "
"ON CONFLICT(name) DO UPDATE SET status=excluded.status,error=excluded.error,updated_at=excluded.updated_at",
(name, status, error))
(name, status, error),
)
# Replace all transcript lines of a meeting; rows are (t, speaker, text).
def replace_lines(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM lines WHERE name=?", (name,))
c.executemany("INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)", [(name, t, s, x) for t, s, x in rows])
c.execute("COMMIT")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM lines WHERE name=?", (name,))
conn.executemany(
"INSERT INTO lines(name,t,speaker,text) VALUES(?,?,?,?)",
[(name, time_s, speaker, text) for time_s, speaker, text in rows],
)
conn.execute("COMMIT")
# Replace shots; shot_text is the FTS mirror of shots and must change with it.
def replace_shots(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM shots WHERE name=?", (name,))
c.execute("DELETE FROM shot_text WHERE name=?", (name,))
for r in rows:
c.execute("INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)",
(name, r["t"], r.get("t_end"), r["file"], r.get("kind"), r.get("title"), r.get("app"),
r.get("summary"), r.get("text"), json.dumps(r.get("entities") or {}, ensure_ascii=False)))
c.execute("INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)",
(name, r["t"], r.get("title") or "", f"{r.get('text') or ''}\n{r.get('summary') or ''}"))
c.execute("COMMIT")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM shots WHERE name=?", (name,))
conn.execute("DELETE FROM shot_text WHERE name=?", (name,))
for shot in rows:
conn.execute(
"INSERT INTO shots(name,t,t_end,file,kind,title,app,caption,text,entities) VALUES(?,?,?,?,?,?,?,?,?,?)",
(
name,
shot["t"],
shot.get("t_end"),
shot["file"],
shot.get("kind"),
shot.get("title"),
shot.get("app"),
shot.get("summary"),
shot.get("text"),
json.dumps(shot.get("entities") or {}, ensure_ascii=False),
),
)
# FTS body: extracted text plus LLM summary.
conn.execute(
"INSERT INTO shot_text(name,t,title,text) VALUES(?,?,?,?)",
(
name,
shot["t"],
shot.get("title") or "",
f"{shot.get('text') or ''}\n{shot.get('summary') or ''}",
),
)
conn.execute("COMMIT")
# Replace topics; each row also keeps the full topic dict as JSON.
def replace_topics(name, topics):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM topics WHERE name=?", (name,))
c.executemany("INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)",
[(name, i, t["title"], t.get("start_s"), t.get("end_s"), json.dumps(t, ensure_ascii=False)) for i, t in enumerate(topics)])
c.execute("COMMIT")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM topics WHERE name=?", (name,))
conn.executemany(
"INSERT INTO topics(name,idx,title,start_s,end_s,json) VALUES(?,?,?,?,?,?)",
[
(
name,
index,
topic["title"],
topic.get("start_s"),
topic.get("end_s"),
json.dumps(topic, ensure_ascii=False),
)
for index, topic in enumerate(topics)
],
)
conn.execute("COMMIT")
# Replace memory rows for a meeting (rows already carry vec bytes, see SCHEMA).
def replace_memory(name, rows):
c = connect()
c.execute("BEGIN")
c.execute("DELETE FROM memory WHERE name=?", (name,))
c.executemany("INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)", rows)
c.execute("COMMIT")
conn = connect()
conn.execute("BEGIN")
conn.execute("DELETE FROM memory WHERE name=?", (name,))
conn.executemany(
"INSERT INTO memory(name,idx,kind,t,meeting,date,topic,anchor,text,vec) VALUES(?,?,?,?,?,?,?,?,?,?)",
rows,
)
conn.execute("COMMIT")
# Per-meeting folder out/<name>/, created on demand.
def out_dir(name) -> Path:
d = OUT / name
d.mkdir(parents=True, exist_ok=True)
return d
folder = OUT / name
folder.mkdir(parents=True, exist_ok=True)
return folder
# Per-meeting logs folder (e.g. embed.log).
def logs(name) -> Path:
folder = out_dir(name) / "logs"
folder.mkdir(exist_ok=True)
return folder
def meta(name) -> dict:
"""out/<name>/meta.json: {"title": manual title, "upload": original filename}; absent keys = not set."""
return _jload(OUT / name / "meta.json", {})
def set_meta(name, **fields):
merged = {**meta(name), **fields}
# Falsy values (None, "") are dropped rather than stored.
_jsave(out_dir(name) / "meta.json", {key: value for key, value in merged.items() if value})
# ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ----
ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses
FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying",
"shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory"}
STATS = OUT / "step_stats.json"
ORDER = [
"audio",
"transcribing",
"diarizing",
"identifying",
"shots",
"docs",
"report",
"memory",
] # step statuses
# Flow step name -> GUI status it maps to (render and title roll into memory).
FROM = {
"audio": "audio",
"transcribe": "transcribing",
"diarize": "diarizing",
"speakers": "identifying",
"shots": "shots",
"docs": "docs",
"report": "report",
"memory": "memory",
"render": "memory",
"title": "memory",
}
# Learned speeds, merged over SPM at runtime.
STATS = GLOBAL / "step_stats.json"
# seconds of work per minute of audio, measured 2026-11-02 on RTX 500 Ada 4 GB + Core Ultra 7 155H (40-min call);
# replaced by a moving average of real runs as soon as one finishes (keys "<step>" or "<step>@<model>")
SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30,
"docs": 2, "report@qwen35b": 21, "report@qwen4b": 7, "report": 15, "memory": 1}
SPM = {
"audio": 1,
"transcribing": 6,
"diarizing": 9,
"identifying": 1,
"shots@qwen4b": 23,
"shots@qwen35b": 48,
"shots": 30,
"docs": 2,
"report@qwen35b": 21,
"report@qwen4b": 7,
"report": 15,
"memory": 1,
}
def _jload(p, default):
try: return json.loads(p.read_text(encoding="utf-8"))
except (OSError, ValueError): return default
# Read JSON; missing or corrupt file -> default.
def _jload(path, default):
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return default
def _jsave(p, o):
tmp = p.with_suffix(".tmp"); tmp.write_text(json.dumps(o), encoding="utf-8")
try: tmp.replace(p)
except OSError: pass # reader had it open: next tick writes again
# Write JSON via a temp file then rename, so readers never see a partial file.
def _jsave(path, data):
tmp_path = path.with_suffix(".tmp")
tmp_path.write_text(json.dumps(data), encoding="utf-8")
# reader had it open: next tick writes again
with contextlib.suppress(OSError):
tmp_path.replace(path)
# Seconds of work per audio minute for a step; a measured value beats the default.
def spm(key):
return {**SPM, **_jload(STATS, {})}.get(key) or SPM.get(key.split("@")[0], 5)
def delete_recording(name):
"""Remove a meeting everywhere: DB rows in every table keyed by name, out/<name>/ and out/<name>.* files."""
"""Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out/<name>/."""
import shutil
c = connect()
for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"):
c.execute(f"DELETE FROM {t} WHERE name=?", (name,))
conn = connect()
for table in (
"recordings",
"lines",
"shots",
"shot_text",
"topics",
"call_events",
"speaker_map",
"memory",
):
conn.execute(f"DELETE FROM {table} WHERE name=?", (name,))
shutil.rmtree(OUT / name, ignore_errors=True)
for p in OUT.glob(f"{name}.*"): p.unlink(missing_ok=True)
def progress(name):
return _jload(OUT / name / "progress.json", None)
# Fresh progress.json for a run; 'start' is the first step to execute (via FROM).
def progress_start(name, start_from):
now = time.time()
_jsave(out_dir(name) / "progress.json", {"run_start": now, "start": FROM.get(start_from, "audio"), "step": None, "key": None,
"step_start": now, "done": 0, "total": 0, "note": "", "updated": now, "steps": []})
_jsave(
out_dir(name) / "progress.json",
{
"run_start": now,
"start": FROM.get(start_from, "audio"),
"step": None,
"key": None,
"step_start": now,
"done": 0,
"total": 0,
"note": "",
"updated": now,
"steps": [],
},
)
def step(name, status, key=None):
"""Close the previous step (learn its speed), open `status` ("done" closes the run)."""
set_status(name, status)
p = progress(name)
if not p: return
state = progress(name)
if not state:
return
now = time.time()
if p["step"]:
p["steps"].append([p["step"], p["step_start"], now])
row = connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
if state["step"]:
state["steps"].append([state["step"], state["step_start"], now])
row = (
connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
)
mins = (row[0] or 0) / 60 if row else 0
if mins > 1 and now - p["step_start"] > 5: # skip no-op steps
st = _jload(STATS, {}); k = p["key"] or p["step"]; v = (now - p["step_start"]) / mins
st[k] = round(v if k not in st else 0.5 * st[k] + 0.5 * v, 2); _jsave(STATS, st)
p.update(step=None if status == "done" else status, key=key or status, step_start=now, done=0, total=0, note="", updated=now)
_jsave(OUT / name / "progress.json", p)
if mins > 1 and now - state["step_start"] > 5: # skip no-op steps
# Learn speed (seconds per audio minute); exponential average with the previous value.
stats = _jload(STATS, {})
stat_key = state["key"] or state["step"]
speed = (now - state["step_start"]) / mins
stats[stat_key] = round(
speed if stat_key not in stats else 0.5 * stats[stat_key] + 0.5 * speed, 2
)
_jsave(STATS, stats)
# 'done' clears step so the GUI shows the run as finished.
state.update(
step=None if status == "done" else status,
key=key or status,
step_start=now,
done=0,
total=0,
note="",
updated=now,
)
_jsave(OUT / name / "progress.json", state)
def tick(name, done, total, note=""):
"""In-step progress; also the heartbeat the GUI uses to show the run is alive."""
p = progress(name)
if not p: return
state = progress(name)
if not state:
return
now = time.time()
if done == 0 and total: p["t0"] = now # loop starts now: rate excludes model load / frame extraction before it
p.update(done=done, total=total, note=note, updated=now)
_jsave(OUT / name / "progress.json", p)
if done == 0 and total:
state["t0"] = now # loop starts now: rate excludes model load / frame extraction before it
state.update(done=done, total=total, note=note, updated=now)
_jsave(OUT / name / "progress.json", state)
def media(name):
"""(audio source, video source) in out/<name>/: source.<suffix> (the CLI recorder may write source.wav + source.mp4); .wav/.m4a/.mp3 have no video."""
# First existing candidate wins (order = preference).
def first(*exts):
for e in exts:
p = OUT / f"{name}{e}"
if p.exists(): return p
# audio source, video source; .mkv/.mov/.m4a/.mp3 come from GUI uploads (meet_*)
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov")
for suffix in exts:
candidate = OUT / name / f"source{suffix}"
if candidate.exists():
return candidate
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(
".webm", ".mp4", ".mkv", ".mov"
)
def duration(path) -> float:
"""Seconds. MediaRecorder webm has no container duration (N/A): fall back to a copy-demux pass (~1 s/h)."""
# Fast path: container duration from ffprobe (empty output when missing).
probe = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
capture_output=True,
text=True,
)
try:
return float(probe.stdout.strip())
except ValueError:
pass
# Slow path: decode the whole stream with -c copy; ffmpeg prints time= progress to stderr.
result = subprocess.run(
[
"ffmpeg",
"-v",
"error",
"-stats",
"-i",
str(path),
"-map",
"0",
"-c",
"copy",
"-f",
"null",
"-",
],
capture_output=True,
text=True,
)
# Take the last time=HH:MM:SS.ss value (end of stream).
times = re.findall(r"time=(\d+):(\d\d):(\d\d(?:\.\d+)?)", result.stderr)
if not times:
raise ValueError(((probe.stderr or result.stderr).strip() or "nessuna durata")[-300:])
hours, minutes, seconds = times[-1]
return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
def add_events(name, rows):
connect().executemany("INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
[(name, *r) for r in rows])
connect().executemany(
"INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
[(name, *row) for row in rows],
)
def events(name, *kinds):
q = "SELECT * FROM call_events WHERE name=?"
if kinds: q += f" AND kind IN ({','.join('?' * len(kinds))})"
return connect().execute(q + " ORDER BY t", (name, *kinds)).fetchall()
query = "SELECT * FROM call_events WHERE name=?"
# Optional kind filter; ORDER BY t gives timeline order.
if kinds:
query += f" AND kind IN ({','.join('?' * len(kinds))})"
return connect().execute(query + " ORDER BY t", (name, *kinds)).fetchall()
def speaker_names(name) -> dict:
return {r["label"]: r["person"] for r in connect().execute(
"SELECT label,person FROM speaker_map WHERE name=? AND person<>'' AND person IS NOT NULL", (name,))}
# Only real names: an empty or NULL person keeps the raw speaker label.
return {
row["label"]: row["person"]
for row in connect().execute(
"SELECT label,person FROM speaker_map WHERE name=? AND person<>'' AND person IS NOT NULL",
(name,),
)
}
# Upsert speaker label -> person, with its source (auto/manual) and overlap seconds.
def set_speaker_map(name, label, person, source, overlap_s=None):
connect().execute(
"INSERT INTO speaker_map(name,label,person,source,overlap_s) VALUES(?,?,?,?,?) "
"ON CONFLICT(name,label) DO UPDATE SET person=excluded.person,source=excluded.source,overlap_s=excluded.overlap_s "
"WHERE speaker_map.source != 'manual' OR excluded.source = 'manual'", (name, label, person, source, overlap_s))
# Manual names win; automatic matches never overwrite them.
"WHERE speaker_map.source != 'manual' OR excluded.source = 'manual'",
(name, label, person, source, overlap_s),
)
def norm_name(raw: str) -> str:
"""Port of norm() in ext/teams.js: 'Rossi, MARIO (IG/S-32)' -> 'Mario Rossi'."""
"""Port of norm() in suffix/teams.js: 'Rossi, MARIO (IG/S-32)' -> 'Mario Rossi'."""
raw = (raw or "").strip()
m = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw)
if not m: return raw
return " ".join(w.title() if w.isupper() else w for w in f"{m[2]} {m[1]}".split())
# Groups: "Last, First" plus an optional trailing "(...)" suffix, which is dropped.
match = re.match(r"^([^,]+),\s*([^(]+?)\s*(\(.*)?$", raw)
if not match:
return raw
# Title-case only ALL-CAPS words; mixed-case words are kept as written.
return " ".join(
word.title() if word.isupper() else word for word in f"{match[2]} {match[1]}".split()
)
+150 -46
View File
@@ -1,62 +1,166 @@
"""Label who speaks (sherpa-onnx, CPU): run(name) -> out/<name>.spk.txt, diar_segments.json, DB lines."""
import json, re, subprocess, time
"""Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled)."""
import json
import os
import re
import subprocess
import time
from pathlib import Path
import numpy as np
import db
import numpy as np
M = Path(__file__).parent / "models"
# sherpa-onnx default is 1 thread (>10 min for a 40-min call); 8 threads: ~6 min. CUDA measured slower (>7 min, GPU ~5 W):
# tiny models + one embedding per segment -> transfer/launch overhead dominates.
THREADS = 8
# Model files shipped under app/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.
# 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)
def run(name, speakers=5, threshold=0.85):
def roster_size(name, default=5):
"""Distinct people seen in the Teams roster events -> cluster count (a fixed 5 merged 8 people into 4 labels)."""
# Speakers seen in roster events (not video tiles); each event's text is a JSON list of {who}.
who = {
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.
return min(max(len(who), 2), 12) if who else default
# Diarize audio.opus, attach speaker labels to transcript lines, and save. Returns nothing.
def run(name, speakers=0, threshold=0.85):
speakers = speakers or roster_size(name)
# Imported here so the module loads without sherpa-onnx installed.
import sherpa_onnx
src = db.out_dir(name) / "audio.opus"
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(src), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
audio = np.frombuffer(raw, np.float32)
sd = sherpa_onnx.OfflineSpeakerDiarization(sherpa_onnx.OfflineSpeakerDiarizationConfig(
source_path = db.out_dir(name) / "audio.opus"
# Decode audio to 16 kHz mono float32 (sherpa input format).
pcm_bytes = subprocess.run(
[
"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.
diarizer = sherpa_onnx.OfflineSpeakerDiarization(
sherpa_onnx.OfflineSpeakerDiarizationConfig(
segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(M / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")),
num_threads=THREADS),
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(M / "emb.onnx"), num_threads=THREADS),
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(
model=str(MODEL_DIR / "sherpa-onnx-pyannote-segmentation-3-0/model.onnx")
),
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.
clustering=sherpa_onnx.FastClusteringConfig(num_clusters=speakers, threshold=threshold),
min_duration_on=0.3, min_duration_off=0.5))
t0, last = time.time(), [-1]
# Drop blips under 0.3 s and merge gaps under 0.5 s.
min_duration_on=0.3,
min_duration_off=0.5,
)
)
# Last printed decile, so progress prints every 10 %.
start_time, last_decile = time.time(), [-1]
def progress(done, total): # sherpa calls this per processed chunk; print every 10 %
pct = done * 100 // max(total, 1)
if pct // 10 > last[0]: last[0] = pct // 10; print(f"diarize {pct}% ({done}/{total}, {time.time() - t0:.0f} s)", flush=True)
if done % 20 == 0 or done == total: db.tick(name, done, total, "impronte vocali dei segmenti")
percent = done * 100 // max(total, 1)
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.
if done % 20 == 0 or done == total:
db.tick(name, done, total, "impronte vocali dei segmenti")
return 0
# Status for the GUI before the slow segmentation starts.
db.tick(name, 0, 0, "segmentazione dell'audio (~1-2 min)")
segs = [(s.start, s.end, s.speaker) for s in sd.process(audio, callback=progress).sort_by_start_time()]
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True)
# Run diarization; segments come back sorted by start time.
segments = [
(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 = []
for l in (db.OUT / f"{name}.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3]))
out, order = [], {}
for i, (t, text) in enumerate(lines):
t1 = lines[i + 1][0] if i + 1 < len(lines) else t + 5
ov = {}
for s, e, sp in segs:
o = min(e, t1) - max(s, t)
if o > 0: ov[sp] = ov.get(sp, 0) + o
sp = max(ov, key=ov.get) if ov else None
if sp is not None: order.setdefault(sp, len(order) + 1)
# Parse transcript lines '[mm:ss] text' into (seconds, text).
for line in (db.out_dir(name) / "transcript.txt").read_text(encoding="utf-8").splitlines():
match = re.match(r"\[(\d+):(\d+)\] (.*)", line)
if match:
lines.append((int(match[1]) * 60 + int(match[2]), match[3]))
# order: first-appearance numbering of speakers, for 'Speaker N' labels.
labelled, order = [], {}
for index, (time_s, text) in enumerate(lines):
# A line lasts until the next line starts; the last line is assumed 5 s.
next_time = lines[index + 1][0] if index + 1 < len(lines) else time_s + 5
overlap_by_speaker = {}
# Total overlap of each diarized segment with this line's window.
for seg_start, seg_end, speaker in segments:
overlap = min(seg_end, next_time) - max(seg_start, time_s)
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).
speaker = (
max(overlap_by_speaker, key=overlap_by_speaker.get) if overlap_by_speaker else None
)
# Number speakers by first appearance in the text.
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
# 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
else: out.append([t, sp, text])
if labelled and labelled[-1][1] == speaker and time_s - labelled[-1][0] < 60:
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
for s in sorted(segs):
order.setdefault(s[2], len(order) + 1)
(db.OUT / f"{name}.spk.txt").write_text("\n".join(
f"[{t//60:02d}:{t%60:02d}] " + (f"Speaker {order[sp]}: " if sp is not None else "") + text for t, sp, text in out), encoding="utf-8")
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8")
db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out])
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None}))
print("saved", db.OUT / f"{name}.spk.txt")
for segment in sorted(segments):
order.setdefault(segment[2], len(order) + 1)
# Save pcm_bytes diarized segments as JSON.
(db.out_dir(name) / "diar_segments.json").write_text(
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.
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.
db.upsert_recording(
name, speakers=len({speaker for _, speaker, _ in labelled if speaker is not None})
)
print("saved", len(labelled), "speaker-labelled lines")
+266 -79
View File
@@ -1,110 +1,297 @@
"""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 db, report
import contextlib
import json
import os
import re
import shutil
import subprocess
# report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address.
import db
import llama
import report
# twg CLI: from PATH, else the default per-user install location.
TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
PROXY = "http://zproxy.idg.audi.vwg:9400"
# Prompt: 4 short search queries (3-6 words) from the meeting description.
SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.'
# Prompt: relevance score 0-3 for each numbered candidate doc.
SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).'
# Full Jira key match (anchored).
KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$")
# Confluence checkbox line ("* [ ] text" or "* [x] text"); group 1 = text. Used to harvest people names.
PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
# Run twg. Returns parsed JSON for "-o json" calls, else stdout (None on failure).
# Retries once through the proxy when the failure looks like a network/proxy error.
def _twg(*args, timeout=120):
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
# Child env without Python home vars that would confuse twg.
env = {
key: value
for key, value in os.environ.items()
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
}
for attempt in range(2):
r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
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.
if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON
except ValueError: out = None
try:
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>"
if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)):
try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError): pass
else: out = r.stdout if r.returncode == 0 else None
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
env = {**env, "HTTPS_PROXY": PROXY, "HTTP_PROXY": PROXY}
if match := re.search(r'^\s*stdout:\s*"(.+?\.json)"', result.stdout, re.M):
try:
return json.loads(open(match[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError):
pass
# Plain-text mode: stdout only on success.
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.
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.
env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY}
# Gather candidate docs for a meeting: queries, Confluence/Jira search, Jira key lookups, LLM relevance scoring.
# Returns the docs.json payload; raises on hard failure (run() catches it).
def _run(name):
if not os.path.exists(TWG): raise FileNotFoundError("twg not found")
d = db.out_dir(name)
meta = [json.loads(e["text"]) for e in db.events(name, "meta") if e["who_key"] != "video"] # Teams topic only, never a shot guess
if not os.path.exists(TWG):
raise FileNotFoundError("twg not found")
# Per-meeting output directory.
meeting_dir = db.out_dir(name)
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 ""
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else []
shots = (
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
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]
txt = (db.OUT / f"{name}.txt").read_text(encoding="utf-8") if (db.OUT / f"{name}.txt").exists() else ""
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}"
# Titles of lead content screens: deduped, max 30.
screens = list(
dict.fromkeys(
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.
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.
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 = list({q.lower(): q for q in reversed(queries)}.values())[::-1]
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.
queries = list({query.lower(): query for query in reversed(queries)}.values())[::-1]
cand = {}
for q in queries:
for app, lim in (("confluence", 6), ("jira", 4)):
for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []:
u = it.get("url")
if not u or u in cand: continue
jk = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", u); cid = re.search(r"/pages/(\d+)", u)
cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None,
"title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False}
items = list(cand.values())
# Candidates keyed by URL across all queries.
candidates = {}
for query in queries:
# Confluence: up to 6 hits per query; Jira: up to 4.
for source_app, limit in (("confluence", 6), ("jira", 4)):
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.
url = item.get("url")
if not url or url in candidates:
continue
# Jira key from /browse/KEY-N URLs; Confluence page id from /pages/ID URLs.
jira_match = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", url)
confluence_match = re.search(r"/pages/(\d+)", url)
candidates[url] = {
"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())
blob = [txt] + [s.get("text") or "" for s in shots]
keys = [k for k in dict.fromkeys(m for b in blob for m in report.TICKET.findall(b)) if KEY.match(k)]
keys += [k for k in (e["key"] for e in items) if k and k not in keys]
mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)})
# Text to scan for ticket keys: transcript plus shot OCR text.
text_blocks = [transcript] + [shot.get("text") or "" for shot in shots]
# Ticket keys found in the content (valid format), then keys already on candidates.
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.
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.
known = {}
if keys[:20 + 6]:
r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for it in (r.get("data") or {}).get("items") or []:
if it.get("ok") and it.get("data"):
x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "")
for e in items:
if e["key"] in known: e["title"], e["status"] = known[e["key"]]
have = {e["key"] for e in items if e["key"]}
for k in keys:
if k in known and k in mentioned and k not in have:
items.append({"source": "jira", "key": k, "id": None, "title": known[k][0], "url": f"{report.JIRA_BROWSE}/{k}", "status": known[k][1], "snippet": "", "mentioned": True})
for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known)
# Only call twg when there are keys.
if keys[: 20 + 6]:
response = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for item in (response.get("data") or {}).get("items") or []:
if item.get("ok") and item.get("data"):
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.
for entry in items:
if entry["key"] in known:
entry["title"], entry["status"] = known[entry["key"]]
# Add mentioned Jira tickets not already in items.
have = {entry["key"] for entry in items if entry["key"]}
for key in keys:
if key in known and key in mentioned and key not in have:
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.
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.
scores = {}
rel = [e for e in items if not e["mentioned"]]
if rel:
u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel))
for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []:
try: scores[int(s["i"])] = int(s["score"])
except (KeyError, TypeError, ValueError): pass
for i, e in enumerate(rel): e["score"] = scores.get(i, 0)
for e in items:
e.setdefault("score", 3 if e["mentioned"] else 0)
keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"])
conf = [e for e in keep if e["source"] == "confluence"][:8]
jira = [e for e in keep if e["source"] == "jira" and not e["mentioned"]][:6] + [e for e in keep if e["mentioned"]]
keep = conf + jira
unscored = [entry for entry in items if not entry["mentioned"]]
# Only score non-mentioned items, if any.
if unscored:
# Numbered candidate list appended to the meeting description.
prompt = (
desc
+ "\n\nDOCUMENTI:\n"
+ "\n".join(
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).
for index, entry in enumerate(unscored):
entry["score"] = scores.get(index, 0)
# Mentioned items score 3 unless already set.
for entry in items:
entry.setdefault("score", 3 if entry["mentioned"] else 0)
# Keep mentioned items plus those scored >= 2, best first.
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.
confluence_items = [entry for entry in keep if entry["source"] == "confluence"][:8]
jira_items = [entry for entry in keep if entry["source"] == "jira" and not entry["mentioned"]][
:6
] + [entry for entry in keep if entry["mentioned"]]
keep = confluence_items + jira_items
for e in keep:
if e["source"] == "confluence" and e["id"]:
b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or ""
lines = b.splitlines()
if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:]
e["body"] = "\n".join(lines)[:6000]
else: e["body"] = f"{e['key']} {e['title']} ({e['status']})"
for i, e in enumerate(keep): e["i"] = i
# Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body.
for entry in keep:
if entry["source"] == "confluence" and entry["id"]:
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.
lines = body.splitlines()
if lines and lines[0].strip() == "+ Content loaded.":
lines = lines[1:]
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.
for index, entry in enumerate(keep):
entry["i"] = index
# People names: checkbox lines in bodies, multi-word only, deduped.
people = []
for e in keep:
for m in PEOPLE.finditer(e["body"]):
n = db.norm_name(m[1])
if " " in n and n not in people: people.append(n)
for entry in keep:
for match in PEOPLE.finditer(entry["body"]):
person = db.norm_name(match[1])
if " " in person and person not in people:
people.append(person)
return {"queries": queries, "items": keep, "people": people, "error": None}
# Entry point. Never fails the flow: errors are recorded in docs.json (error field) instead of raised.
def run(name):
try: out = _run(name)
except Exception as e:
print("docs failed:", repr(e), flush=True)
out = {"queries": [], "items": [], "people": [], "error": repr(e)[:300]}
(db.out_dir(name) / "docs.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
try:
output = _run(name)
except Exception as error:
print("docs failed:", repr(error), flush=True)
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"
)
+61
View File
@@ -0,0 +1,61 @@
// Make Teams see Edge instead of Opera: rewrite UA + client-hint request headers.
// Edge UA built from the browser's own UA: the Opera OPR/ token is removed and an Edg/ token is added.
const userAgent = navigator.userAgent;
// Chrome major version taken from the UA; falls back to 130 if the UA has no Chrome token.
const chromeMajor = (userAgent.match(/Chrome\/(\d+)/) || [])[1] || "130";
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.
const brands = `"Microsoft Edge";v="${chromeMajor}", "Chromium";v="${chromeMajor}", "Not_A Brand";v="24"`;
// Helper: builds one declarativeNetRequest header operation.
const headerSet = (header, value) => ({ header, operation: "set", value });
// Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start.
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [1],
addRules: [{
id: 1,
// Higher than default so this rule wins over other extensions' header rules.
priority: 1,
// Rewrite the outgoing request headers.
action: {
type: "modifyHeaders",
requestHeaders: [headerSet("User-Agent", edgeUA), headerSet("Sec-CH-UA", brands)],
},
condition: {
// Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft.
regexFilter: "^https://teams\\.(cloud\\.)?microsoft(\\.com)?/",
// Every request type Teams uses, including websocket handshakes.
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest", "script", "stylesheet", "image", "font", "websocket", "other"],
},
}],
});
// Toolbar icon per recorder state, drawn at runtime (no PNG assets). offscreen.js pushes {to:"bg", state} every second.
const ICON = {
idle: { bg: "#64748b", badge: "" },
recording: { bg: "#dc2626", badge: "REC" },
transcribing: { bg: "#2563eb", badge: "..." },
done: { bg: "#16a34a", badge: "OK" },
error: { bg: "#d97706", badge: "!" },
};
function drawIcon(state) {
const { bg, badge } = ICON[state] || ICON.idle;
const images = {};
for (const size of [16, 32, 48]) {
const canvas = new OffscreenCanvas(size, size), ctx = canvas.getContext("2d"), c = size / 2;
ctx.fillStyle = bg; ctx.beginPath(); ctx.arc(c, c, c, 0, 2 * Math.PI); ctx.fill();
ctx.fillStyle = ctx.strokeStyle = "#fff"; ctx.lineWidth = size / 8; ctx.lineCap = "round";
if (state === "recording") { ctx.beginPath(); ctx.arc(c, c, size * 0.22, 0, 2 * Math.PI); ctx.fill(); }
else if (state === "error") { ctx.fillRect(c - size * 0.07, size * 0.2, size * 0.14, size * 0.38); ctx.fillRect(c - size * 0.07, size * 0.68, size * 0.14, size * 0.14); }
else if (state === "done") { ctx.beginPath(); ctx.moveTo(size * 0.27, c); ctx.lineTo(size * 0.44, size * 0.68); ctx.lineTo(size * 0.74, size * 0.32); ctx.stroke(); }
else if (state === "transcribing") { for (const dx of [-0.24, 0, 0.24]) { ctx.beginPath(); ctx.arc(c + dx * size, c, size * 0.07, 0, 2 * Math.PI); ctx.fill(); } }
else { ctx.beginPath(); ctx.moveTo(size * 0.4, size * 0.28); ctx.lineTo(size * 0.72, c); ctx.lineTo(size * 0.4, size * 0.72); ctx.closePath(); ctx.fill(); }
images[size] = ctx.getImageData(0, 0, size, size);
}
chrome.action.setIcon({ imageData: images });
chrome.action.setBadgeText({ text: badge });
chrome.action.setBadgeBackgroundColor({ color: bg });
chrome.action.setTitle({ title: `Teams Whisper - ${state}` });
}
drawIcon("idle");
chrome.runtime.onMessage.addListener(message => { if (message.to === "bg") drawIcon(message.state); });
+8 -4
View File
@@ -1,10 +1,14 @@
{
"manifest_version": 3,
"name": "Teams Whisper Recorder",
"version": "1.1",
"version": "1.2",
"description": "Record Teams tab audio+video (+mic) and transcribe with local whisper server",
"permissions": ["tabCapture", "offscreen", "activeTab", "tabs"],
"host_permissions": ["http://127.0.0.1:18765/*"],
"content_scripts": [{ "matches": ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], "js": ["teams.js"], "run_at": "document_idle" }],
"permissions": ["tabCapture", "offscreen", "activeTab", "tabs", "declarativeNetRequest"],
"host_permissions": ["http://127.0.0.1:18765/*", "https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"],
"background": { "service_worker": "background.js" },
"content_scripts": [
{ "matches": ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], "js": ["spoof.js"], "run_at": "document_start", "world": "MAIN", "all_frames": true },
{ "matches": ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], "js": ["teams.js"], "run_at": "document_idle" }
],
"action": { "default_popup": "popup.html" }
}
+2
View File
@@ -1,2 +1,4 @@
<!-- Opened as a normal tab so Chrome can show the mic permission prompt; close it after granting. -->
<body>Allow the microphone, then close this tab.
<!-- mic.js requests the permission. -->
<script src="mic.js"></script>
+5 -2
View File
@@ -1,3 +1,6 @@
// Run in mic.html (a normal tab): asks for mic permission once so offscreen.js can use it later without a prompt.
navigator.mediaDevices.getUserMedia({ audio: true })
.then(s => { s.getTracks().forEach(t => t.stop()); document.body.append(" granted."); })
.catch(e => document.body.append(" " + e));
// Stop the probe tracks at once: only the permission grant was needed, not the audio.
.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).
.catch(error => document.body.append(" " + error));
+1
View File
@@ -1 +1,2 @@
<!-- Hidden offscreen document created by popup.js to hold the recorder; not shown to the user. -->
<script src="offscreen.js"></script>
+67 -41
View File
@@ -1,57 +1,83 @@
// Offscreen document: records the Teams tab (tabCapture) and uploads 10 s WebM chunks to the local server.
// Local server endpoint (server.py); must match start.js port 18765.
const API = "http://127.0.0.1:18765";
let rec, ctx, tab, mic, q = Promise.resolve(), name;
let recorder, audioContext, tabStream, micStream, uploadQueue = Promise.resolve(), recordingName;
// 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: "" };
// Toolbar icon follows state; failed uploads while recording show as error. The idle icon is drawn by background.js on startup.
setInterval(() => chrome.runtime.sendMessage({ to: "bg", state: recorderState.state === "recording" && recorderState.failed ? "error" : recorderState.state }), 1000);
chrome.runtime.onMessage.addListener((m, _s, send) => {
if (m.to !== "off") return;
if (m.cmd === "status") send(S);
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 (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 (m.cmd === "stop") { rec.stop(); send({ ok: true }); }
// Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored.
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message.to !== "off") return;
if (message.cmd === "status") sendResponse(recorderState);
// start is async: reply with ok, or with the error text (also stored in recorderState for the popup).
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.
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.
if (message.cmd === "stop") { recorder.stop(); sendResponse({ ok: true }); }
// Keep the message channel open for the async replies above.
return true;
});
// Send buffered Teams events to the server; on failure count it so the popup can warn.
async function flushEv() {
if (!S.ev.length) return;
const b = S.ev.splice(0);
if (!recorderState.ev.length) return;
const batch = recorderState.ev.splice(0);
try {
const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });
if (!r.ok) throw 0;
S.evSent += b.length;
} catch { S.failed++; }
const response = await fetch(`${API}/events?name=${recordingName}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(batch) });
if (!response.ok) throw 0;
recorderState.evSent += batch.length;
} catch { recorderState.failed++; }
}
async function start(id, tabId) {
name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } };
tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src });
ctx = new AudioContext();
const dest = ctx.createMediaStreamDestination();
const t = ctx.createMediaStreamSource(tab);
t.connect(dest);
t.connect(ctx.destination); // tabCapture mutes the tab; play it back
// Start recording the given tab (id from tabCapture.getMediaStreamId).
async function start(streamId, tabId) {
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.
const captureConstraint = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: streamId } };
const videoConstraint = { mandatory: { ...captureConstraint.mandatory, maxFrameRate: 15 } }; // fewer fps = more bits per frame for slides/text
tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: videoConstraint });
for (const t of tabStream.getVideoTracks()) t.contentHint = "detail"; // favor sharpness over motion
// Mixer: tab audio + optional mic are mixed into one destination track.
audioContext = new AudioContext();
const dest = audioContext.createMediaStreamDestination();
const tabSource = audioContext.createMediaStreamSource(tabStream);
tabSource.connect(dest);
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.
try { // needs one-time grant via mic.html
mic = await navigator.mediaDevices.getUserMedia({ audio: true });
ctx.createMediaStreamSource(mic).connect(dest);
} catch { mic = null; }
const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]);
rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
rec.ondataavailable = e => {
q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv);
micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
audioContext.createMediaStreamSource(micStream).connect(dest);
} catch { micStream = null; }
// Output stream: tab video + mixed audio.
const outStream = new MediaStream([...tabStream.getVideoTracks(), ...dest.stream.getAudioTracks()]);
// VP8 video + Opus audio at 3 Mbps video (1 Mbps gave blocky/ringing text on shared screens).
recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 3e6 });
// Each 10 s chunk is uploaded in order through the uploadQueue promise chain.
recorder.ondataavailable = event => {
// Chain the upload on uploadQueue so chunks reach the server in order; count success or failure, then flush events.
uploadQueue = uploadQueue.then(() => fetch(`${API}/chunk?name=${recordingName}`, { method: "POST", body: event.data })).then(() => recorderState.chunks++, () => recorderState.failed++).then(flushEv);
};
rec.onstop = async () => {
S.state = "transcribing"; S.t1 = Date.now();
// Stop path: wait for uploads, release the capture, then ask the server to transcribe.
recorder.onstop = async () => {
recorderState.state = "transcribing"; recorderState.t1 = Date.now();
try {
await q;
// Wait for all queued chunk uploads to finish before asking for transcription.
await uploadQueue;
await flushEv();
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop()));
ctx.close();
const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" });
S.text = await r.text(); S.state = r.ok ? "done" : "error";
} catch (e) { S.text = "server down or failed: " + e; S.state = "error"; }
rec = null;
// Release tab/mic capture devices and the audio context.
[tabStream, micStream].forEach(stream => stream && stream.getTracks().forEach(track => track.stop()));
audioContext.close();
// Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text.
const response = await fetch(`${API}/stop?name=${recordingName}`, { method: "POST" });
recorderState.text = await response.text(); recorderState.state = response.ok ? "done" : "error";
} catch (error) { recorderState.text = "server down or failed: " + error; recorderState.state = "error"; }
recorder = null;
};
Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId });
rec.start(10000);
// Reset per-session state and record the start time; events are kept in recorderState.ev until sent.
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.
recorder.start(10000);
}
+57 -3
View File
@@ -1,5 +1,59 @@
<body style="width:380px;font:13px sans-serif">
<button id="go">Start</button> <a href="mic.html" target="_blank">grant mic (once)</a>
<!-- Extension popup: Start/Stop button, mic-grant link, status line and transcript view. -->
<meta charset="utf-8">
<style>
:root { --accent: #64748b; }
body { width: 380px; margin: 0; padding: 16px; box-sizing: border-box; font: 13px/1.4 system-ui, "Segoe UI", sans-serif; color: #0f172a; background: #f8fafc; }
body[data-state=recording] { --accent: #dc2626; }
body[data-state=transcribing] { --accent: #2563eb; }
body[data-state=done] { --accent: #16a34a; }
body[data-state=error] { --accent: #d97706; }
body[data-state=offline] { --accent: #dc2626; }
#off { margin-bottom: 12px; padding: 12px 14px; border-radius: 8px; background: #fef2f2; border: 2px solid #dc2626; color: #7f1d1d; }
#off b { display: block; margin-bottom: 4px; font-size: 15px; color: #b91c1c; }
#off ol { margin: 8px 0 0; padding-left: 20px; }
body[data-state=offline] #st, body[data-state=offline] #txt { display: none; }
body[data-state=offline] #go:disabled { opacity: 1; background: #fecaca; color: #991b1b; }
/* Offline alarm: banner, button and dot strobe red/white. 0.4 s per cycle = 2.5 flashes/s, under the 3/s photosensitivity limit.
No prefers-reduced-motion opt-out on purpose: Windows with animations off reports "reduce" and would hide the alarm. */
body[data-state=offline] #off { animation: strobe .4s steps(1) infinite; }
body[data-state=offline] #go:disabled, body[data-state=offline] .dot { animation: strobe .4s steps(1) infinite reverse; }
@keyframes strobe { 0% { background: #dc2626; color: #fff; border-color: #fff; } 50% { background: #fff; color: #b91c1c; border-color: #dc2626; } }
body[data-state=offline] #off b { color: inherit; }
h1 { margin: 0 0 12px; font-size: 15px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); flex: none; }
body[data-state=recording] .dot { animation: pulse 1.2s infinite; }
@keyframes pulse { 50% { opacity: .25; } }
#go { width: 100%; padding: 10px; border: 0; border-radius: 8px; font: inherit; font-weight: 600; color: #fff; background: var(--accent); cursor: pointer; transition: filter .15s; }
#go:hover:not(:disabled) { filter: brightness(1.1); }
#go:disabled { opacity: .5; cursor: default; }
body[data-state=idle] #go, body[data-state=done] #go, body[data-state=error] #go { background: #0f172a; }
#st { margin-top: 12px; padding: 8px 10px; background: #fff; border: 1px solid #e2e8f0; border-left: 3px solid var(--accent); border-radius: 6px; word-break: break-word; }
#txt { margin: 12px 0 0; padding: 10px; white-space: pre-wrap; max-height: 260px; overflow: auto; background: #fff; border: 1px solid #e2e8f0; border-radius: 6px; font: 12px/1.45 ui-monospace, Consolas, monospace; }
#txt:empty { display: none; }
#srv { margin-top: 8px; font-size: 12px; color: #475569; display: flex; align-items: center; gap: 6px; }
#srv::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; }
#srv[data-ok=true]::before { background: #16a34a; }
#srv[data-ok=false] { color: #dc2626; font-weight: 600; }
#srv[data-ok=false]::before { background: #dc2626; }
a { display: inline-block; margin-top: 12px; color: #475569; font-size: 12px; }
</style>
<body data-state="idle">
<h1><span class="dot"></span>Teams Whisper</h1>
<!-- Shown by popup.js when /health fails and nothing is recording. -->
<div id="off" hidden>
<b>Backend offline. Recording is NOT possible.</b>
The Teams Whisper server (127.0.0.1:18765) is not running, so nothing would be saved.
<ol><li>Open Pinokio, then Teams Whisper, then press <b style="display:inline;font-size:inherit">Start</b>.</li><li>Wait until the dot below turns green.</li><li>Press Start here again.</li></ol>
</div>
<!-- Start/Stop; popup.js drives it. -->
<button id="go">Start</button>
<!-- Status line, filled by popup.js. -->
<div id="st"></div>
<pre id="txt" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre>
<!-- Backend health (/health), refreshed every second by popup.js. -->
<div id="srv"></div>
<!-- Transcript/result text returned by the recorder. -->
<pre id="txt"></pre>
<!-- mic.html opens in a new tab so the permission prompt can appear; needed once. -->
<a href="mic.html" target="_blank">grant mic (once)</a>
<script src="popup.js"></script>
</body>
+61 -25
View File
@@ -1,46 +1,82 @@
const $ = id => document.getElementById(id);
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg });
const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
let S = { state: "idle" }, lastErr = "";
// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
// Shorthand for getElementById.
const byId = elementId => document.getElementById(elementId);
// Forward a command to the offscreen document (addressed with to:"off").
const sendToOffscreen = message => chrome.runtime.sendMessage({ to: "off", ...message });
// Format milliseconds as m:ss.
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.
let recorderState = { state: "idle" }, lastError = "", serverOk = null;
// Backend liveness (server.py /health); false on any error or after 1.5 s.
const serverUp = () => fetch("http://127.0.0.1:18765/health", { signal: AbortSignal.timeout(1500) }).then(response => response.ok, () => false);
// Refresh the button and status line from state recorderState.
function render() {
const go = $("go"), st = $("st");
go.disabled = S.state === "transcribing";
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start";
st.textContent = {
const goButton = byId("go"), statusLine = byId("st");
// Backend down and not mid-recording: starting is impossible, the offline banner replaces the status line.
const offline = serverOk === false && recorderState.state !== "recording";
document.body.dataset.state = offline ? "offline" : recorderState.state;
byId("off").hidden = !offline;
// Pipeline busy after stop: no new start until it finishes.
goButton.disabled = offline || recorderState.state === "transcribing";
// Backend indicator under the button.
byId("srv").dataset.ok = serverOk ?? "";
byId("srv").textContent = serverOk == null ? "server: checking..." : serverOk ? "server: online" : "server: OFFLINE";
// Button doubles as Stop while recording.
goButton.textContent = offline ? "Recording blocked: server offline" : recorderState.state === "recording" ? "Stop + transcribe" : "Start";
// Status line text per recorder state.
statusLine.textContent = {
idle: "idle - open a Teams tab and press Start",
recording: `REC ${mmss(Date.now() - S.t0)} | ${S.chunks} chunks uploaded${S.failed ? ` | ${S.failed} FAILED (server down?)` : ""} | mic ${S.mic ? "on" : "OFF (grant it)"} | eventi call: ${S.evSent || 0}`,
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...`,
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
error: "ERROR (see below)",
}[S.state];
if (S.text) $("txt").textContent = S.text;
}[recorderState.state];
// Show the transcript/result text when there is one.
if (recorderState.text) byId("txt").textContent = recorderState.text;
}
// Poll the recorder state every second.
async function poll() {
if (await chrome.offscreen.hasDocument()) S = (await off({ cmd: "status" })) || S; else S = lastErr ? { state: "error", text: lastErr } : { state: "idle" };
// A failed Start wins; else ask the offscreen doc (if any) for its state, or show idle.
recorderState = lastError ? { state: "error", text: lastError } : (await chrome.offscreen.hasDocument()) ? (await sendToOffscreen({ cmd: "status" })) || recorderState : { state: "idle" };
serverOk = await serverUp();
render();
}
$("go").onclick = async () => {
if (S.state === "recording") {
if (S.tabId != null) await chrome.tabs.sendMessage(S.tabId, { cmd: "cap-stop" }).catch(() => {});
await new Promise(r => setTimeout(r, 300));
await off({ cmd: "stop" }); return poll();
// Start / Stop click handler.
byId("go").onclick = async () => {
// Stop path: first ask teams.js to stop its scanners.
if (recorderState.state === "recording") {
// Tell the Teams content script to stop (errors ignored: the tab may be gone).
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.
await new Promise(resolve => setTimeout(resolve, 300));
await sendToOffscreen({ cmd: "stop" }); return poll();
}
lastErr = "";
// Clear the previous error before a new attempt.
lastError = "";
try {
const [t] = await chrome.tabs.query({ active: true, currentWindow: true });
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.");
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id });
// Tab the user is looking at when the button is pressed.
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
// The popup itself is an extension page; it can't be recorded.
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.
const streamId = await chrome.tabCapture.getMediaStreamId({ targetTabId: activeTab.id });
// Health check before recording: backend down = nothing would be saved, so show the offline banner and stop here.
if (!(serverOk = await serverUp())) return render();
// Create the offscreen document once; it stays alive while recording.
if (!(await chrome.offscreen.hasDocument()))
await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" });
const r = await off({ cmd: "start", id, tabId: t.id });
if (r?.err) throw new Error(r.err);
chrome.tabs.sendMessage(t.id, { cmd: "cap-start" }).catch(() => {});
} catch (e) { lastErr = String(e); }
const response = await sendToOffscreen({ cmd: "start", id: streamId, tabId: activeTab.id });
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.
chrome.tabs.sendMessage(activeTab.id, { cmd: "cap-start" }).catch(() => {});
// Any failure is shown in the status line.
} catch (error) { lastError = String(error); chrome.runtime.sendMessage({ to: "bg", state: "error" }); }
render(); poll();
};
// Keep status fresh while the popup is open.
poll(); setInterval(poll, 1000);
+45
View File
@@ -0,0 +1,45 @@
// MAIN world, document_start: navigator.* reports Edge instead of Opera.
/* global Navigator */
(() => {
// Original UA string from the page (Opera).
const originalUA = navigator.userAgent;
// Only patch Opera; other browsers are left as-is.
if (!/OPR\//.test(originalUA)) return;
// Chrome major version, same logic as background.js.
const chromeMajor = (originalUA.match(/Chrome\/(\d+)/) || [])[1] || "130";
// Same UA rewrite as background.js: drop OPR/, add Edg/.
const edgeUA = originalUA.replace(/ OPR\/[\d.]+/, "") + ` Edg/${chromeMajor}.0.0.0`;
// Replace any Opera brand entry with Microsoft Edge, keeping its version.
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.
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.
defineGetter(Navigator.prototype, "userAgent", () => edgeUA);
// appVersion is the UA without the leading "Mozilla/".
defineGetter(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
// userAgentData (Client Hints) exists only in Chromium-based browsers.
const uaData = navigator.userAgentData;
// Older builds without UA-CH: nothing more to patch.
if (!uaData) return;
// Brand list with Opera replaced by Edge.
const brands = fixBrands(uaData.brands);
// Keep the original function bound to the real object.
const originalHighEntropy = uaData.getHighEntropyValues.bind(uaData);
// Replacement userAgentData object exposing the same fields as the original.
const patched = {
brands,
mobile: uaData.mobile,
platform: uaData.platform,
// High-entropy values also carry brands and fullVersionList: patch them too.
getHighEntropyValues: async hints => {
const result = await originalHighEntropy(hints);
if (result.brands) result.brands = fixBrands(result.brands);
if (result.fullVersionList) result.fullVersionList = fixBrands(result.fullVersionList);
return result;
},
// toJSON is used when the object is serialised; must match the patched fields.
toJSON: () => ({ brands, mobile: uaData.mobile, platform: uaData.platform }),
};
// Installed on the prototype, same as userAgent above.
defineGetter(Navigator.prototype, "userAgentData", () => patched);
})();
+92 -34
View File
@@ -1,108 +1,166 @@
// Content script on Teams web: logs active speaker, shares, captions, chat, hands, presence while recording.
// Events go via the offscreen document (it has host_permissions for 127.0.0.1). Never clicks or types in the call.
// DOM selectors for the Teams web client. The data-tid attributes are Teams' internal test ids and can change with Teams releases.
const SEL = {
// Call elapsed-time element.
duration: '[data-tid="call-duration"]',
// Name label inside each participant tile.
nametag: '[data-tid="participant-info-nametag"]',
// Participant info container.
info: '[data-tid="participant-info"]',
// Speaking outline: data-is-speaking="true" while the participant talks.
speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]',
// The local user's own video tile.
self: '[data-tid="myself-video"]',
// Screen-share banner aria-label (English and Italian UI); group 2 is the sharer's name.
shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/,
caption: null, captionAuthor: null, captionText: null, // discovery step (see plan 3b)
caption: '[data-tid="author"],[data-tid="closed-caption-text"]', // DOM order; author only on first row of a speaker's run
// Chat selectors not found yet (null): chat capture is disabled.
chatMsg: null, chatAuthor: null, chatText: null, // discovery step
// Raised-hand selector not found yet (null): hand capture is disabled.
hand: null, // discovery step
};
let buf = [], timers = [], seenCap = new WeakSet(), seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
// State: buf = queued events; timers = intervals; seenCap = caption rows already emitted; capAuthor = last caption speaker; seenChat; lastShare = current sharer; raised = hands up; lastTitle = last title sent.
let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
// Normalise a Teams display name: "LAST, First (Org)" -> "First Last"; ALL-CAPS words are title-cased.
const norm = raw => {
raw = (raw || "").trim();
const m = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!m) return raw;
return `${m[2]} ${m[1]}`.split(/\s+/).map(w => (w.length > 1 && w === w.toUpperCase() ? w[0] + w.slice(1).toLowerCase() : w)).join(" ");
// Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed.
const match = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!match) return raw;
// Reorder to "First Last" and title-case words that are fully uppercase.
return `${match[2]} ${match[1]}`.split(/\s+/).map(word => (word.length > 1 && word === word.toUpperCase() ? word[0] + word.slice(1).toLowerCase() : word)).join(" ");
};
const tileOf = el => { while (el && !el.querySelector(SEL.nametag)) el = el.parentElement; return el; };
// Walk up from an element to the participant tile (the ancestor containing a name tag).
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.
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() || "";
};
// Display name from a tile's name tag.
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; };
// Name of the local user, read from the self-video tile.
const selfName = () => { const selfTile = document.querySelector(SEL.self); return selfTile ? nameOf(selfTile) : ""; };
// 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 guard = f => () => { try { f(); } catch { } };
// Wrap timer callbacks so one exception does not kill the interval.
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).
const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
// All participant tiles currently in the DOM.
const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean);
// Emit the meeting title and call elapsed time, but only when the title changes.
function meta() {
// Page title looks like "Meeting | Name | Microsoft Teams": drop the leading segment and the trailing suffix.
const title = document.title.replace(/^[^|]*\|\s*/, "").replace(/\s*\|\s*Microsoft Teams$/, "");
// Nothing new since last time.
if (title === lastTitle) return;
lastTitle = title;
// Payload is JSON in the text field.
emit("meta", "", "", JSON.stringify({ title, call_elapsed: document.querySelector(SEL.duration)?.textContent.trim() || "", url: location.href }));
}
// Roster snapshot: one entry per participant key.
function present() {
// Dedupe by key (a participant can have more than one tile).
const seen = new Map();
for (const t of tiles()) seen.set(keyOf(t), { key: keyOf(t), who: t.closest(SEL.self) ? selfName() : nameOf(t) });
// The self tile's name comes from the self-video element.
for (const tile of tiles()) seen.set(keyOf(tile), { key: keyOf(tile), who: tile.closest(SEL.self) ? selfName() : nameOf(tile) });
// Roster snapshot payload.
emit("present", "", "", JSON.stringify([...seen.values()]));
}
// Emit one "active" event for each participant whose speaking outline is on.
function active() {
for (const el of document.querySelectorAll(SEL.speaking)) {
const t = tileOf(el); if (!t) continue;
if (t.closest(SEL.self) || t.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(t), nameOf(t));
// Speaking outlines in the DOM.
for (const element of document.querySelectorAll(SEL.speaking)) {
const tile = tileOf(element); if (!tile) continue;
// The local user speaking is recorded under the key "self".
if (tile.closest(SEL.self) || tile.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(tile), nameOf(tile));
}
}
// Screen share: detect the sharer from the banner aria-label and emit start/stop on change.
function share() {
// Roster names to match the banner text against.
const names = tiles().map(nameOf);
let cur = "";
for (const el of document.querySelectorAll("[aria-label]")) {
const m = el.getAttribute("aria-label").match(SEL.shareAria);
if (m) { cur = names.find(n => n && m[2].startsWith(n)) || m[2]; break; }
// Scan all aria-labels for the share banner.
for (const element of document.querySelectorAll("[aria-label]")) {
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.
if (match) { cur = names.find(name => name && match[2].startsWith(name)) || match[2]; break; }
}
// No change since last check.
if (cur === lastShare) return;
// Previous sharer stopped.
if (lastShare) emit("share_stop", "", lastShare);
if (cur) emit("share_start", "", cur);
lastShare = cur;
}
// Captions, chat and raised hands, each emitted once.
function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) {
if (seenCap.has(el)) continue; seenCap.add(el);
const text = el.querySelector(SEL.captionText)?.textContent.trim();
if (text) emit("caption", "", norm(el.querySelector(SEL.captionAuthor)?.textContent), text);
if (SEL.caption) for (const element of document.querySelectorAll(SEL.caption)) {
// Author row sets the speaker for the text rows that follow it.
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 of this row.
const text = element.textContent.trim(), seenState = seenCap.get(element) || {};
// Already emitted this row.
if (seenState.done) continue;
// Unchanged since last tick: treat as final and emit once.
if (text && seenState.text === text) { seenState.done = true; emit("caption", "", capAuthor, text); }
seenState.text = text; seenCap.set(element, seenState);
}
if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el);
const text = el.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(el.querySelector(SEL.chatAuthor)?.textContent), text);
// Chat messages (inactive while SEL.chatMsg is null); each element is counted once.
if (SEL.chatMsg) for (const element of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(element)) continue; seenChat.add(element);
const text = element.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(element.querySelector(SEL.chatAuthor)?.textContent), text);
}
// Hand raises (inactive while SEL.hand is null); emit only new raises.
if (SEL.hand) {
// Hands raised this tick.
const now = new Set();
for (const el of document.querySelectorAll(SEL.hand)) {
const t = tileOf(el); if (!t) continue;
const k = keyOf(t); now.add(k);
if (!raised.has(k)) emit("hand", k, nameOf(t));
for (const element of document.querySelectorAll(SEL.hand)) {
const tile = tileOf(element); if (!tile) continue;
const participantKey = keyOf(tile); now.add(participantKey);
// New raise since the last tick.
if (!raised.has(participantKey)) emit("hand", participantKey, nameOf(tile));
}
// Keep only hands still up.
raised = now;
}
}
// Stop: clear timers, flush pending events, and close any open share.
function stop() {
timers.forEach(clearInterval); timers = [];
send();
if (lastShare) { emit("share_stop", "", lastShare); lastShare = ""; }
send();
}
// Start a fresh recording: stop old timers, then reset per-recording state.
function start() {
stop();
buf = []; seenCap = new WeakSet(); seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
// Reset per-recording state.
buf = []; seenCap = new WeakMap(); capAuthor = ""; seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
// Emit the initial snapshot right away.
meta(); present();
// Periodic scans: speaker 500 ms, share and captions 1 s, roster 30 s, flush 5 s.
timers = [
setInterval(guard(() => { meta(); active(); }), 500),
setInterval(guard(() => { share(); messages(); }), 1000),
setInterval(guard(share), 1000),
setInterval(guard(messages), 1000),
setInterval(guard(present), 30000),
setInterval(guard(send), 5000),
];
}
chrome.runtime.onMessage.addListener(m => {
if (m.cmd === "cap-start") start();
if (m.cmd === "cap-stop") stop();
// Start/stop commands sent by popup.js directly to this tab.
chrome.runtime.onMessage.addListener(message => {
if (message.cmd === "cap-start") start();
if (message.cmd === "cap-stop") stop();
});
+248 -71
View File
@@ -1,150 +1,327 @@
# /// script
# requires-python = ">=3.10,<3.13"
# dependencies = ["prefect>=3", "faster-whisper", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"]
# dependencies = ["prefect>=3", "faster-whisper", "ctranslate2==4.8.*", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"]
# ///
# ponytail: ctranslate2 4.8 links cublas64_12 (matches the nvidia-*-cu12 wheels); bump all three together when it moves to CUDA 13
"""Meeting pipeline. uv run --script flow.py <name> [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]"""
# Prefect pipeline entry point. Env vars below (lines 8-16) must be set before prefect is imported (line 21).
import os
# Talk to the local Prefect server started by server.py; setdefault keeps a user override.
os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api")
# Bypass the corporate proxy for localhost, or Prefect API calls get routed out.
os.environ["NO_PROXY"] = "127.0.0.1,localhost"
# Turn off Prefect's usage analytics.
os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false"
# Prefect log level follows LOG_LEVEL (default INFO).
os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper())
os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI
import argparse, sys
# stdlib only: CLI args, JSON, paths, exit codes.
import argparse
import json
import sys
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.runtime import flow_run
from prefect.task_runners import ThreadPoolTaskRunner
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
HERE = Path(__file__).parent
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
# 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",
]
def step_status(name, s):
# Record the current stage for the GUI. LLM stages include the loaded model name so timing stats stay per model.
def step_status(name, stage):
# 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().
@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")
def t_transcribe(name, model, device, status=True):
if status: step_status(name, "transcribing")
def transcribe_task(name, model, device, status=True):
if status:
step_status(name, "transcribing")
transcribe.run(name, model=model, device=device)
@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")
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.
@task(name="shots", retries=1, retry_delay_seconds=10)
def t_shots(name, status=True):
if status: step_status(name, "shots")
def shots_task(name, status=True):
if status:
step_status(name, "shots")
shots.run(name)
@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)
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")
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.
class Llama:
"""Start llama-server in vision (shots) or text (report) profile; switching restarts it. Terminate in close() only if we started it."""
def __init__(self, name): self.name, self.p, self.vision = name, None, None
def __init__(self, name):
self.name, self.process, self.vision = name, None, None
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
log = db.out_dir(self.name) / ("llama.log" if vision else "llama_text.log")
log = db.logs(self.name) / ("llama.log" if vision else "llama_text.log")
try:
p = llama.start(vision=vision, log=log)
except Exception:
process = llama.start(vision=vision, log=log)
except Exception as error:
# llama.log with 'out of memory' means another CUDA app holds VRAM; tell the user the fix.
if log.exists() and "out of memory" in log.read_text(errors="replace"):
raise RuntimeError("GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'")
raise RuntimeError(
"GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'"
) from error
raise
self.p = self.p or p
# Keep the process we started earlier; llama.start() returns None when a server is already running.
self.process = self.process or process
def close(self):
if self.p and self.p.poll() is None: self.p.terminate(); self.p.wait() # wait: port must be free before a profile switch
self.p = None
if self.process and self.process.poll() is 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.
def default_device():
try:
d = (db.OUT / "transcribe_device.txt").read_text().strip()
return d if d in ("cuda", "npu") else "cuda"
device_name = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
return device_name if device_name in ("cuda", "npu") else "cuda"
except OSError:
return "cuda"
# Up to 3 threads; ordering comes from explicit .result() waits, not from the runner.
@flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3))
def meeting(name: str, start_from: str = "audio", speakers: int = 5, 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()
go = lambda s: STEPS.index(s) >= STEPS.index(start_from)
L = Llama(name)
# 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.
llama_server = Llama(name)
try:
# Link the DB row to this Prefect run so the GUI can find it.
db.upsert_recording(name, flow_run_id=str(flow_run.id))
db.progress_start(name, start_from)
if start_from == "render":
# shots run every time unless the GUI toggle "Salta schermate" is on
# Resume: reuse shots already extracted by an earlier run.
shots_json_path = db.out_dir(name) / "shots.json"
try:
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"
# Dropped video: reuse the shots already extracted; dropped source: reuse audio.opus (no audio/shots re-extraction).
no_video = db.media(name)[1] is None
skip_shots = no_shots or no_video
# Toggle on (or no video) with no prior shots: write empty placeholders so downstream steps find their files.
if skip_shots and not previous_shots:
for file_name in ("shots.json", "glossary.json"):
(db.out_dir(name) / file_name).write_text("[]")
db.replace_shots(name, [])
if skip_shots and should_run("shots"):
print("shots skipped")
def audio_ok():
return (db.out_dir(name) / "audio.opus").exists()
# Title/render restart: re-run only text-only post-processing, no vision model needed.
if start_from == "title":
llama_server.ensure(vision=False)
report.retitle(name)
memory.run(name, link=False)
elif start_from == "render":
memory.run(name, link=False)
else:
if go("audio"): t_audio(name)
spk_chain = lambda: [t_diarize(name, speakers), t_speakers(name)] if go("diarize") else ([t_speakers(name)] if go("speakers") else None)
if device == "npu" and go("transcribe") and go("shots"):
if should_run("audio") and db.media(name)[0]:
audio_task(name)
# Speaker labelling: diarize, then name mapping.
def speaker_chain():
return (
[diarize_task(name, speakers), speakers_task(name)]
if should_run("diarize") and audio_ok()
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.
if (
device == "npu"
and should_run("transcribe")
and should_run("shots")
and not skip_shots
):
db.set_status(name, "transcribing")
L.ensure()
f_t = t_transcribe.submit(name, model, "npu", False)
f_s = t_shots.submit(name, False)
llama_server.ensure()
transcribe_future = transcribe_task.submit(name, model, "npu", False)
shots_future = shots_task.submit(name, False)
# Wait for NPU transcription; shots keep running meanwhile.
try:
f_t.result()
except Exception as e:
if "NPU failed" not in repr(e): raise
f_s.result(); L.close()
transcribe_future.result()
except Exception as error:
# Only the NPU failure is handled here; anything else is a real error.
if "NPU failed" not in repr(error):
raise
shots_future.result()
llama_server.close()
print("NPU failed, transcribed on cuda")
t_transcribe(name, model, "cuda")
spk_chain(); L.ensure(); f_s = None
transcribe_task(name, model, "cuda")
# Shots already finished above; clear the handle.
speaker_chain()
llama_server.ensure()
shots_future = None
else:
spk_chain()
if f_s is not None: f_s.result()
speaker_chain()
# Shots still running in parallel; wait for them before text stages.
if shots_future is not None:
shots_future.result()
else:
if go("transcribe"): t_transcribe(name, model, device)
spk_chain()
if go("shots"): L.ensure(); t_shots(name)
L.ensure(vision=False) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
if go("docs"): t_docs(name)
if go("report"): t_report(name)
t_memory(name)
# Sequential path (CUDA, or NPU without shots).
if should_run("transcribe") and audio_ok():
transcribe_task(name, model, device)
speaker_chain()
if should_run("shots") and not skip_shots:
llama_server.ensure()
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_task(name)
db.step(name, "done")
except Exception as e:
db.set_status(name, "error", repr(e)[:500])
except Exception as error:
# Record the failure for the GUI, then re-raise so Prefect marks the run failed.
db.set_status(name, "error", repr(error)[:500])
raise
finally:
L.close()
llama_server.close()
# Benchmark both transcribers on the same audio and store the choice for default_device().
def bench(name):
d = db.out_dir(name)
try: npu_s = transcribe.run(name, device="npu", out_path=d / "bench_npu.txt")
except Exception as e: print("npu error:", e); npu_s = None
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt")
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
(db.OUT / "transcribe_device.txt").write_text(dev)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
out_dir = db.out_dir(name)
# A failed NPU run is recorded as None so the comparison below picks CUDA.
try:
npu_s = transcribe.run(name, device="npu", out_path=out_dir / "bench_npu.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).
chosen_device = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
# Persist for later runs (read by default_device).
(db.GLOBAL / "transcribe_device.txt").write_text(chosen_device)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={chosen_device}")
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
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")
ap = argparse.ArgumentParser()
ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS)
ap.add_argument("--speakers", type=int, default=5); ap.add_argument("--device", choices=["cuda", "npu"])
ap.add_argument("--bench-npu", action="store_true")
a = ap.parse_args()
if a.bench_npu: bench(a.name)
else: meeting(a.name, a.start, a.speakers, device=a.device)
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--from", dest="start", default="audio", choices=STEPS)
parser.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster")
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.
if args.bench_npu:
bench(args.name)
else:
meeting(args.name, args.start, args.speakers, device=args.device)
+724 -37
View File
@@ -1,72 +1,759 @@
import subprocess, time, urllib.request
# llama.py: starts llama-server (local GGUF chat/vision/embedding), routes chat to local or cloud models, installs omp and downloads models.
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
# Paths relative to this file: bin/ (llama-server, omp), models/ (GGUF), out/ (GUI state).
HERE = Path(__file__).parent
SERVER = HERE / "bin" / "llama-server.exe"
MD = HERE / "models"
CHOICE = HERE / "out" / "llm.txt" # GUI header: "<shots model> <report model>"
MODELS_DIR = HERE / "models"
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.
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
_KV_ARGS = [
"-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))
# Values below are the 4 GB profile; _fit() strips -ngl/-ot/--cpu-moe on >= 7 GiB GPUs.
MODELS = {
# 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).
"qwen35b": ("Qwen3.6 35B-A3B (RAM)", MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf",
["--mmproj-offload", *_IMG, "--cpu-moe", "-ngl", "30", "-c", "16384", *_Q],
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", "--reasoning-budget", "1024", *_Q]),
"qwen35b": (
"Qwen3.6 35B-A3B (RAM)",
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.
# 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.
"qwen4b": ("Qwen3.5 4B (VRAM)", MD / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf", MD / "qwen3.5-4b" / "mmproj-BF16.gguf",
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q],
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]),
"qwen4b": (
"Qwen3.5 4B (VRAM)",
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.
PORT = 18081
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
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.
@functools.cache
def vram_mib():
"""Largest NVIDIA GPU's total VRAM in MiB; 0 without NVIDIA driver."""
# memory.total per GPU in MiB, plain numbers (nounits); max() picks the largest card.
try:
return max(
int(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
def _fit(args, vision):
"""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."""
if vram_mib() < 7168:
return args
kept_args, arg_iter = [], iter(args)
for argument in arg_iter:
if argument in _TUNED:
for _ in range(_TUNED[argument]):
next(arg_iter)
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)
# key -> (label, model id, vision, provider). Vision=False: report/docs/memory/ask only (BYOK italdesign/ models reject images).
REMOTE = {
"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-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.
_COPILOT_HEADERS = {
"Editor-Version": "vscode/1.107.1",
"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].
_proxy_probe = [0.0, None]
def proxy():
"""PROXY if reachable right now (TCP connect, 2 s; = $PROFILE's Test-Connection), else None. Re-checked every 5 min: laptops move between office/VPN/home."""
if time.time() - _proxy_probe[0] > 300:
# Reachability probe only: a TCP connect to the proxy host, no HTTP request.
try:
socket.create_connection(("zproxy.idg.audi.vwg", 9400), timeout=2).close()
proxy_url = PROXY
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.
@functools.cache
def _opener(proxy_url):
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():
"""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())
def omp_env():
"""Env for omp subprocesses: omp ignores HTTP(S)_PROXY and reads PI_PROXY; the corp proxy re-signs TLS. Without the proxy, strip every proxy var."""
# Build omp's env without any inherited proxy vars, so a stale proxy setting cannot leak in.
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.
# Corp proxy only while reachable; it re-signs TLS, so omp must accept its certificate.
if proxy_url := proxy():
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.
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).
def available(vision=True):
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 available(): return [k for k, m in MODELS.items() if m[1].exists()]
def current(vision=True):
"""Model for shots (vision) or report/ask (text): GUI choice if on disk, else 4B for shots (VRAM-only, near-35B shots)
and the biggest model for reports (4B reports lose structure on long transcripts)."""
ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""]
k = ks[0] if vision else ks[-1] # a single key (old format) applies to both
av = available()
if k in av: return k
if vision and "qwen4b" in av: return "qwen4b"
return (av or ["qwen4b"])[0]
"""Model for shots (vision) or report/ask (text): GUI choice if available, else 4B for shots (VRAM-only, near-35B shots)
and the biggest local model for reports (4B reports lose structure on long transcripts). Falls back to the first cloud model only when no local model is installed (cloud-only install)."""
# CHOICE holds "<vision key> <text key>"; an empty file gives [""] so fallbacks apply.
keys = (CHOICE_FILE.read_text().split() if CHOICE_FILE.exists() else []) or [""]
key = keys[0] if vision else keys[-1] # a single key (old format) applies to both
if key in available(vision):
return key
local_keys = _local()
# 4B fits fully in VRAM: shots near 35B quality at much higher speed (see MODELS).
if vision and "qwen4b" in local_keys:
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)
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."""
cached = _token_cache.get(provider)
# Reuse the cached token for 5 min instead of spawning omp on every call.
if cached and time.time() - cached[2] < 300:
return cached[:2]
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.
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.
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.
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.
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).
_token_cache[provider] = (data["token"], base, time.time())
return _token_cache[provider][:2]
# Cache for omp_status(): [timestamp, status dict].
_omp_status_cache = [0.0, None]
def omp_status():
"""{'exe': path|None, 'github-copilot': None|reason, 'anthropic': None|reason}: can omp hand out a valid (refreshed) token right now. Cached 60 s (GUI polls every 3 s).
ponytail: a revoked Copilot token only shows up on the next API call (its expiresAt is years away)."""
if time.time() - _omp_status_cache[0] < 60:
return _omp_status_cache[1]
status = {"exe": omp_exe()}
for provider in ("github-copilot", "anthropic"):
# Drop the cached token so every provider is re-checked for real.
_token_cache.pop(provider, None)
try:
_token(provider)
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).
_ANTHROPIC_HEADERS = {
"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."""
# Anthropic accepts subscription OAuth only with the Claude Code identity as the first system block.
system, msgs = (
[{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude."}],
[],
)
for message in body["messages"]:
# Anthropic takes system as blocks, so system messages are collected separately.
if message["role"] == "system":
system.append({"type": "text", "text": message["content"]})
continue
content = message["content"]
if isinstance(content, list): # shots.py: text + data-URL jpeg
# OpenAI content parts -> Anthropic blocks; images arrive as data URLs.
content = [
{"type": "text", "text": part["text"]}
if part["type"] == "text"
# data:<mime>;base64,<data>: [5:] strips "data:", the mime is before ";".
else {
"type": "image",
"source": {
"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.
try:
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.
return {
"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):
"""Chat completion on llama-server, or on a cloud model (Copilot / Anthropic via omp login) when the GUI picked a REMOTE model."""
# Local llama-server unless the GUI picked a cloud (REMOTE) model.
# GUI choice decides local vs cloud; REMOTE holds the cloud model metadata.
key = current(vision)
remote = REMOTE.get(key)
if not remote:
# Local llama-server, OpenAI-compatible endpoint.
request = urllib.request.Request(
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.
token, api_base = _token(remote[3])
# chat_template_kwargs is llama.cpp-specific; cloud APIs would reject it.
body = {
**{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.
headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
**_COPILOT_HEADERS,
**({"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):
"""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."""
key = current(False)
remote = REMOTE.get(key)
if remote and remote[3] == "anthropic":
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:
token, api_base = _token(remote[3])
cloud_body = {
**{field: value for field, value in body.items() if field != "chat_template_kwargs"},
"model": remote[1],
"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]".
if not line.startswith(b"data: "):
continue
payload = line[6:].strip()
if payload == b"[DONE]":
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()).
def choose(vision_key, text_key):
CHOICE_FILE.write_text(f"{vision_key} {text_key}")
def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
def content(resp, what):
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints)."""
t = resp.get("timings") or {}
# llama.cpp reports timings; cloud APIs report usage instead.
timings = resp.get("timings") or {}
# Reasoning models: count thinking words for the speed log only.
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split())
if t: print(f"llm {what}: prompt {t.get('prompt_n', 0)} tok @ {t.get('prompt_per_second', 0):.0f} t/s, "
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s" + (f" (thinking ~{think} words)" if think else ""), flush=True)
if timings:
print(
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"]
def up(port=PORT):
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True
except Exception: return False
# Health probe: llama-server answers /health once the model is loaded.
def up(port=PORT):
try:
_open(f"http://127.0.0.1:{port}/health", timeout=2)
return True
except Exception:
return False
# Launch llama-server on port and wait until /health answers. Returns the Popen, or None if already up.
def _spawn(args, port, log):
if up(port): return None
p = subprocess.Popen([str(SERVER), *args, "--port", str(port)], stdout=open(log, "w"), stderr=subprocess.STDOUT)
# Already serving on this port: reuse it instead of starting a second copy.
if up(port):
return None
# Log to a file, not a pipe: nothing reads a pipe here, so the server would block once it fills.
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.
for _ in range(600):
if up(port): return p
assert p.poll() is None, f"llama-server died, see {log}"
if up(port):
return process
# Server exited (bad args, out of memory): fail now instead of waiting out the timeout.
assert process.poll() is None, f"llama-server died, see {log}"
time.sleep(2)
raise TimeoutError("llama-server not ready")
def start(vision=True, port=PORT, log="llama.log"):
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
_, model, mmproj, vargs, targs = MODELS[current(vision)]
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *vargs] if vision else targs), "--jinja"], port, log)
# Cloud choice from the GUI: no local server to start.
if current(vision) in REMOTE:
return None
# MODELS entry: (label, model, mmproj, vision args, text args).
_, model, mmproj, vision_args, text_args = MODELS[current(vision)]
# Vision: mmproj for images. Text: no mmproj. --jinja applies the model's chat template.
return _spawn(
[
"-m",
str(model),
*(
["--mmproj", str(mmproj), *_fit(vision_args, True)]
if vision
else _fit(text_args, False)
),
"--jinja",
],
port,
log,
)
def start_embed(log="embed.log"):
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
if not EMBED.exists():
raise FileNotFoundError(
f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models"
)
# bge-m3 on CPU only (-ngl 0, -dev none); 8k context; CLS pooling as bge-m3 expects.
return _spawn(
[
"-m",
str(EMBED),
"--embeddings",
"--pooling",
"cls",
"-ngl",
"0",
"-dev",
"none",
"-c",
"8192",
"-b",
"2048",
"-ub",
"2048",
],
EMBED_PORT,
log,
)
# Latest stable omp build metadata (JSON with download URL and sha256).
OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
# models.yml seeded into ~/.omp/agent: Copilot provider and its BYOK models.
MODELS_YML = """providers:
github-copilot:
auth: none
baseUrl: https://api.githubcopilot.com
models:
- id: italdesign/Bedrock_Mantle/qwen.qwen3-coder-480b-a35b-instruct
name: Qwen3 Coder 480B (Mantle)
api: openai-completions
supportsTools: true
contextWindow: 128000
maxTokens: 16384
tokenizer: qwen3
headers: &copilot_headers
Editor-Version: vscode/1.107.1
Editor-Plugin-Version: copilot-chat/0.26.7
Copilot-Integration-Id: copilot-developer-cli
- id: italdesign/Bedrock_Mantle/qwen.qwen3-vl-235b-a22b-instruct
name: Qwen3 VL 235B (Mantle)
api: openai-completions
tokenizer: qwen3
input: [text, image]
supportsTools: true
contextWindow: 256000
maxTokens: 8192
headers: *copilot_headers
- id: italdesign/Bedrock_Mantle/deepseek.v3.2
name: DeepSeek V3.2 (Mantle)
api: openai-completions
supportsTools: true
contextWindow: 163840
maxTokens: 8192
tokenizer: deepseek-v3
headers: *copilot_headers
- id: italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5
name: Kimi K2.5 (Mantle)
api: openai-completions
supportsTools: true
contextWindow: 262144
tokenizer: kimi-k2
maxTokens: 16384
headers: *copilot_headers
"""
def install_omp():
"""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())
else:
OMP_LOCAL.parent.mkdir(exist_ok=True)
headers = {
"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.
with (
_ropen()(
urllib.request.Request(build_info["download"], headers=headers), timeout=900
) as response,
open(part, "wb") as out_file,
):
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):
"""Interactive `omp login` in this console with the proxy env; if_needed: skip when omp already hands out a valid token (install)."""
omp_path = omp_exe()
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 if_needed:
try:
_token(provider)
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(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."""
dest = Path(dest)
if dest.exists():
print("kept", dest)
return
dest.parent.mkdir(parents=True, exist_ok=True)
part = dest.with_name(dest.name + ".part")
# Resume: bytes already in .part; ask the server for the rest (Range header).
have = part.stat().st_size if part.exists() else 0
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.
with (
_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>`.
if __name__ == "__main__":
args = sys.argv[1:]
if args == ["install-omp"]:
install_omp()
elif args[:1] == ["login"]:
login(args[1], "--if-needed" in args)
elif args[:1] == ["download"]:
download(args[1], args[2])
+139 -52
View File
@@ -6,71 +6,158 @@
Usage: uv run meet.py [--screen] [--name meet_...]
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
import numpy as np
import pyaudiowpatch as pa
ap = argparse.ArgumentParser()
ap.add_argument("--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)")
ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
ap.add_argument("--seconds", type=float, help="auto-stop after N seconds")
a = ap.parse_args()
out = Path(__file__).parent / "out"; out.mkdir(exist_ok=True)
SR = 16000
# CLI: --screen adds video, --name sets the folder under out/, --seconds auto-stops.
parser = argparse.ArgumentParser()
parser.add_argument(
"--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)"
)
parser.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
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).
SAMPLE_RATE = 16000
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)
# 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)
# Capture system audio (WASAPI loopback = what plays on the speakers) and the default mic.
def record():
p = pa.PyAudio()
lb = p.get_default_wasapi_loopback()
mic = p.get_device_info_by_index(p.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"])
bufs = {"sys": [], "mic": []}
audio_interface = pa.PyAudio()
# Loopback device and default mic device.
loopback_device = audio_interface.get_default_wasapi_loopback()
mic_device = audio_interface.get_device_info_by_index(
audio_interface.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"]
)
buffers = {"sys": [], "mic": []}
streams = []
for key, d in (("sys", lb), ("mic", mic)):
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"])
def cb(data, f, t, s, key=key): bufs[key].append(data); return (None, pa.paContinue)
st = p.open(format=pa.paInt16, channels=ch, rate=sr, input=True,
input_device_index=d["index"], frames_per_buffer=1024, stream_callback=cb)
streams.append((key, ch, sr, st))
print(f"loopback: {lb['name']}\nmic: {mic['name']}")
ff = None
if a.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(out / f"{a.name}.mp4")], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# One stream per source, at the device's own channel count and rate; converted to 16 kHz mono in the mix step.
for key, device in (("sys", loopback_device), ("mic", mic_device)):
channels, sample_rate = int(device["maxInputChannels"]), int(device["defaultSampleRate"])
# Callback appends raw PCM chunks; paContinue keeps the stream running.
def callback(data, frame_count, time_info, status_flags, key=key):
buffers[key].append(data)
return (None, pa.paContinue)
# int16 PCM, 1024-frame buffers.
stream = audio_interface.open(
format=pa.paInt16,
channels=channels,
rate=sample_rate,
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.
if args.screen:
ffmpeg_process = subprocess.Popen(
[
"ffmpeg",
"-y",
"-f",
"gdigrab",
"-framerate",
"15",
"-i",
"desktop",
"-c:v",
"libx264",
"-preset",
"ultrafast",
"-pix_fmt",
"yuv420p",
str(out / "source.mp4"),
],
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
print("Recording... Ctrl+C to stop")
# Wait until Ctrl+C or the --seconds limit.
try:
t0 = time.time()
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5)
except KeyboardInterrupt: pass
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait()
p.terminate()
mix = []
for key, ch, sr, st in streams:
raw = np.frombuffer(b"".join(bufs[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw): mix.append(to16k(raw[: len(raw) // ch * ch], ch, sr))
n = max(len(m) for m in mix)
y = sum(np.pad(m, (0, n - len(m))) for m in mix)
y = np.clip(y, -1, 1)
path = out / f"{a.name}.wav"
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((y * 32767).astype(np.int16).tobytes())
start_time = time.time()
while not args.seconds or time.time() - start_time < args.seconds:
time.sleep(0.5)
except KeyboardInterrupt:
pass
# Send 'q' so ffmpeg finalises the mp4 cleanly.
if ffmpeg_process:
ffmpeg_process.stdin.write(b"q")
ffmpeg_process.stdin.flush()
ffmpeg_process.wait()
# Stop PortAudio.
audio_interface.terminate()
# Mix: decode each stream and convert to 16 kHz mono float in [-1, 1].
mixed_sources = []
for key, channels, sample_rate, _stream in streams:
raw = np.frombuffer(b"".join(buffers[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw):
mixed_sources.append(
to16k(raw[: len(raw) // channels * channels], channels, sample_rate)
)
# Pad shorter streams with silence and sum them.
max_length = max(len(source) for source in mixed_sources)
mixed = sum(np.pad(source, (0, max_length - len(source))) for source in mixed_sources)
# Clip to avoid overflow when summing.
mixed = np.clip(mixed, -1, 1)
path = out / "source.wav"
# Write a 16-bit mono WAV.
with wave.open(str(path), "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(SAMPLE_RATE)
wav_file.writeframes((mixed * 32767).astype(np.int16).tobytes())
return path
# Save the DB row, then run the transcription/report pipeline (flow.py) as a child uv process.
def finish(path):
import os
import db
now = time.strftime("%Y-%m-%d %H:%M:%S")
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued")
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
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)
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
import db
now = time.strftime("%Y-%m-%d %H:%M:%S")
# Queued DB row with the start and end time.
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.
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.
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", args.name], cwd=Path(__file__).parent, env=env
)
# Start timestamp stored in the DB row.
start_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
# Record, then hand off to the pipeline.
finish(record())
+252 -79
View File
@@ -4,131 +4,304 @@
# ///
"""Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db.
uv run --script memory.py --reindex"""
import contextlib, json, re, sys, urllib.request
import numpy as np
import db, llama, report
import contextlib
import json
import re
import sys
import urllib.request
import db
import llama
import numpy as np
import report
# bge-m3 embeddings endpoint on the local embedding server.
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
# MEM_MIN: min cosine to link; K_TOPIC: candidates per topic; K_ASK: excerpts for a question.
MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
# Direct opener bypassing the corp proxy (the embedding server is localhost).
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.')
SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi SOLO JSON: {"answer":str}. Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.'
# Italian prompt: link current-meeting topics to earlier excerpts; JSON output.
SYS_M = (
'Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che questo argomento non chiude; "contesto": informazione precedente utile a capire l\'argomento. '
"Una sola voce per ciascun fatto precedente. Non ripetere, neanche riformulate, le voci in GIÀ COLLEGATI: sono già nel report sotto altri argomenti. "
'Non scrivere che qualcosa "non è stato ripreso oggi": vedi solo questo argomento, non tutta la riunione. '
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.'
)
# Prompt for ask(): answer from numbered excerpts only, cite as [n].
SYS_ASK = "Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi 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.
STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
# Start the CPU embedding server for the block; stop it on exit only if this call started it.
@contextlib.contextmanager
def embedder(log):
p = llama.start_embed(log=log)
try: yield
def embedder(log_path):
embed_process = llama.start_embed(log=log_path)
try:
yield
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.
def embed(texts):
out = []
for i in range(0, len(texts), 32):
body = {"input": [x[:2000] for x in texts[i:i + 32]], "model": "bge-m3"}
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])]
v = np.array(out, dtype=np.float32)
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
vectors = []
for start in range(0, len(texts), 32):
body = {"input": [text[:2000] for text in texts[start : start + 32]], "model": "bge-m3"}
response = json.load(
_open(
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.
return matrix / np.maximum(np.linalg.norm(matrix, axis=1, keepdims=True), 1e-9)
def _stamp(n):
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n)
return m[0] if m else ""
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
def _stamp(name):
match = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", name)
return match[0] if match else ""
# Load memory rows matching pred and stack their vectors into an (n, dim) matrix.
def _rows(pred):
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k.
rows = [r for r in db.connect().execute("SELECT * FROM memory") if pred(r)]
if not rows: return [], None
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1)
rows = [row for row in db.connect().execute("SELECT * FROM memory") if pred(row)]
if not rows:
return [], None
return rows, np.frombuffer(b"".join(row["vec"] for row in rows), np.float32).reshape(
len(rows), -1
)
def _txt(x): return x["text"] if isinstance(x, dict) else str(x)
# Summary entries may be dicts {"text": ...} or plain strings.
def _summary_text(item):
return item["text"] if isinstance(item, dict) else str(item)
def _topic_text(t, title=True):
parts = ([t["title"]] if title else []) + [_txt(x) for x in t.get("summary", [])] + list(t.get("decisions", [])) + list(t.get("open_questions", []))
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p)
# Topic as one string: title (optional), summary, decisions, open questions.
def _topic_text(topic, title=True):
parts = (
([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).
def index(name):
# slugify matches the report's heading anchors.
from markdown.extensions.toc import slugify
rep = report._load(name, "report.json", None)
if rep is None: return
rep, _ = report.named(name, rep)
report_json = report._load(name, "report.json", None)
if report_json is None:
return
report_json, _ = report.named(name, report_json)
items = []
for i, t in enumerate(rep["topics"], 1):
base = (name, i, t["start_s"], rep["meeting_title"], rep["date"], t["title"], slugify(report._head(i, t), "-"))
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])]
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])]
its += [("open_question", x) for x in t.get("open_questions", [])]
items += [(base, k, x) for k, x in its if x]
if not items: db.replace_memory(name, []); return
V = embed([f"{b[5]}: {x}" for b, _, x in items])
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)])
# One item per topic summary, decision, action and open question.
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).
base = (
name,
topic_index,
topic["start_s"],
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.
if not items:
db.replace_memory(name, [])
return
# Prefix the title so each item's vector carries its topic context.
vectors = embed([f"{base[5]}: {text}" for base, _, text in items])
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")
def _prev_line(n, r): return f"[{n}] {r['date']} «{r['meeting']}» — {r['topic']} ({r['kind']}): {r['text']}"
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, 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.
def _link(name):
rep = report._load(name, "report.json", None)
if rep is None: return
named_rep, _ = report.named(name, rep)
cur = _stamp(name)
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur)
for t in rep["topics"]: t["previous"] = []
report_json = report._load(name, "report.json", None)
if report_json is None:
return
named_report, _ = report.named(name, report_json)
# Stamp of this meeting, from its folder name.
current_stamp = _stamp(name)
# Only strictly earlier meetings; stamps sort lexicographically.
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.
for topic in report_json["topics"]:
topic["previous"] = []
reported = [] # (text, source anchor) of links already given to earlier topics of this meeting
if rows:
Q = embed([_topic_text(t) for t in named_rep["topics"]])
S = Q @ M.T
for t, nt, s in zip(rep["topics"], named_rep["topics"], S):
top = [j for j in np.argsort(-s)[:K_TOPIC] if s[j] >= MEM_MIN]
if not top: continue
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", []))
user = (f"ARGOMENTO: {nt['title']}\nSINTESI: {' '.join(_txt(x) for x in nt.get('summary', []))}\nDECISIONI: {'; '.join(nt.get('decisions', []))}\n"
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n"
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1)))
r = report.chat(SYS_M, user, 1500) or {}
for l in (r.get("links") or [])[:4]:
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip()
except (KeyError, TypeError, ValueError): continue
if 1 <= ref <= len(top) and st in STATUSES and tx:
p = rows[top[ref - 1]]
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"],
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]})
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
# Query vectors: each current topic as title + content.
query_vectors = embed([_topic_text(topic) for topic in named_report["topics"]])
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
similarity = query_vectors @ matrix.T
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.
top = [
index
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, numbered earlier excerpts the model may cite as [n], then links already reported.
user = (
f"ARGOMENTO: {named_topic['title']}\nSINTESI: {' '.join(_summary_text(item) for item in named_topic.get('summary', []))}\nDECISIONI: {'; '.join(named_topic.get('decisions', []))}\n"
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))
+ ("\n\nGIÀ COLLEGATI:\n" + "\n".join(f"- {text}" for text, _ in reported[-20:]) if reported else "")
)
# report.chat returns parsed JSON or None; None -> no links.
response = report.chat(SYS_M, user, 1500) or {}
# Cap at 4 links per topic (matches the prompt).
for link in (response.get("links") or [])[:4]:
# Validate LLM output: ref in range, known status, non-empty text.
try:
ref, status, text = int(link["ref"]), link["status"], str(link["text"]).strip()
except (KeyError, TypeError, ValueError):
continue
if 1 <= ref <= len(top) and status in STATUSES and text:
previous = rows[top[ref - 1]]
source = f"{previous['name']}#{previous['anchor']}"
# Same earlier excerpt, same content (word overlap >= 0.45): a repeat the model let through.
if any(
seen_source == source and report._jaccard(text, seen_text) >= 0.45
for seen_text, seen_source in reported
):
continue
reported.append((text, source))
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.
(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):
"""Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow."""
try:
with embedder(db.out_dir(name) / "embed.log"):
# Embedder lives for linking and indexing; its log sits with the meeting logs.
with embedder(db.logs(name) / "embed.log"):
if link:
try: _link(name)
except Exception as e: print("memory link skipped:", repr(e))
try:
_link(name)
except Exception as error:
print("memory link skipped:", repr(error))
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.
report.render(name)
def ask(q):
rows, M = _rows(lambda r: True)
if not rows: return {"answer": "Nessuna riunione indicizzata.", "sources": []}
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK]
rs = [rows[j] for j in top]
r = report.chat(SYS_ASK, f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1)), 1500) or {}
return {"answer": str(r.get("answer") or "Risposta non disponibile."),
"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]}
# 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.
def ask_stream(question):
# Cosine search over the normalized matrix; keep the best K_ASK excerpts.
rows, matrix = _rows(lambda row: True)
if not rows:
yield {"sources": []}
yield {"t": "Nessuna riunione indicizzata."}
return
top = np.argsort(-(matrix @ embed([question])[0]))[:K_ASK]
selected = [rows[index] for index in top]
yield {
"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__":
# Force UTF-8 so Italian text prints correctly on Windows consoles.
sys.stdout.reconfigure(encoding="utf-8")
# CLI: rebuild the memory index for every meeting that has a report.json.
if "--reindex" in sys.argv:
with embedder(db.OUT / "embed.log"):
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
with embedder(db.GLOBAL / "embed.log"):
for path in sorted(db.OUT.glob("*/report.json")):
index(path.parent.name)
+955 -320
View File
File diff suppressed because it is too large Load Diff
+170 -80
View File
@@ -2,116 +2,206 @@
# dependencies = []
# ///
"""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
from report import TICKET, _key, _sim
# Shared helpers from report.py: ticket regex, key normaliser, name similarity.
from report import _sim
from shots import CONTENT_KINDS
# Stopwords used by english() to tell English from Italian text.
ENG = {"the", "and", "of", "with", "is", "shows", "showing", "screenshot", "meeting", "displays"}
ITA = {"il", "la", "di", "che", "con", "della", "viene", "mostra", "sono", "per"}
def english(s):
w = re.findall(r"[a-zà-ú]+", str(s).lower())
e, i = sum(x in ENG for x in w), sum(x in ITA for x in w)
return e >= 3 and e > i
# True if text is mostly English: at least 3 English stopwords and more than Italian ones.
def english(text):
words = re.findall(r"[a-zà-ú]+", str(text).lower())
english_count, italian_count = (
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
def jpeg_w(p):
b = p.read_bytes(); i = 2
while i < len(b):
if b[i] != 0xFF: i += 1; continue
m = b[i + 1]
if m in (0xC0, 0xC1, 0xC2): return struct.unpack(">H", b[i + 7:i + 9])[0]
i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
# Read image width from the JPEG SOF marker (0 if not found).
def jpeg_w(path):
data = path.read_bytes()
index = 2
while index < len(data):
# Skip non-marker bytes.
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
# SOF0-SOF2: frame header holds height, then width (2 bytes each).
if marker in (0xC0, 0xC1, 0xC2):
return struct.unpack(">H", data[index + 7 : index + 9])[0]
# Jump over this segment using its length field.
index += 2 + struct.unpack(">H", data[index + 2 : index + 4])[0]
return 0
# Run all quality rules on one meeting's outputs; print failures; True if none.
def review(name):
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
md = (d / "report.md").read_text(encoding="utf-8")
html = (d / "report.html").read_text(encoding="utf-8")
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
docs = json.loads((d / "docs.json").read_text(encoding="utf-8")) if (d / "docs.json").exists() else None
out_dir = db.out_dir(name)
report = json.loads((out_dir / "report.json").read_text(encoding="utf-8"))
markdown_text = (out_dir / "report.md").read_text(encoding="utf-8")
html_text = (out_dir / "report.html").read_text(encoding="utf-8")
shots = (
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", [])
fails = []
F = lambda code, detail: fails.append(f"FAIL {code} {str(detail)[:200]}")
for m in re.finditer(r"\bSpeaker \d+\b", md): F("R1", md[max(0, m.start() - 40):m.end() + 40].replace("\n", " "))
# Record a failure with its rule code (R1-R12).
def fail(code, detail):
return fails.append(f"FAIL {code} {str(detail)[:200]}")
T, dur = rep["topics"], rep["duration_s"]
if not max(3, dur / 900) <= len(T) <= max(4, dur / 150): F("R2", f"{len(T)} topics for {dur / 60:.0f} min")
for t in T[:-1]:
if t["end_s"] - t["start_s"] < 120: F("R2", f"short topic {t['title']} {t['end_s'] - t['start_s']}s")
for t in T:
for x in t["shown"]:
m = re.search(r"(\d\d):(\d\d)", x)
if not m or not t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30: F("R3", f"{t['title']}: {x}")
# R1: no generic 'Speaker N' labels left in the report.
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", " "))
byfile = {}
for s in shots: byfile[s["file"]] = byfile[s.get("view") or s["file"]] = s
for sec in re.split(r"\n(?=## )", md):
imgs = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", sec)
if len(imgs) > 2: F("R4", f">2 images in {sec[:40]!r}")
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", md)
for f in used:
if byfile.get(f, {}).get("kind") not in CONTENT_KINDS: F("R4", f"{f} kind {byfile.get(f, {}).get('kind')}")
if any((s.get("view") or "").startswith("view_") for s in shots):
for f in used:
if not f.startswith("view_"): F("R4", f"uncropped image {f}")
# R2: topic count between dur/900 and dur/150 (min 3 / 4), so long calls get more topics.
topics, duration = report["topics"], report["duration_s"]
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.
for topic in topics[:-1]:
if topic["end_s"] - topic["start_s"] < 120:
fail("R2", f"short topic {topic['title']} {topic['end_s'] - topic['start_s']}s")
for topic in topics:
for shown_time in topic["shown"]:
# R3: each shown timestamp must fall inside the topic span (+/-30 s).
match = re.search(r"(\d\d):(\d\d)", shown_time)
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}")
texts = list(rep["tldr"])
for t in T:
texts += [x["text"] if isinstance(x, dict) else x for x in t["summary"]] + [x["text"] for x in t.get("from_docs", [])]
texts += [s.get("summary") or "" for s in t["shots"]]
for x in texts:
if english(x): F("R5", x)
shot_by_name = {}
# Index shots by file name and by cropped view name, for R4.
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.
for section in re.split(r"\n(?=## )", markdown_text):
images = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", section)
if len(images) > 2:
fail("R4", f">2 images in {section[:40]!r}")
# R4: every image used must be a content screen (CONTENT_KINDS).
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", markdown_text)
for file_name in used:
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.
if any((shot.get("view") or "").startswith("view_") for shot in shots):
for file_name in used:
if not file_name.startswith("view_"):
fail("R4", f"uncropped image {file_name}")
sec = re.search(r"## Partecipanti\n(.*?)(?=\n## )", md, re.S)
# R5: collect all prose fields to check for English.
texts = list(report["tldr"])
for topic in topics:
texts += [item["text"] if isinstance(item, dict) else item for item in topic["summary"]] + [
item["text"] for item in topic.get("from_docs", [])
]
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, chips or comma list); it is the last section.
section = re.search(r"## Partecipanti\n(.*?)(?=\n## |\Z)", markdown_text, re.S)
people = []
for l in (sec[1].splitlines() if sec else []):
if l.startswith("|"):
c = l.split("|")[1].strip()
if c not in ("Partecipante", "") and not c.startswith("-"): people.append(c)
elif l.strip() and not l.startswith("*"): people += [x.strip() for x in l.split(",")]
for p in people:
if re.fullmatch(r"[A-Z]{1,3}", p) or "..." in p or "…" in p: F("R6", f"initials/truncated {p}")
for i, a in enumerate(people):
for b in people[i + 1:]:
if _sim(a, b) >= 0.82: F("R6", f"{a} ~ {b}")
for line in section[1].splitlines() if section else []:
if line.startswith("|"):
cell = line.split("|")[1].strip()
if cell not in ("Partecipante", "") and not cell.startswith("-"):
people.append(cell)
elif "<span>" in line:
people += re.findall(r"<span>(.*?)</span>", line)
elif line.strip() and not line.startswith("*"):
people += [name_part.strip() for name_part in line.split(",")]
# R6: no initials or truncated names.
for person in people:
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).
for index, first in enumerate(people):
for second in people[index + 1 :]:
if _sim(first, second) >= 0.82:
fail("R6", f"{first} ~ {second}")
S = rep["shares"]
for s in S:
if s["end"] - s["start"] < 20: F("R7", f"short share {s}")
for a, b in zip(S, S[1:]):
if a["who"] == b["who"] and b["start"] - a["end"] <= 60: F("R7", f"mergeable {a['who']} {a['end']}->{b['start']}")
# R7: share segments must be >= 20 s and not split by a gap of <= 60 s.
shares = report["shares"]
for share in shares:
if share["end"] - share["start"] < 20:
fail("R7", f"short share {share}")
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']}")
rs = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", md, re.S)
ok = ({x["key"] for x in items if x["source"] == "jira" and x.get("mentioned")} if docs is not None
else {x["key"] for x in rep["references"]["tickets"]})
for k in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", rs[1] if rs else ""):
if k not in ok: F("R8", f"ticket {k}")
if "Numeri a schermo" in md or "**Email**" in md: F("R8", "numbers/email lists present")
# R8: ticket keys from the report's Ticket section.
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.
allowed_keys = (
{item["key"] for item in items if item["source"] == "jira" and item.get("mentioned")}
if docs is not None
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.
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.
if items:
if "## Documentazione correlata" not in md: F("R9", "missing Documentazione correlata")
urls = {x["url"] for x in items}
for u in re.findall(r"\[📄\]\(([^ )]+)", md):
if u not in urls: F("R9", f"citation url not in docs {u}")
if "## Documentazione correlata" not in markdown_text:
fail("R9", "missing Documentazione correlata")
urls = {item["url"] for item in items}
# Citation icon links in the markdown.
for url in re.findall(r"\[📄\]\(([^ )]+)", markdown_text):
if url not in urls:
fail("R9", f"citation url not in docs {url}")
if 'src="shots/' in html: F("R10", "unembedded image")
for b in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html):
if len(base64.b64decode(b)) <= 5000: F("R10", "tiny image")
if "## Trascrizione" in md: F("R11", "transcript present")
for f in set(used):
if f.startswith("view_") and jpeg_w(d / "shots" / f) < 600: F("R12", f"{f} narrow {jpeg_w(d / 'shots' / f)}px")
# R10: HTML must embed images, not reference shots/ paths.
if 'src="shots/' in html_text:
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.
if len(base64.b64decode(encoded)) <= 5000:
fail("R10", "tiny image")
# R11: transcript must not be included in the report.
if "## Trascrizione" in markdown_text:
fail("R11", "transcript present")
for file_name in set(used):
# R12: cropped views must be at least 600 px wide.
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"))
return not fails
if __name__ == "__main__":
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)
+1208 -413
View File
File diff suppressed because it is too large Load Diff
+505 -129
View File
@@ -1,191 +1,567 @@
"""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
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None}
CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"}
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.
EMPTY = {
"kind": "other",
"title": None,
"app": None,
"summary": "",
"text": "",
"entities": {},
"people": [],
"presenter": None,
"meeting_title": None,
"content_box": None,
}
# Kinds whose content is worth summarising in the report (the rest are chat/video/other).
CONTENT_KINDS = {
"slide",
"code",
"terminal",
"browser",
"document",
"spreadsheet",
"diagram",
"dashboard",
"ticket",
}
# Crop frames to the model-reported shared-content box (see _view).
CROP_BOX = True
KINDS = ["slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket", "chat", "video_tiles", "other"]
_S, _N, _L = {"type": "string", "maxLength": 300}, {"type": ["string", "null"], "maxLength": 200}, {"type": "array", "items": {"type": "string", "maxLength": 120}, "maxItems": 25}
# Seconds after a scene change before grabbing the frame: slide/tab swipe animations and Teams' share re-sharpening are over by then.
# A candidate followed by another change within SETTLE s is mid-transition and skipped.
SETTLE = 1.5
# Allowed values for 'kind'; also the grammar enum in SCHEMA.
KINDS = [
"slide",
"code",
"terminal",
"browser",
"document",
"spreadsheet",
"diagram",
"dashboard",
"ticket",
"chat",
"video_tiles",
"other",
]
# Schema shorthands: _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)
SCHEMA = {"type": "object", "additionalProperties": False,
"required": ["kind", "title", "app", "summary", "text", "entities", "people", "presenter", "meeting_title", "content_box"],
"properties": {"kind": {"enum": KINDS}, "title": _N, "app": _N, "summary": _S, "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": {k: _L for k in ("systems", "tickets", "urls", "numbers", "terms")}},
"people": _L, "presenter": _N, "meeting_title": _N,
"content_box": {"anyOf": [{"type": "array", "items": {"type": "integer"}, "minItems": 4, "maxItems": 4}, {"type": "null"}]}}}
SCHEMA = {
"type": "object",
"additionalProperties": False,
"required": [
"kind",
"title",
"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
# (v1 left title undefined), summary rules in Italian (v1 'ITALIAN' got echoed). Text before image: image-first measured worse.
PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"' + '|'.join(KINDS) + '","title":str|null,"app":str|null,"summary":str,"text":str,'
# Italian/English VLM prompt. Field list mirrors SCHEMA; the rules stop invented values.
PROMPT = (
'Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"'
+ "|".join(KINDS)
+ '","title":str|null,"app":str|null,"summary":str,"text":str,'
'"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}\n'
'Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles and captions, except for people/presenter/meeting_title.\n'
'- 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'
"Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles, captions and notification pop-ups/toasts (chat messages, meeting reminders), 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"
'- title: the heading written inside the shared content: slide title, diagram or document heading, page title (e.g. "Sprint Review Q3 - Backlog"). Use the active browser tab or window title only when the content has no heading. null only if no title is readable.\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'
'- 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'
"- summary: in italiano, massimo 40 parole: cosa si vede (nomi concreti: progetti, ambienti, servizi, valori). Inizia direttamente con il contenuto; niente frasi finali di commento (es. «utile per…», «serve a…»).\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"
'- 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'
'Never invent: use null or [] when absent.')
"- content_box: bounding box of the shared screen area (excluding Teams toolbar, video tiles, captions) in 0-1000 coordinates of this image; null if nothing is shared.\n"
"Never invent: use null or [] when absent."
)
# Jira-style issue key, e.g. ABC-123 (2-10 char project prefix).
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
# http(s) URL; stops at whitespace, quotes or closing brackets.
URL = re.compile(r"""https?://[^\s)\]>"']+""")
# Simple e-mail address.
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
# Send one keyframe to the VLM. json_mode=False drops response_format for servers that reject it.
def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode()
body = {"model": llama.current(True), "max_tokens": 1200, "temperature": 0.1,
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"
"chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]}
if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"}
req = urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"})
return llama.content(json.load(_open(req, timeout=900)), f"shot {path.name}")
"messages": [
{
"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.
if json_mode:
body["response_format"] = (
{"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}}
if SCHEMA
else {"type": "json_object"}
)
return llama.content(llama.post(body, True, 900), f"shot {path.name}")
# Read one frame. Two tries on bad JSON; always returns a full dict (EMPTY on failure).
def read_shot(path):
json_mode = True
# Retry once: VLM replies are sometimes malformed.
for _ in range(2):
try:
try: t = _ask(path, json_mode)
except urllib.error.HTTPError as e:
if e.code != 400 or not json_mode: raise
json_mode = False; t = _ask(path, False)
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
if isinstance(d, dict): return {**EMPTY, **d}
except (ValueError, KeyError): pass
try:
text = _ask(path, json_mode)
except urllib.error.HTTPError as err:
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.
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
# Keep only the outermost {...} in case of surrounding text.
parsed = json.loads(text[text.find("{") : text.rfind("}") + 1])
if isinstance(parsed, dict):
return {**EMPTY, **parsed}
except (ValueError, KeyError, IndexError):
pass # IndexError: cloud returned empty "choices" (content filter / transient)
return dict(EMPTY)
def _dedupe(xs):
seen, out = set(), []
for x in xs:
x = str(x).strip()
if x and x.lower() not in seen: seen.add(x.lower()); out.append(x)
return out
# Deduplicate case-insensitively, keep order, drop empties.
def _dedupe(items):
seen, unique = set(), []
for item in items:
item = str(item).strip()
if item and item.lower() not in seen:
seen.add(item.lower())
unique.append(item)
return unique
def _augment(d):
ent = d.get("entities") if isinstance(d.get("entities"), dict) else {}
blob = f"{d.get('text') or ''} {d.get('summary') or ''}"
for k in ("systems", "tickets", "urls", "numbers", "terms"): ent[k] = list(ent.get(k) or [])
ent["tickets"] += TICKET.findall(blob)
ent["urls"] += URL.findall(blob)
ent["emails"] = EMAIL.findall(blob)
d["entities"] = {k: _dedupe(v) for k, v in ent.items()}
d["people"] = _dedupe(d.get("people") or [])
# Merge regex-found tickets/URLs/e-mails into the model's entities; edits d in place.
def _augment(shot):
entities = shot.get("entities") if isinstance(shot.get("entities"), dict) else {}
blob = f"{shot.get('text') or ''} {shot.get('summary') or ''}"
for key in ("systems", "tickets", "urls", "numbers", "terms"):
entities[key] = list(entities.get(key) or [])
entities["tickets"] += TICKET.findall(blob)
entities["urls"] += URL.findall(blob)
entities["emails"] = EMAIL.findall(blob)
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)."""
w = int(subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", str(video)],
capture_output=True, text=True).stdout.strip() or 0)
r = subprocess.run(["ffmpeg", "-ss", str(dur / 2), "-i", str(video), "-vf", "cropdetect=24:16:0", "-frames:v", "60", "-f", "null", "-"],
capture_output=True, text=True)
m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr)
if not m or not w or int(m[-1][0]) < 0.5 * w: return None
return "crop=" + ":".join(m[-1])
# Frame width, to check the crop is a real side-bar removal.
width = int(
subprocess.run(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width",
"-of",
"csv=p=0",
str(video),
],
capture_output=True,
text=True,
).stdout.strip()
or 0
)
# cropdetect: black threshold 24, round 16 px, sampled at mid-video.
result = subprocess.run(
[
"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).
if not crop_matches or not width or int(crop_matches[-1][0]) < 0.5 * width:
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."""
from PIL import Image
if not CROP_BOX or not isinstance(box, list) or len(box) != 4 or not all(isinstance(v, (int, float)) for v in box): return path.name
im = Image.open(path); W, H = im.size
sx, sy = (1, 1) if max(box) > 1000 else (W / 1000, H / 1000)
x1, x2 = sorted((box[0] * sx, box[2] * sx)); y1, y2 = sorted((box[1] * sy, box[3] * sy))
x1, x2 = max(0, x1 - W * .01), min(W, x2 + W * .01); y1, y2 = max(0, y1 - H * .01), min(H, y2 + H * .01)
if x2 - x1 < .25 * W or y2 - y1 < .25 * H: return path.name
out = path.with_name(f"view_{path.stem}.jpg")
im.crop((int(x1), int(y1), int(x2), int(y2))).convert("RGB").save(out, quality=90)
return out.name
# Fall back to the full frame when no usable box was returned.
if (
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.
scale_x, scale_y = (1, 1) if max(content_box) > 1000 else (width / 1000, height / 1000)
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.
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.
if right - left < 0.25 * width or bottom - top < 0.25 * height:
return path.name
crop_path = path.with_name(f"view_{path.stem}.jpg")
image.crop((int(left), int(top), int(right), int(bottom))).convert("RGB").save(
crop_path, quality=95, subsampling=0
)
return crop_path.name
def _times(video, scene, bars=None):
r = subprocess.run(["ffmpeg", "-i", str(video), "-vf",
(bars + "," if bars else "") + f"fps=2,scale=640:-2,select='gt(scene,{scene})+isnan(prev_selected_t)+gte(t-prev_selected_t,60)',showinfo",
"-f", "null", "-"], capture_output=True, text=True)
return [float(m) for m in re.findall(r"pts_time:([\d.]+)", r.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.
result = subprocess.run(
[
"ffmpeg",
"-i",
str(video),
"-vf",
(bars + "," if bars else "")
+ f"fps=2,scale=640:-2,select='gt(scene,{scene})+isnan(prev_selected_t)+gte(t-prev_selected_t,60)',showinfo",
"-f",
"null",
"-",
],
capture_output=True,
text=True,
)
# Timestamps (seconds) parsed from showinfo output.
return [float(match) for match in re.findall(r"pts_time:([\d.]+)", result.stderr)]
# Fix rare OCR misreads inside identifiers by majority vote on their parts: 'sap-infra-iac'/'sep-env-dev' lose to 'scp-' seen on more frames.
# ponytail: hyphenated identifiers only (plain words like componente/components are real variants); one letter differs, never a digit or case.
def _fix_spelling(rows, fields=("title", "summary", "text")):
def strings(row):
return [row.get(field) or "" for field in fields] + [
item for items in (row.get("entities") or {}).values() for item in items if isinstance(item, str)
]
def identifiers(text):
return [token for token in re.findall(r"\w+(?:-\w+)+", text) if len(token) >= 6]
# Frames each identifier part ('scp', 'infra', 'iac') appears on.
counts = collections.Counter(
part
for row in rows
for part in {
part
for text in strings(row)
for token in identifiers(text)
for part in token.split("-")
if len(part) >= 3
}
)
fixes = {}
for rare, rare_count in counts.items():
for common, common_count in counts.most_common():
if common_count < max(3, 2 * rare_count):
break
diff = [(a, b) for a, b in zip(rare, common) if a != b]
if (
len(rare) == len(common)
and len(diff) == 1
and diff[0][0].isalpha()
and diff[0][1].isalpha()
and diff[0][0].lower() != diff[0][1].lower()
):
fixes[rare] = common
break
if not fixes:
return
def fix(text):
return re.sub(
r"\w+(?:-\w+)+",
lambda match: "-".join(fixes.get(part, part) for part in match[0].split("-"))
if len(match[0]) >= 6
else match[0],
text,
)
for row in rows:
for field in fields:
if row.get(field):
row[field] = fix(row[field])
for key, items in (row.get("entities") or {}).items():
row["entities"][key] = [fix(item) if isinstance(item, str) else item for item in items]
print("shots: spelling fixes", fixes, flush=True)
# Extract scene-change keyframes, dedupe, read each with the VLM, write shots.json and glossary, derive share/presence events.
def run(name, max_frames=60, scene=0.05):
import imagehash
from PIL import Image
d = db.out_dir(name)
out_dir = db.out_dir(name)
# media() returns (audio, video); index 1 is the video.
video = db.media(name)[1]
# No video: write empty outputs and stop.
if video is None:
db.replace_shots(name, [])
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]")
(out_dir / "shots.json").write_text("[]")
(out_dir / "glossary.json").write_text("[]")
return
sd = d / "shots"
sd.mkdir(exist_ok=True)
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
shots_dir = out_dir / "shots"
shots_dir.mkdir(exist_ok=True)
# Clear frames from a previous run.
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")
kept = [] # (t, path, hash)
bars = _bars(video, (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [0])[0] or 0)
for t in _times(video, scene, bars):
p = sd / f"shot_{int(t)//60:02d}m{int(t)%60:02d}s.jpg"
if any(k[1] == p for k in kept): continue # same second as a kept frame
subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(t), "-i", str(video), "-frames:v", "1",
*(["-vf", bars] if bars else []), "-q:v", "3", str(p)], check=True)
if not p.exists(): continue
h = imagehash.phash(Image.open(p))
if kept and h - kept[-1][2] <= 8: p.unlink(); continue
kept.append((t, p, h))
# 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,
)
times = _times(video, scene, bars)
for timestamp, next_change in zip(times, [*times[1:], float("inf")]):
if next_change - timestamp <= SETTLE:
continue # transitional: the next change follows within SETTLE s
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 + SETTLE),
"-i",
str(video),
"-frames:v",
"1",
*(["-vf", bars] if bars else []),
"-q:v",
"2",
"-pix_fmt",
"yuvj444p",
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.
if kept and phash - kept[-1][2] <= 8:
frame_path.unlink()
continue
kept.append((timestamp, frame_path, phash))
# Too many frames: keep evenly spaced ones up to max_frames.
if len(kept) > max_frames:
keep = sorted({round(i * (len(kept) - 1) / (max_frames - 1)) for i in range(max_frames)})
for i, k in enumerate(kept):
if i not in keep: k[1].unlink()
kept = [kept[i] for i in keep]
keep = sorted(
{round(index * (len(kept) - 1) / (max_frames - 1)) for index in range(max_frames)}
)
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")
srv = llama.start(log=d / "llama.log") # None if already running
# srv is None if llama-server was already running (we do not stop someone else's).
server = llama.start(log=db.logs(name) / "llama.log") # None if already running
rows = []
try:
for i, (t, p, _) in enumerate(kept):
db.tick(name, i, len(kept), f"schermata {i + 1} di {len(kept)} ({int(t) // 60:02d}:{int(t) % 60:02d})")
r = read_shot(p); _augment(r)
r["view"] = _view(p, r.pop("content_box", None))
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True)
for index, (timestamp, frame_path, _) in enumerate(kept):
db.tick(
name,
index,
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:
if srv: srv.terminate()
# Stop only the server this function started.
if server:
server.terminate()
dur = (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [None])[0]
if dur is None: dur = rows[-1]["t"] + 60 if rows else 0
# Duration from DB; fall back to last frame time + 60 s.
duration = (
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
_fix_spelling(rows)
prev = None
for i, r in enumerate(rows):
r["t_end"] = rows[i + 1]["t"] if i + 1 < len(rows) else dur
key = (r["kind"], (r["title"] or "").lower()) if r["title"] else None
r["lead"] = not (key and key == prev)
# lead=False when a row repeats the previous kind+title (continuation of the same topic).
for index, row in enumerate(rows):
row["t_end"] = rows[index + 1]["t"] if index + 1 < len(rows) else duration
key = (row["kind"], (row["title"] or "").lower()) if row["title"] else None
row["lead"] = not (key and key == prev)
prev = key
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
# Persist to file and DB.
(out_dir / "shots.json").write_text(
json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8"
)
db.replace_shots(name, rows)
cnt = collections.Counter()
for r in rows:
e = r["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
(d / "glossary.json").write_text(json.dumps([w for w, _ in cnt.most_common(150)], ensure_ascii=False), encoding="utf-8")
# Glossary: terms appearing in the most frames (3-40 chars), top 150.
term_counts = collections.Counter()
for row in rows:
entities = row["entities"]
for item in {
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()
if c.execute("SELECT count(*) FROM call_events WHERE name=? AND kind='present' AND who_key<>'video'", (name,)).fetchone()[0] == 0:
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
ev = []
for r in rows:
ppl = [n for n in (db.norm_name(x) for x in r["people"]) if " " in n and len(n) > 4]
if ppl: ev.append((r["t"], "present", "video", "", json.dumps([{"key": "video", "who": n} for n in ppl], ensure_ascii=False)))
connection = db.connect()
# Derive events only if the call has no roster presence events yet (avoid duplicates).
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.
connection.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
events = []
# People shown on video tiles -> 'present' events. Names with a space and >4 chars only (skips initials).
for row in rows:
present_names = [
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
for r in rows:
pr = db.norm_name(r["presenter"]) if r["presenter"] else None
if pr != last:
if last: ev.append((r["t"], "share_stop", "video", last, ""))
if pr: ev.append((r["t"], "share_start", "video", pr, ""))
last = pr
if last: ev.append((dur, "share_stop", "video", last, ""))
db.add_events(name, ev)
# Presenter changes -> share_start / share_stop pairs.
for row in rows:
presenter_key = db.norm_name(row["presenter"]) if row["presenter"] else None
if presenter_key != last:
if last:
events.append((row["t"], "share_stop", "video", last, ""))
if presenter_key:
events.append((row["t"], "share_start", "video", presenter_key, ""))
last = presenter_key
if last:
events.append((duration, "share_stop", "video", last, ""))
db.add_events(name, events)
if __name__ == "__main__":
# Self-check: a one-letter OCR misread loses to the spelling seen on more frames, unrelated identifiers survive.
shots = [
{"title": "scp-infra-iac", "summary": "", "text": "", "entities": {"systems": ["scp-env-dev"]}},
{"title": "scp-infra-iac", "summary": "pipeline scp-env-dev", "text": "", "entities": {}},
{"title": "scp-infra-iac", "summary": "", "text": "stage1-deploy", "entities": {}},
{"title": "sap-infra-iac", "summary": "", "text": "stage2-deploy", "entities": {"systems": ["sep-env-dev"]}},
]
_fix_spelling(shots)
assert shots[3]["title"] == "scp-infra-iac", shots[3]
assert shots[3]["entities"]["systems"] == ["scp-env-dev"], shots[3]
assert shots[2]["text"] == "stage1-deploy" and shots[3]["text"] == "stage2-deploy" # digits never voted away
print("ok")
+168 -22
View File
@@ -1,28 +1,174 @@
"""Map diarization labels to names seen in Teams call events."""
import difflib
import json
import re
import unicodedata
import db
# Map each diarized 'Speaker N' label to a person from Teams events; unmatched labels get an empty name.
def run(name):
p = db.out_dir(name) / "diar_segments.json"
ev = db.events(name, "active", "caption")
if not p.exists() or not ev: return
segs = json.loads(p.read_text(encoding="utf-8"))
iv = []
for e in ev:
if not e["who"]: continue
a, b = (e["t"], e["t"] + 0.5) if e["kind"] == "active" else (e["t"] - 2, e["t"] + 2)
iv.append((a, b, e["who"]))
tot = {}
for s in segs:
d = tot.setdefault(s["label"], {})
for a, b, who in iv:
o = min(b, s["end"]) - max(a, s["start"])
if o > 0: d[who] = d.get(who, 0) + o
for label in {s["label"] for s in segs}:
d = tot.get(label, {})
if not d:
db.set_speaker_map(name, label, "", "auto", 0); continue
person = max(d, key=d.get); ov = d[person]
ok = ov >= 5 and ov / sum(d.values()) >= 0.4
db.set_speaker_map(name, label, person if ok else "", "auto", ov)
diar_path = db.out_dir(name) / "diar_segments.json"
events = db.events(name, "active", "caption")
if not diar_path.exists() or not events:
return
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.
for event in events:
if not event["who"]:
continue
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).
totals = {}
for segment in segments:
label_totals = totals.setdefault(segment["label"], {})
for start, end, who in intervals:
overlap = min(end, segment["end"]) - max(start, segment["start"])
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
pairs = sorted(
(
(overlap, label, who)
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.
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='').
for label in {segment["label"] for segment in segments}:
who, overlap = assigned.get(label, ("", sum(totals.get(label, {}).values())))
# Store the mapping (source 'auto', with overlap seconds).
db.set_speaker_map(name, label, who, "auto", overlap)
_caption_split(name, [event for event in events if event["kind"] == "caption" and event["who"]])
# Lowercase, accent-free, punctuation-stripped word for caption/transcript alignment.
def _norm(word):
return (
unicodedata.normalize("NFKD", word).encode("ascii", "ignore").decode().lower().strip(".,;:?!'\"()«»")
)
def _caption_split(name, captions):
"""Diarization clusters merge similar voices (a whole speaker vanished into another label), and a paragraph gets one label.
Teams captions carry the real speaker: align each paragraph's words with nearby caption words and split at speaker changes."""
if not captions:
return
names = db.speaker_names(name)
label_by_person = {person: label for label, person in names.items()}
labels = [row[0] for row in db.connect().execute("SELECT label FROM speaker_map WHERE name=?", (name,))]
next_number = max([int(n) for label in labels for n in re.findall(r"\d+", label)] + [0]) + 1
def label_of(person):
nonlocal next_number
if person not in label_by_person:
# Captioned person with no diarization cluster: give them their own label.
label_by_person[person] = f"Speaker {next_number}"
db.set_speaker_map(name, label_by_person[person], person, "auto", 0)
next_number += 1
return label_by_person[person]
lines = [
(int(stamp), speaker, text)
for stamp, speaker, text in db.connect().execute(
"SELECT t, speaker, text FROM lines WHERE name=? ORDER BY CAST(t AS INTEGER)", (name,)
)
]
out = _split_lines(
lines, [(caption["t"], caption["who"], caption["text"]) for caption in captions], label_of
)
db.replace_lines(name, out)
print("speakers: speaker split", len(lines), "->", len(out), "paragraphs", flush=True)
# Split speaker-labelled paragraphs where the captions change speaker; label_of(person) -> "Speaker N".
def _split_lines(lines, captions, label_of):
out = []
for index, (start, label, text) in enumerate(lines):
end = lines[index + 1][0] if index + 1 < len(lines) else start + 60
words = text.split()
# Caption t is when the caption settles (end of the utterance), so look up to 20 s past the paragraph.
window = [
(_norm(word), who)
for stamp, who, caption_text in captions
if start - 2 <= stamp <= end + 20
for word in caption_text.split()
]
who = [None] * len(words)
matcher = difflib.SequenceMatcher(
None, [_norm(word) for word in words], [word for word, _ in window], autojunk=False
)
for word_index, window_index, size in matcher.get_matching_blocks():
if size >= 2: # single-word matches ("ok", "sì") are noise
for offset in range(size):
who[word_index + offset] = window[window_index + offset][1]
# 'active speaker' events were tried here as a fallback without captions: 0.5 s points plus interpolated word
# times split mid-sentence and moved whole turns to the wrong person, so paragraphs without captions stay as diarized.
# Unmatched words take the previous matched speaker, leading ones the next.
for order in (range(len(words)), reversed(range(len(words)))):
last = None
for word_index in order:
last = who[word_index] = who[word_index] or last
runs = []
for word_index, word in enumerate(words):
run_label = label_of(who[word_index]) if who[word_index] else label
if runs and runs[-1][1] == run_label:
runs[-1][2].append(word)
else:
runs.append([word_index, run_label, [word]])
# Runs under 4 words are alignment noise: fold them into the run before (or after, at the start).
merged = []
for run in runs:
if merged and (len(run[2]) < 4 or merged[-1][1] == run[1]):
merged[-1][2] += run[2]
else:
merged.append(run)
if len(merged) > 1 and len(merged[0][2]) < 4:
merged[1][2][:0], merged[1][0] = merged[0][2], 0
merged.pop(0)
for word_index, run_label, run_words in merged:
stamp = start + (end - start) * word_index // len(words) # ponytail: time interpolated by word position
# Same speaker continues: one paragraph, cut every 60 s like diarize.
if out and out[-1][1] == run_label and stamp - out[-1][0] < 60:
out[-1][2] += " " + " ".join(run_words)
else:
out.append([stamp, run_label, " ".join(run_words)])
return [tuple(row) for row in out]
if __name__ == "__main__":
# Self-check: one diarized paragraph holding two speakers is split where the captions change speaker.
rows = _split_lines(
[
(
100,
"Speaker 1",
"come next step possiamo iniziare a deployare questi pezzetti nel momento in cui fate il deploy coinvolgete anche Mattia",
)
],
[
(104, "Adriano", "Come next step possiamo iniziare a deployare questi pezzetti."),
(118, "Edoardo", "Nel momento in cui fate il deploy coinvolgete anche Mattia."),
],
lambda person: {"Adriano": "Speaker 4", "Edoardo": "Speaker 8"}[person],
)
assert [row[1] for row in rows] == ["Speaker 4", "Speaker 8"], rows
assert rows[0][2].endswith("pezzetti") and rows[1][2].startswith("nel momento"), rows
print("ok")
+147 -52
View File
@@ -1,95 +1,190 @@
"""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
import numpy as np
import db
import numpy as np
HERE = Path(__file__).parent
# Pre-converted OpenVINO Whisper model; downloaded on first NPU use.
NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
def _log(msg):
# Log via Prefect when inside a flow; print otherwise.
def _log(message):
try:
from prefect import get_run_logger
get_run_logger().info(msg)
get_run_logger().info(message)
except Exception:
print(msg, flush=True)
print(message, flush=True)
def aggregate(segs):
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run."""
lines, buf, start, end = [], [], 0, 0
"""(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, pending, start, end, previous_text, repeat_count = [], [], 0, 0, None, 0
def flush():
if buf:
lines.append((int(start), " ".join(buf))); buf.clear()
for s, e, t in segs:
t = t.strip()
if not t: continue
if buf and s - end > 1: flush()
if not buf: start = s
buf.append(t); end = e
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
if pending:
lines.append((int(start), " ".join(pending)))
pending.clear()
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.
repeat_count = repeat_count + 1 if text == previous_text else 0
previous_text = text
if repeat_count >= 2:
continue
# A pause over 1 s starts a new line.
if pending and seg_start - end > 1:
flush()
if not pending:
start = seg_start
pending.append(text)
end = seg_end
# End the line at sentence punctuation, or after 12 s.
if text.endswith((".", "?", "!", "…")) or end - start > 12:
flush()
flush()
return lines
# Decode to 16 kHz mono float32 PCM via ffmpeg; the format whisper and the NPU pipeline expect.
def _decode(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
return np.frombuffer(raw, np.float32)
pcm_bytes = subprocess.run(
[
"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.
def _cuda(audio, model, glossary, tick=lambda done, total: None):
import common
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)
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:
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
out = []
for s in segs: out.append((s.start, s.end, s.text)); tick(s.end, info.duration)
return out, dev
# Italian forced; VAD (voice activity detection) skips silence.
segments, info = whisper_model.transcribe(
str(audio), language="it", vad_filter=True, **kwargs
)
collected = []
# Keep each segment, reporting progress by its end time.
for segment in segments:
collected.append((segment.start, segment.end, segment.text))
tick(segment.end, info.duration)
return collected, used_device
finally:
del m; gc.collect()
# Free the model (VRAM) before returning, even on error.
del whisper_model
gc.collect()
# OpenVINO GenAI Whisper on the Intel NPU. Failure raises 'NPU failed' so flow.py can fall back to CUDA.
def _npu(audio):
try:
import openvino_genai as ov
import openvino_genai
# First run: download the pre-converted model; if that fails, export it locally with optimum (slow).
if not NPU_MODEL_DIR.exists():
from huggingface_hub import snapshot_download
try:
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:
subprocess.run(["optimum-cli", "export", "openvino", "--model", "openai/whisper-large-v3-turbo",
"--weight-format", "fp16", str(NPU_MODEL_DIR)], check=True)
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True)
if not res.chunks: raise RuntimeError("no chunks returned")
return [(c.start_ts, c.end_ts, c.text) for c in res.chunks]
except Exception as e:
raise RuntimeError(f"NPU failed: {e!r}")
subprocess.run(
[
"optimum-cli",
"export",
"openvino",
"--model",
"openai/whisper-large-v3-turbo",
"--weight-format",
"fp16",
str(NPU_MODEL_DIR),
],
check=True,
)
# Load the pipeline on the NPU device.
pipe = openvino_genai.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
result = pipe.generate(
_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True
)
# Empty output counts as failure.
if not result.chunks:
raise RuntimeError("no chunks returned")
return [(chunk.start_ts, chunk.end_ts, chunk.text) for chunk in result.chunks]
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.
def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path | None = None):
audio = db.out_dir(name) / "audio.opus"
gl = db.out_dir(name) / "glossary.json"
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
t0 = time.time()
glossary_path = db.out_dir(name) / "glossary.json"
# Glossary from shots (used as whisper hotwords).
glossary = (
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.
if device == "npu":
db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)")
segs, used = _npu(audio), "npu"
segments, used_device = _npu(audio), "npu"
else:
tick = lambda done, total: db.tick(name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio")
segs, used = _cuda(audio, model, glossary, tick)
lines = aggregate(segs)
txt = "\n".join(f"[{t//60:02d}:{t%60:02d}] {x}" for t, x in lines)
for l in txt.splitlines(): _log(l)
secs = time.time() - t0
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.
lines = aggregate(segments)
# Format as [mm:ss] text, the format diarize.py parses.
transcript_text = "\n".join(
f"[{time_s // 60:02d}:{time_s % 60:02d}] {text}" for time_s, text in lines
)
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.
if out_path is not None:
out_path.write_text(txt, encoding="utf-8")
return secs
(db.OUT / f"{name}.txt").write_text(txt, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs)
return secs
out_path.write_text(transcript_text, encoding="utf-8")
return elapsed_s
# Normal mode: persist transcript file and DB rows, and record which device was used.
(db.out_dir(name) / "transcript.txt").write_text(transcript_text, encoding="utf-8")
db.replace_lines(name, [(time_s, None, text) for time_s, text in lines])
db.upsert_recording(name, transcribe_device=used_device, transcribe_s=elapsed_s)
return elapsed_s
+53
View File
@@ -0,0 +1,53 @@
<!doctype html><meta charset=utf-8><title>Meetings</title>
<!-- Local Web UI for recorded Teams meetings; ui.js renders and drives everything. -->
<link rel=stylesheet href=/ui.css>
<!-- Header: title, omp login status (omps) and queue summary (qs), both filled by tick() in ui.js. -->
<main><header><div><h1>Riunioni</h1><div class=hs><span id=omps title="login: menu Pinokio → Cloud login"></span><span id=qs></span></div></div>
<!-- Header actions: settings popover and upload. -->
<div class=ha>
<!-- Settings popover: skip-screenshots switch and LLM model pickers (wired by setSkip / setLlm in ui.js). -->
<details class=cfg><summary title="impostazioni di elaborazione">⚙ Impostazioni</summary><div class=pop>
<label class=sw title="non legge le schermate condivise: elaborazione molto più veloce, report solo dal parlato"><input type=checkbox id=skp onchange=setSkip()><i></i><span><b>Salta schermate</b><small>più veloce, report solo dal parlato</small></span></label>
<label class=fl>Modello schermate<select id=llm title="modello per le schermate (shots)" onchange=setLlm()></select></label>
<label class=fl>Modello report<select id=llmr title="modello per il report" onchange=setLlm()></select></label></div></details>
<!-- Upload button; the hidden file input below does the picking. -->
<button class=pri onclick=pick() title="mp4, mkv, mov, webm, wav, m4a, mp3">⬆ Carica video</button>
<!-- Hidden file input used by pick(). -->
<input type=file id=up accept="video/*,audio/*,.mkv" hidden></div></header>
<!-- Drag-and-drop hint; ui.js also accepts drops anywhere on the page. -->
<div id=hint>Trascina qui un video o un audio di una riunione per elaborarlo.</div>
<!-- Upload progress card (send() in ui.js). -->
<div class="card" id=ub hidden><div class=pg style="margin:0;border:0;padding:0;background:none"><div class=pgh><span><span class=big id=ubig>0%</span> &nbsp;<b id=utitle></b></span><button id=ucancel>annulla</button></div>
<div class=bar><i id=ubar></i></div><div class=sub><span id=utxt></span></div></div></div>
<!-- Search over speech and screen text, plus Q&A over the meetings. -->
<div class=card><div class=row><input id=q placeholder="Cerca nel parlato e sullo schermo"><button onclick=srch()>Cerca</button></div>
<div id=sr></div><div class=row><input id=qa placeholder="Chiedi alle riunioni"><select id=llma title="modello per le risposte (stesso del report)" onchange="llmr.value=llma.value;setLlm()"></select><button class=pri id=ab onclick=ask()>Chiedi</button></div><div id=ar></div></div>
<!-- Bulk-action bar, shown only when recordings are checked (upd() in ui.js). -->
<div class=card id=bulk hidden><b id=bn></b><a onclick=selAll(1)>tutte</a><a onclick=selAll(0)>nessuna</a><span class=sep></span>
<button onclick=mergeSel() title="unisce in un solo video le registrazioni spuntate (stessa chiamata riavviata)">Unisci</button>
<select id=bf title="step da cui rielaborare"><option>audio<option>transcribe<option>diarize<option>speakers<option>shots<option>docs<option>report<option>memory<option>render</select><button onclick=bulkRun() title="rielabora le registrazioni spuntate dallo step scelto">Rielabora da qui</button>
<button class=del onclick=bulkDrop() title="elimina solo i file video, report e trascrizione restano">Elimina video</button>
<button class=del onclick=bulkDel()>Elimina tutto</button></div>
<!-- Meetings table: rendered by tick() in ui.js. -->
<div class="card t"><table id=t></table></div><div id=pgr class=row style="justify-content:center"></div></main>
<!-- Preview and crop dialog (play() in ui.js). -->
<dialog id=cdlg><div class=pgh><b id=ctitle></b><button onclick=cclose()>✕ chiudi</button></div>
<video id=cv controls preload=metadata></video>
<!-- Crop controls: start and end time as mm:ss or h:mm:ss. -->
<div class=row style="margin-top:10px"><button onclick="cs.value=fmt(cv.currentTime)">⇤ inizio = qui</button><input class=tm id=cs value="00:00">
<input class=tm id=ce><button onclick="ce.value=fmt(cv.currentTime)">fine = qui ⇥</button>
<button onclick=cplay()>▶ anteprima ritaglio</button><button class=pri id=cgo_ onclick="cgo(0)">✂ Ritaglia e salva come nuova riunione</button><button id=cgi_ onclick="cgo(1)">✂ Ritaglia e salva in questa riunione</button></div>
<!-- Progress bar for the crop re-encode (polled from /crop_progress). -->
<progress id=cpr max=100 value=0 hidden style="width:100%"></progress>
<div id=cmsg>L'originale resta intatto: il ritaglio diventa una nuova riunione (mm:ss o h:mm:ss).</div></dialog>
<!-- Per-recording actions modal (more() in ui.js). -->
<dialog id=mdlg style="width:min(320px,94vw)"><div id=mbody style="display:flex;flex-direction:column;gap:10px"></div></dialog>
<!-- Title edit dialog (setTitle() in ui.js). -->
<dialog id=tdlg style="width:min(420px,94vw)"><b>Titolo della riunione</b><input id=tin placeholder="vuoto = titolo automatico" style="width:100%;margin-top:12px" onkeydown="if(event.key==='Enter')saveTitle()">
<div class=sa><button class=pri onclick=saveTitle()>✓ Salva titolo</button><button onclick=tdlg.close()>✕ Chiudi</button></div></dialog>
<!-- Reprocess dialog (reprocess() in ui.js). -->
<dialog id=rdlg style="width:min(380px,94vw)"><b>Riprocessa riunione</b><div class=row style="margin-top:12px;align-items:center">Inizia da: <select id=rstep></select></div>
<textarea id=rprompt rows=4 style="width:100%;margin-top:10px" placeholder="Raffina il report (opzionale), es. «più dettaglio sulle decisioni». Ha effetto se si riparte da report o prima. Vuoto = nessuna istruzione."></textarea>
<div class=sa><button class=pri onclick=run()>▶ Inizia</button><button onclick=rdlg.close()>✕ Chiudi</button></div></dialog>
<!-- Web UI logic. -->
<script src=/ui.js></script>
+107
View File
@@ -0,0 +1,107 @@
/* Theme colours as CSS variables; light theme by default. */
:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442;--acc2:#b05535;--on:#fff;
--red:#f6e0dc;--redf:#a33a2a;--amb:#f7ecd6;--ambf:#8a5a12;--grn:#e2eedf;--grnf:#3d6b35;--gry:#ebe9e1;--gryf:#5e5d57}
/* Dark theme overrides, applied when the OS prefers dark. */
@media (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757;--acc2:#e58a6c;--on:#1f1e1d;
--red:#4a2b26;--redf:#f0a597;--amb:#4a3d24;--ambf:#ecc77f;--grn:#2d3f2a;--grnf:#a8d39c;--gry:#3a3a35;--gryf:#c2c0b6}}
/* Base reset and body typography. */
*{box-sizing:border-box}body{font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;margin:0;padding:32px 24px 64px;background:var(--bg);color:var(--fg)}
/* Centred page column; header wraps on narrow windows. */
main{max-width:1200px;margin:auto}header{display:flex;align-items:end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px}
/* Serif page heading. */
h1{font:500 30px/1.2 ui-serif,Georgia,"Times New Roman",serif;letter-spacing:-.01em;margin:0}
/* Card container for each section. */
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:16px}
/* Flex rows for toolbars and search; inputs grow to fill. */
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.row+.row{margin-top:10px}.row input{flex:1;min-width:220px}
/* Shared form-control look. */
input,select,button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:6px 10px}
/* Accent focus ring. */
input:focus,select:focus{outline:2px solid var(--acc);outline-offset:-1px}
/* Default buttons; primary buttons (.pri) use the accent colour. */
button{cursor:pointer;background:var(--soft)}button:hover{border-color:var(--mut)}button:disabled{opacity:.5;cursor:default}
button.pri{background:var(--acc);border-color:var(--acc);color:var(--on)}button.pri:hover{background:var(--acc2)}
/* Search and Q&A result containers. */
#sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px}
/* Rendered markdown answer: tight spacing; sources are collapsed in <details>. */
.md p,.md ul,.md h4{margin:4px 0}.md ul{padding-left:20px}.md code{background:var(--bg);padding:0 4px;border-radius:4px}#ar details{margin-top:6px}#ar summary{cursor:pointer}#ar details>div{padding:2px 0}
/* Meetings table: full width, rows separated by lines. */
table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:middle}tbody.rec:last-child tr:last-child td{border-bottom:0}
/* Alternate background per recording group (tbody.rec); accent bar marks the main row. */
tbody.rec:nth-of-type(even) td{background:color-mix(in srgb,var(--acc) 7%,transparent)}tbody.rec tr.main td:first-child{box-shadow:inset 3px 0 var(--acc)}tbody.rec tr:last-child td{border-bottom:2px solid var(--line)}
/* Table headers. */
th{font-size:12px;font-weight:600;color:var(--mut);text-transform:uppercase;letter-spacing:.05em}.card.t{padding:4px 8px;overflow-x:auto}
/* Status badge pill. */
.b{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:500;background:var(--gry);color:var(--gryf)}
/* Status colours: red = recording/error/cancelled, amber = in progress, green = done. */
.recording,.error,.cancelled{background:var(--red);color:var(--redf)}.audio,.transcribing,.diarizing,.identifying,.shots,.docs,.report,.memory{background:var(--amb);color:var(--ambf)}.done{background:var(--grn);color:var(--grnf)}
/* Links, muted small text, speaker-panel row background. */
a{color:var(--acc);cursor:pointer;margin-right:10px;text-decoration:none}a:hover{text-decoration:underline}small{color:var(--mut)}.sp td{background:var(--soft)}.sp div{margin-bottom:8px}
/* Speaker-panel footer buttons. */
.sp .sa,#tdlg .sa,#rdlg .sa{display:flex;gap:8px;justify-content:flex-end;margin-top:12px;padding-top:12px;border-top:1px solid var(--line)}.sp .sa button,#tdlg .sa button,#rdlg .sa button{padding:7px 16px;font-weight:500}.sp td{padding:14px 16px}
/* Spacing for table action buttons; muted queue counter. */
td button,td select{margin:0 4px 4px 0}#qs{color:var(--mut)}.acts{display:flex;gap:8px;flex-wrap:nowrap;white-space:nowrap;align-items:center;justify-content:flex-end}.acts button,.acts a.btn{margin:0;padding:6px 12px;line-height:1.3}thead th:last-child{text-align:right}
a.btn{border:1px solid var(--line);border-radius:9px;background:var(--soft);color:var(--fg)}a.btn:hover{border-color:var(--mut);text-decoration:none}a.btn.pri{background:var(--acc);border-color:var(--acc);color:var(--on);font-weight:500}a.btn.pri:hover{background:var(--acc2)}
a.btn:not([href]){opacity:.5;cursor:default;pointer-events:none}
#mbody a.btn{text-align:center;padding:6px 10px}#mbody{text-align:center}#mbody .row{justify-content:center}
.ttl.act{cursor:pointer}.spin{display:inline-block;width:12px;height:12px;margin-left:8px;border:2px solid var(--line);border-top-color:var(--acc);border-radius:50%;animation:rot .8s linear infinite;vertical-align:middle}@keyframes rot{to{transform:rotate(360deg)}}
/* Progress panel (.pg) shown while a pipeline runs. */
.pg{padding:14px 16px 12px;background:var(--soft);border:1px solid var(--line);border-radius:12px;margin:0 0 8px}
/* Progress panel header row. */
.pgh{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap;margin-bottom:8px}.pgh b{font-size:15px}.pgh .n{color:var(--mut)}
/* Large percentage figure and ETA text. */
.big{font:600 22px/1 ui-serif,Georgia,serif;letter-spacing:-.01em}.eta{color:var(--mut);font-size:13px}.eta b{color:var(--fg);font-size:13px}
/* Progress bar track; .thin is the per-step bar. */
.bar{height:12px;background:var(--line);border-radius:99px;overflow:hidden}.bar.thin{height:6px;margin-top:10px}
/* Bar fill: animated diagonal stripes (moved by the mv keyframes). */
.bar>i{display:block;height:100%;width:0;border-radius:99px;transition:width .9s ease;background-color:var(--acc);
background-image:linear-gradient(45deg,rgba(255,255,255,.2) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.2) 50%,rgba(255,255,255,.2) 75%,transparent 75%),linear-gradient(90deg,var(--acc),var(--acc2));
background-size:24px 24px,100% 100%;animation:mv 1s linear infinite}
@keyframes mv{to{background-position:24px 0,0 0}}
/* Indeterminate bar: sliding 30% segment (used while progress is unknown). */
.bar.ind>i{width:30%!important;animation:mv 1s linear infinite,ind 1.6s ease-in-out infinite}@keyframes ind{0%{margin-left:-30%}100%{margin-left:100%}}
/* Step chips row. */
.steps{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
/* Step chip base. */
.st{font-size:12px;padding:3px 10px;border-radius:99px;background:var(--card);border:1px solid var(--line);color:var(--mut);white-space:nowrap}
/* Step chip states: ok, running (pulsing), skipped (struck through). */
.st.ok{background:var(--grn);color:var(--grnf);border-color:transparent}.st.run{background:var(--acc);color:var(--on);border-color:transparent;animation:pulse 1.8s ease-in-out infinite}.st.skip{opacity:.4;text-decoration:line-through}
@keyframes pulse{50%{opacity:.72}}
/* Caption line under the progress bar. */
.sub{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:6px;font-size:12.5px;color:var(--mut)}
/* Live activity line with pulsing dot. */
.live{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:13px;color:var(--mut)}.dot{flex:none;width:9px;height:9px;border-radius:50%;background:var(--grnf);animation:pulse 1s ease-in-out infinite}
/* Live activity severity: warn = amber, bad = red with a static dot. */
.live.warn,.live.warn b{color:var(--ambf)}.live.warn .dot{background:var(--ambf)}.live.bad,.live.bad b{color:var(--redf)}.live.bad .dot{background:var(--redf);animation:none}
/* Upload card stays visible while scrolling. */
#ub{position:sticky;top:12px;z-index:5}#ub .pgh{margin-bottom:10px}
/* Dashed outline while a file is dragged over the page. */
body.drag main{outline:3px dashed var(--acc);outline-offset:8px;border-radius:14px}
/* Hint text. */
#hint{color:var(--mut);font-size:12.5px}
/* Destructive buttons. */
button.del{color:var(--redf)}button.del:hover{background:var(--red);border-color:var(--redf)}
/* Preview/crop dialog. */
dialog{border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--fg);padding:16px;width:min(960px,94vw)}dialog::backdrop{background:rgba(0,0,0,.5)}
/* Video inside the dialog. */
dialog video{width:100%;max-height:68vh;background:#000;border-radius:8px}dialog input.tm{width:90px}#cmsg{color:var(--mut);font-size:13px}
/* Header layout; separator line under it; the subtitle line hides when empty. */
header{align-items:center;padding-bottom:16px;border-bottom:1px solid var(--line)}.hs{display:flex;gap:12px;flex-wrap:wrap;margin-top:4px;font-size:12.5px;color:var(--mut)}.hs:empty{display:none}
/* Header action group. */
.ha{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.ha>button,.cfg summary{padding:8px 14px;font-weight:500}
/* Settings dropdown (details/summary). */
.cfg{position:relative}.cfg summary{list-style:none;cursor:pointer;user-select:none;background:var(--soft);border:1px solid var(--line);border-radius:9px}.cfg summary::-webkit-details-marker{display:none}.cfg summary:hover,.cfg[open] summary{border-color:var(--mut)}
/* Settings popover panel. */
.pop{position:absolute;right:0;top:calc(100% + 8px);z-index:20;width:300px;display:flex;flex-direction:column;gap:14px;padding:16px;background:var(--card);border:1px solid var(--line);border-radius:14px;box-shadow:0 10px 30px rgba(0,0,0,.18)}
/* On/off switch: the checkbox is hidden and the track (i) is styled. */
.sw{display:flex;gap:12px;align-items:center;cursor:pointer}.sw span{display:flex;flex-direction:column}.sw small{font-size:12px}
/* Switch track. */
.sw input{position:absolute;opacity:0;width:0;height:0}.sw i{flex:none;position:relative;width:38px;height:22px;border-radius:99px;background:var(--line);transition:background .15s}
/* Switch knob. */
.sw i::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s}
/* Checked state: knob slides 16 px. */
.sw input:checked+i{background:var(--acc)}.sw input:checked+i::after{transform:translateX(16px)}.sw input:focus-visible+i{outline:2px solid var(--acc);outline-offset:2px}.sw input:disabled+i{opacity:.5}
/* Labelled select in the settings popover. */
.fl{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--mut)}.fl select{width:100%;font-size:14px;color:var(--fg)}
/* Bulk-action bar: sticky at the top while visible. */
#bulk{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 14px;position:sticky;top:12px;z-index:6;box-shadow:0 6px 20px rgba(0,0,0,.12)}#bulk[hidden]{display:none}#bulk a{cursor:pointer}#bulk .sep{flex:1}
+245
View File
@@ -0,0 +1,245 @@
// 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.
// Element ids from index.html used as window globals (plus bare addEventListener), declared for ESLint no-undef.
/* global ab addEventListener ar bf bn bulk cdlg ce cgi_ cgo_ cmsg cpr cs ctitle cv llm llma llmr omps pgr q qa qs skp sr t ub ubar ubig ucancel up utitle utxt */
// Escape text for innerHTML (&, <, >, ").
const E=value=>String(value??"").replace(/[&<>"]/g,char=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[char]));
// Seconds -> mm:ss (minutes can exceed 59; no hour form here).
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.
q.onkeydown=event=>{if(event.key==="Enter")srch()};
// Enter in the Q&A box asks the question.
qa.onkeydown=event=>{if(event.key==="Enter")ask()};
// Close button appended after results: clears the input and the result box.
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.
async function ask(){if(!qa.value)return;ar.innerHTML="<small>…avvio modelli / risposta (può richiedere qualche minuto)</small>";
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;
// 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.
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 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){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 html+(ul?"</ul>":"")};
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.
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(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=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 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()}
// Search over speech and screen text (/search).
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.
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")}
// Reprocess dialog: pick the first step, then start the pipeline from it (/run); 409 means it is already running.
let rname="";
function reprocess(name,mb){rname=name;rstep.innerHTML=["audio","transcribe","diarize","speakers","shots","docs","report","memory","render"].slice(mb?0:5).map(step=>`<option>${step}`).join("");rprompt.value="";rdlg.showModal()}
async function run(){const response=await fetch(`/run?name=${rname}&from=${rstep.value}&refine=${encodeURIComponent(rprompt.value)}`,{method:"POST"});rdlg.close();if(response.status===409)alert("già in esecuzione");tick()}
// Names of the checked recording rows (.mg checkboxes).
const sel_=()=>[...document.querySelectorAll(".mg:checked")].map(x=>x.value);
// Show the bulk bar only when something is checked, and show the selected count.
function upd(){const count=sel_().length;bulk.hidden=!count;bn.textContent=`${count} selezionat${count===1?"a":"e"}`}
// Check or uncheck all recording rows.
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.
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()}
// Re-run the selected recordings from the step chosen in #bf.
function bulkRun(){bulk_("/run?from="+bf.value,sel_(),"rielaborazione")}
// Bulk delete of video files only; report, transcript and screenshots are kept.
function bulkDrop(){const names=sel_();if(confirm(`Eliminare i file video di ${names.length} riunioni?
Report, trascrizione, audio e schermate restano; la rielaborazione salterà i passaggi che richiedono il video. Non si può annullare.`))bulk_("/drop_video",names,"elimina video")}
// Bulk delete of whole recordings; asks for confirmation first.
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",names,"elimina")}
// Merge two or more checked recordings (same meeting restarted) into one.
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.
const open_=new Set();
// Toggle the speakers panel for one recording and re-render.
async function spk(name){editing=false;open_.has(name)?open_.delete(name):open_.add(name);tick()}
// Recordings whose progress panel is expanded (click on the title while processing).
const pgo=new Set();
function togPg(name){pgo.has(name)?pgo.delete(name):pgo.add(name);tick()}
// Speakers panel: diarization label -> person mapping, with a datalist of candidate names.
async function panel(name){const data=await (await fetch("/speakers?name="+name)).json();
return `<tr class=sp><td colspan=7><datalist id="cand-${name}">${data.candidates.map(candidate=>`<option value="${E(candidate)}">`).join("")}</datalist>`+
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('${name}')">✓ Salva nomi</button><button onclick="spk('${name}')">✕ Chiudi</button></div>`}
// Read the label -> person inputs and save them (/speaker_map).
async function saveSpk(name){const labels={};document.querySelectorAll(`input[data-n="${name}"]`).forEach(input=>labels[input.dataset.l]=input.value);
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.
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={};
// Mini modal with the secondary actions of one recording: rerun from step, drop video, delete.
function more(name,mb,label,canDrop,title,canRetitle,blocked){
mbody.innerHTML=`<b>${label}</b><button onclick="who('${name}')">👥 partecipanti</button><button onclick="mclose();spk('${name}')">speakers</button><button onclick="mclose();setTitle('${name}','${title}')">✎ modifica titolo</button>`+(canRetitle?`<button onclick="mclose();retitle('${name}')">↻ ricalcola titolo</button>`:"")+`<button ${blocked?"disabled":""} onclick="mclose();reprocess('${name}',${mb})">↻ riprocessa</button>`+
`<button onclick="mclose();reveal('${name}')">📂 mostra su disco</button>`+
(canDrop&&!blocked?`<button onclick="mclose();dropVid('${name}',${mb})">🎞 elimina video</button>`:"")+
(blocked?"":`<button class=del onclick="mclose();del_('${name}','${label}')">🗑 elimina riunione</button>`)+`<button onclick="mclose()">✕ chiudi</button>`;mdlg.showModal()}
// Ask the server to open the meeting folder in Explorer.
async function reveal(name){const response=await fetch("/reveal?name="+name,{method:"POST"});if(!response.ok)alert(await response.text())}
// Participants: named speakers (unnamed labels shown as-is) with talk time, in the same modal.
async function who(name){const data=await (await fetch("/speakers?name="+name)).json();
mbody.innerHTML=`<b>Partecipanti</b>`+(data.rows.map(row=>`<div>${E(row.person||row.label)} <small>${fmt(row.talk_s)}</small></div>`).join("")||"<div>nessun dato</div>")+`<button onclick="mclose()">✕ chiudi</button>`}
const mclose=()=>mdlg.close();
// Delete one recording after confirmation.
async function del_(name,label){if(!confirm(`Eliminare definitivamente "${label}"?
Vengono cancellati registrazione, trascrizione, schermate e report. Non si può annullare.`))return;
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).
async function dropVid(name,mb){if(!confirm(`Eliminare il file video (${mb} MB)?
Report, trascrizione, audio e schermate restano; la rielaborazione salterà i passaggi che richiedono il video (audio, schermate). Non si può annullare.`))return;
const response=await fetch("/drop_video?name="+name,{method:"POST"});if(!response.ok)alert(await response.text());tick()}
// Title dialog; empty means automatic. The date suffix is stripped from the default text.
let tname="";
function setTitle(name,cur){tname=name;tin.value=cur.replace(/ — \d{4}-\d\d-\d\d.*$/,"");tdlg.showModal();tin.select()}
async function saveTitle(){const response=await fetch("/title?name="+tname,{method:"POST",body:tin.value});tdlg.close();if(!response.ok)alert(await response.text());tick()}
// "mm:ss" or "h:mm:ss" -> seconds.
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).
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.
function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()}
// Esc closes the dialog through the same cleanup.
cdlg.addEventListener("cancel",cclose);
// Play from the start time; pause at the end time when one is set.
function cplay(){cv.currentTime=sec(cs.value);cv.play();const 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.
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.
if(!(start>=0&&end>start)){cmsg.textContent="intervallo non valido";return}
// Replacing the original is irreversible, so confirm first.
if(inplace&&!confirm("Sostituire il video di questa riunione con il ritaglio? L'originale va perso e la riunione viene rielaborata da zero."))return;
if(inplace){cv.pause();cv.removeAttribute("src");cv.load()} // release the file: Windows can't replace a source the browser has open
// Disable both crop buttons while the re-encode runs.
cgo_.disabled=cgi_.disabled=true;cmsg.textContent="ritaglio in corso… (ricodifica, può richiedere minuti)";cpr.value=0;cpr.hidden=false;
// Poll crop progress every 700 ms while the blocking /crop request is pending.
const iv=setInterval(async()=>{try{const 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.
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.
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).
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.
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.
async function setSkip(){await fetch("/skip_shots?v="+(skp.checked?1:0),{method:"POST"});tick()}
// Italian labels for pipeline steps.
const LBL={audio:"Audio",transcribing:"Trascrizione",diarizing:"Riconoscimento voci",identifying:"Assegnazione nomi",shots:"Schermate",docs:"Documentazione",report:"Report",memory:"Memoria"};
// What each step does, shown under the progress bar.
const HOW={audio:"pulizia e normalizzazione dell'audio",transcribing:"Whisper trascrive il parlato",diarizing:"separazione dei partecipanti in base alla voce",identifying:"associazione di ogni voce al nome del partecipante",shots:"il modello di visione legge ogni schermata condivisa",docs:"ricerca su Confluence e Jira",report:"il modello scrive argomenti, decisioni e azioni",memory:"indicizzazione per la ricerca tra riunioni"};
// Seconds -> "N s", "N min" or "H h MM min".
const dur=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.
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.
const LT={};
// LLM activity line: prompt reading vs token writing; idle time sets the severity colour.
function live(name,prog){const info=prog.llm;let txt="",act=false;
// Model is busy: compare token counts with the previous tick.
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.
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>${info.n_prompt_tokens_processed||0}</b> di ${info.n_prompt_tokens} token`;
// Store this sample for the next tick.
LT[key]=[now,decoded]}
// Severity by idle time: under 90 s ok, under 300 s warn, otherwise bad.
const idle=prog.idle,cls=act||idle<90?"":idle<300?"warn":"bad";
// Status text for the idle time.
const tail=act?`ultimo passo completato ${dur(idle)} fa`:idle<90?`attivo · aggiornato ${dur(idle)} fa`:idle<300?`nessun avanzamento da <b>${dur(idle)}</b>: può essere normale (avvio modello, passo lungo)`:`nessuna attività da <b>${dur(idle)}</b>: possibile blocco, controlla il log Prefect o premi stop`;
return `<div class="live ${cls}"><span class=dot></span><span>${txt?txt+" — ":""}${tail}</span></div>`}
// Progress panel for a recording: boot, queued, or running pipeline.
function progPanel(row){const prog=row.prog,stop=`<span class=acts>${row.flow_run_id?`<a class=btn href="http://127.0.0.1:4200/runs/flow-run/${row.flow_run_id}" target=_blank>prefect</a>`:""}<button class=del onclick="stopRun('${row.name}')">■ stop</button></span>`;
// Pipeline starting: the Python environment can take minutes on the first run.
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>${stop}</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.
if(!prog)return row.status==="queued"?`<tr><td colspan=7><div class=pg><div class=pgh><b>In coda</b><span><span class=eta>parte appena finisce l'elaborazione in corso</span> ${stop}</span></div><div class="bar ind"><i></i></div></div>`:"";
// Overall percent (null if unknown) and the running step.
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.
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.
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.
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(prog.note||HOW[prog.step]||"")}</span></span>
<span><span class=eta>${prog.eta!=null?`fine prevista <b>~${clock(prog.eta)}</b> · mancano <b>${dur(prog.eta)}</b> · `:""}trascorso ${dur(prog.elapsed)}</span> ${stop}</span></div>
<div class="bar${pct==null?" ind":""}"><i style="width:${pct||0}%"></i></div>
<div class=steps>${chips}</div>
<div class="bar thin"><i style="width:${Math.round(prog.frac*100)}%"></i></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(row.name,prog)}</div>`}
function pick(){up.click()}
// Upload with XHR so we get upload progress events. Target: POST /upload?filename=.
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.
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=(fraction*100).toFixed(1)+"%";ubig.textContent=Math.floor(fraction*100)+"%";
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.
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.
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: "+xhr.responseText}tick()};
// Network error.
xhr.onerror=()=>{ubig.textContent="!";utxt.textContent="Errore di rete durante il caricamento"};
// Cancel: abort the request and hide the card.
ucancel.onclick=()=>{xhr.abort();ub.hidden=true};
// File is sent as the raw request body.
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.
up.onchange=()=>{if(up.files[0])send(up.files[0]);up.value=""};
// Dragging over the page: highlight the drop zone.
addEventListener("dragover",event=>{event.preventDefault();document.body.classList.add("drag")});
// Leaving the window (no relatedTarget) clears the highlight.
addEventListener("dragleave",event=>{if(!event.relatedTarget)document.body.classList.remove("drag")});
// Drop anywhere on the page: upload the first file.
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.
const PS=100;let pg_=0;
function goPg(delta){pg_+=delta;tick()}
// Sort by processing date (updated_at): 0 = default (newest name first), -1 = newest first, 1 = oldest first.
let srt=0;function sortDt(){srt=srt<0?1:-1;pg_=0;tick()}
// SQLite UTC "YYYY-MM-DD HH:MM:SS" shown in local time.
const dt=value=>value?new Date(value.replace(" ","T")+"Z").toLocaleString("it-IT",{dateStyle:"short",timeStyle:"short"}):"";
// Refresh the whole UI from /status: header, LLM pickers, table.
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.
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.
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.
skp.checked=data.skip_shots;skp.disabled=data.busy;
// omp login status: red and showing the error when logged out.
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.
qs.textContent=data.queue?`rielaborazione: ${data.queue} da completare`:"";
// Remember step-select values so they survive the re-render.
document.querySelectorAll("select[id^=f-]").forEach(select=>sel[select.id]=select.value);
// Table header.
let html=`<thead><tr><th>riunione<th>stato<th style="cursor:pointer;user-select:none;white-space:nowrap" onclick=sortDt() title="ordina per data di elaborazione">elaborazione ${srt<0?"▼":srt>0?"▲":"↕"}<th>durata<th>speaker<th>dimensione<th>azioni</tr></thead>`;
// Apply the date sort before paging (ISO strings sort lexicographically).
const recs=srt?[...data.recs].sort((a,b)=>srt*(a.updated_at||"").localeCompare(b.updated_at||"")):data.recs;
// Pagination: PS meetings per page; clamp the page if recordings were removed, then draw the pager.
const pages=Math.max(1,Math.ceil(data.recs.length/PS));if(pg_>=pages)pg_=pages-1;
pgr.innerHTML=pages>1?`<button ${pg_?"":"disabled"} onclick="goPg(-1)">‹</button><span>pagina ${pg_+1} di ${pages} (${data.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.
for(const row of recs.slice(pg_*PS,(pg_+1)*PS)){
// Display title, falling back to the upload name.
const nm=row.title||row.upload,act=!!(row.prog||row.running||row.status==="queued");
// Main row: checkbox, title and rename buttons; status badge with error text and time since last data.
html+=`<tbody class=rec><tr class=main><td><input type=checkbox class=mg value="${row.name}"><span class="ttl${act?" act":""}"${act?` onclick="togPg('${row.name}')" title="mostra/nascondi avanzamento"`:""}>${nm?`<b>${E(nm)}</b>${act?"<span class=spin></span>":""}<br><small>${row.name}</small>`:row.name+(act?"<span class=spin></span>":"")}</span><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>${dt(row.updated_at)}<td>${row.duration_s?fmt(row.duration_s):""}<td>${row.speakers??""}<td>${row.mb?row.mb+" MB":""}
<td><div class=acts><a class="btn pri"${row.files.includes("report.html")?` href="/report?name=${row.name}" target=_blank`:""}>📄 report</a><a class=btn${row.files.includes("report.html")?` href="/pdf?name=${row.name}" target=_blank`:""}>pdf</a><button title="anteprima e ritaglio" ${row.mb?"":"disabled"} onclick="play('${row.name}',${row.duration_s||0},'${E(nm||row.name).replace(/'/g,"")}')">▶ video</button><button title="altre azioni" onclick="more('${row.name}',${row.mb||0},'${E(nm||row.name).replace(/'/g,"")}',${!!(row.mb&&row.status==="done"&&!row.running)},'${E(row.title||row.upload||"").replace(/'/g,"")}',${!!row.files.includes("report.html")},${!!(row.running||row.status==="queued"||row.status==="recording")})">⋯</button></div>`;
html+=pgo.has(row.name)?progPanel(row):"";
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.
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.
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.
tick();setInterval(tick,3000);
+2
View File
@@ -1,5 +1,7 @@
// Pinokio menu "Extension": opens app/ext so the unpacked Chrome extension can be loaded.
module.exports = {
run: [{
// fs.open opens the folder in the file manager.
method: "fs.open",
params: {
path: "app/ext"
+153 -42
View File
@@ -1,77 +1,167 @@
// Install step list (Pinokio "Install"): detects GPU/CUDA, asks which on-prem models to download, fetches llama.cpp, diarization, embedding and VLM models, and sets up omp. Requires the "ai" bundle.
const { execFileSync } = require("child_process")
module.exports = {
requires: {
bundle: "ai"
},
run: [
// Print the detected hardware (template variables).
{
method: "log",
params: {
raw: "Hardware: {{gpu_model}} · {{vram}} GB VRAM · {{ram}} GB RAM"
}
},
// floor: NVIDIA with 4 GB VRAM (llama.cpp CUDA build + whisper on GPU)
{
when: "{{gpu !== 'nvidia' || vram < 4}}",
method: "notify",
// 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)
method: async (req, ondata, kernel) => {
let versionMatch = null, computeCap = 0
try { versionMatch = execFileSync("nvidia-smi", { encoding: "utf8" }).match(/CUDA (?:UMD )?Version:\s*(\d+)\.(\d+)/) } catch { /* no NVIDIA driver */ }
// lowest GPU wins
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.
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.
const build = cudaVersion >= 1300 && computeCap >= 7.5 ? "cuda-13.4" : cudaVersion >= 1204 ? "cuda-12.4" : "cpu"
ondata({ raw: `CUDA: ${versionMatch ? versionMatch[1] + "." + versionMatch[2] : "none"}, compute ${computeCap || "?"} -> llama.cpp ${build}\r\n` })
return { build }
}
},
// Save the chosen build for the later download steps.
{ method: "local.set", params: { build: "{{input.build}}" } },
// on-prem LLM choice (35B needs 48+ GB RAM); transcription, diarization and embeddings always stay local
// Full on-prem choice (Qwen 35B) only with a CUDA GPU (>= 4 GB VRAM) and >= 48 GB RAM.
{
when: "{{local.build !== 'cpu' && vram >= 4 && ram >= 48}}",
method: "input",
params: {
html: "Teams Whisper needs an NVIDIA GPU with at least 4 GB VRAM (found: {{gpu_model}}, {{vram}} GB)."
title: "Local LLM",
description: "Transcription, speakers and search always run locally. Cloud models (GitHub Copilot / Anthropic via omp) stay selectable in the Web UI either way.",
form: [{
type: "select", key: "onprem", title: "On-prem models", default: "35b",
items: [
{ text: "Cloud only (no LLM download)", value: "none" },
{ text: "Qwen3.5 4B on-prem (~3.3 GB, all in VRAM)", value: "4b" },
{ text: "Qwen3.5 4B + Qwen3.6 35B on-prem (~26 GB, experts in RAM)", value: "35b" }
]
}]
}
},
next: null
// Save the chosen on-prem option.
{
when: "{{local.build !== 'cpu' && vram >= 4 && ram >= 48}}",
method: "local.set",
params: { onprem: "{{input.onprem}}" }
},
// Less than 48 GB RAM: the 35B option is not offered.
{
when: "{{local.build !== 'cpu' && vram >= 4 && ram < 48}}",
method: "input",
params: {
title: "Local LLM",
description: "Transcription, speakers and search always run locally. Cloud models (GitHub Copilot / Anthropic via omp) stay selectable in the Web UI either way.",
form: [{
type: "select", key: "onprem", title: "On-prem models", default: "4b",
items: [
{ text: "Cloud only (no LLM download)", value: "none" },
{ text: "Qwen3.5 4B on-prem (~3.3 GB, all in VRAM)", value: "4b" }
]
}]
}
},
{
when: "{{local.build !== 'cpu' && vram >= 4 && ram < 48}}",
method: "local.set",
params: { onprem: "{{input.onprem}}" }
},
// No usable GPU: no on-prem model choice; everything else runs on CPU.
{
when: "{{local.build === 'cpu' || vram < 4}}",
method: "log",
params: {
raw: "No CUDA GPU with 4+ GB VRAM: cloud models only; transcription, diarization and embeddings run on CPU."
}
},
// ffmpeg for audio/video handling, and 7-Zip to extract the archives (installed via conda).
{
method: "shell.run",
params: {
message: "conda install -y -c conda-forge ffmpeg 7zip"
}
},
// llama.cpp server (CUDA 13) for the Qwen VLM + bge-m3 embeddings
// evaluated once, before the extract creates llama-server.exe (re-running Install must not re-download ~700 MB)
{ method: "local.set", params: { have: "{{exists('app/bin/llama-server.exe') ? 'yes' : 'no'}}" } },
// llama.cpp server (CUDA 13.4 / 12.4 / CPU build, per detection above) for the Qwen VLM + bge-m3 embeddings
{
method: "fs.download",
when: "{{local.have !== 'yes'}}",
method: "shell.run",
params: {
uri: [
"https://github.com/ggml-org/llama.cpp/releases/download/b11889/llama-b11889-bin-win-cuda-13.4-x64.zip",
"https://github.com/ggml-org/llama.cpp/releases/download/b11889/cudart-llama-bin-win-cuda-13.4-x64.zip"
],
dir: "app/bin"
path: "app",
message: "uv run --script llama.py download https://github.com/ggml-org/llama.cpp/releases/download/b11889/llama-b11889-bin-win-{{local.build}}-x64.zip bin/llama-b11889-bin-win-{{local.build}}-x64.zip"
}
},
// CUDA runtime DLLs (cudart), downloaded separately for CUDA builds only.
{
when: "{{local.build !== 'cpu' && local.have !== 'yes'}}",
method: "shell.run",
params: {
path: "app",
message: "uv run --script llama.py download https://github.com/ggml-org/llama.cpp/releases/download/b11889/cudart-llama-bin-win-{{local.build}}-x64.zip bin/cudart-llama-bin-win-{{local.build}}-x64.zip"
}
},
// Extract the llama.cpp zip into app/bin.
{
when: "{{local.have !== 'yes'}}",
method: "shell.run",
params: {
path: "app/bin",
message: [
"7z x -y llama-b11889-bin-win-cuda-13.4-x64.zip",
"7z x -y cudart-llama-bin-win-cuda-13.4-x64.zip"
]
message: "7z x -y llama-b11889-bin-win-{{local.build}}-x64.zip"
}
},
// Extract the cudart zip into the same folder.
{
when: "{{local.build !== 'cpu' && local.have !== 'yes'}}",
method: "shell.run",
params: {
path: "app/bin",
message: "7z x -y cudart-llama-bin-win-{{local.build}}-x64.zip"
}
},
// Delete the zip archives after extraction, only when they were downloaded in this run.
{
when: "{{local.have !== 'yes'}}",
method: "fs.rm",
params: {
path: "app/bin/llama-b11889-bin-win-{{local.build}}-x64.zip"
}
},
{
when: "{{local.build !== 'cpu' && local.have !== 'yes'}}",
method: "fs.rm",
params: {
path: "app/bin/llama-b11889-bin-win-cuda-13.4-x64.zip"
}
},
{
method: "fs.rm",
params: {
path: "app/bin/cudart-llama-bin-win-cuda-13.4-x64.zip"
path: "app/bin/cudart-llama-bin-win-{{local.build}}-x64.zip"
}
},
// speaker diarization (sherpa-onnx)
// Speaker embedding model (ERes2Net, 3D-Speaker).
{
method: "fs.download",
method: "shell.run",
params: {
uri: "https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx",
path: "app/models/emb.onnx"
path: "app",
message: "uv run --script llama.py download https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx models/emb.onnx"
}
},
// Pyannote segmentation model archive for sherpa-onnx.
{
method: "fs.download",
method: "shell.run",
params: {
uri: "https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/sherpa-onnx-pyannote-segmentation-3-0.tar.bz2",
path: "app/models/seg.tar.bz2"
path: "app",
message: "uv run --script llama.py download https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/sherpa-onnx-pyannote-segmentation-3-0.tar.bz2 models/seg.tar.bz2"
}
},
// Extract the segmentation model into app/models.
{
method: "shell.run",
params: {
@@ -81,30 +171,34 @@ module.exports = {
},
// embeddings for cross-meeting memory
{
method: "hf.download",
method: "shell.run",
params: {
path: "app",
_: ["gpustack/bge-m3-GGUF", "bge-m3-Q8_0.gguf"],
"local-dir": "models"
message: "uv run --script llama.py download https://huggingface.co/gpustack/bge-m3-GGUF/resolve/main/bge-m3-Q8_0.gguf models/bge-m3-Q8_0.gguf"
}
},
// small VLM (Qwen3.5 4B, ~3.3 GB), all layers in 4 GB VRAM: always installed, enough for 32 GB RAM machines
// small VLM (Qwen3.5 4B, ~3.3 GB), all layers in 4 GB VRAM: chosen at install
{
method: "hf.download",
when: "{{local.onprem === '4b' || local.onprem === '35b'}}",
method: "shell.run",
params: {
path: "app",
_: ["unsloth/Qwen3.5-4B-GGUF", "mmproj-BF16.gguf", "Qwen3.5-4B-Q4_K_S.gguf"],
"local-dir": "models/qwen3.5-4b"
message: [
"uv run --script llama.py download https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/mmproj-BF16.gguf models/qwen3.5-4b/mmproj-BF16.gguf",
"uv run --script llama.py download https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q4_K_S.gguf models/qwen3.5-4b/Qwen3.5-4B-Q4_K_S.gguf"
]
}
},
// big MoE LLM + vision projector (~23 GB, experts in RAM): only with 48+ GB RAM
// big MoE LLM + vision projector (~23 GB, experts in RAM): only when chosen at install
{
when: "{{ram >= 48}}",
method: "hf.download",
when: "{{local.onprem === '35b'}}",
method: "shell.run",
params: {
path: "app",
_: ["unsloth/Qwen3.6-35B-A3B-GGUF", "mmproj-BF16.gguf", "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"],
"local-dir": "models"
message: [
"uv run --script llama.py download https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF/resolve/main/mmproj-BF16.gguf models/mmproj-BF16.gguf",
"uv run --script llama.py download https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF/resolve/main/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"
]
}
},
// pre-build the uv script environments (whisper, prefect, sherpa-onnx, openvino, ...)
@@ -119,10 +213,27 @@ module.exports = {
]
}
},
// omp (cloud auth): installed into app/bin unless already on PATH; seeds ~/.omp/agent/models.yml only if absent
{
method: "shell.run",
params: {
path: "app",
message: "uv run --script llama.py install-omp"
}
},
{
method: "notify",
params: {
html: "Installation finished ({{ram >= 48 ? 'Qwen3.6 35B + Qwen3.5 4B: pick one in the Web UI header' : 'Qwen3.5 4B'}}). Click 'Start', then load the browser extension from the 'Extension' tab."
html: "Installation finished ({{local.onprem === '35b' ? 'Qwen3.6 35B + Qwen3.5 4B' : local.onprem === '4b' ? 'Qwen3.5 4B' : 'cloud models only'}}; pick the model in the Web UI header). Log in to GitHub Copilot in this terminal now; Anthropic: menu 'Cloud login'."
}
},
// last: an aborted device flow cannot leave the install half done; skips itself when omp already has a valid login
{
method: "shell.run",
params: {
path: "app",
input: true,
message: ["uv run --script llama.py login github-copilot --if-needed", "exit"]
}
}
]
+16
View File
@@ -0,0 +1,16 @@
// Pinokio menu "Cloud login": asks for the provider, then runs the omp login through llama.py.
module.exports = {
run: [{
// Step 1: choose the provider.
method: "input",
params: {
title: "Cloud login (omp)",
form: [{ type: "select", key: "provider", title: "Provider", default: "github-copilot",
items: [{ text: "GitHub Copilot", value: "github-copilot" }, { text: "Anthropic (Claude Pro/Max)", value: "anthropic" }] }]
}
// Step 2: run the login in the terminal; input: true lets the user answer prompts.
}, {
method: "shell.run",
params: { path: "app", input: true, message: "uv run --script llama.py login {{input.provider}}" }
}]
}
+20 -1
View File
@@ -1,15 +1,19 @@
// Pinokio launcher entry: the menu buttons depend on whether the app is installed and what is running.
module.exports = {
version: "7.0",
title: "Teams Whisper",
description: "Record Teams calls and turn them into meeting reports, fully local",
menu: async (kernel, info) => {
let installed = info.exists("app/models/qwen3.5-4b/Qwen3.5-4B-Q4_K_S.gguf")
// Installed marker: the bge-m3 embedding model that install.js downloads.
let installed = info.exists("app/models/bge-m3-Q8_0.gguf")
// Which launcher scripts are currently running.
let running = {
install: info.running("install.js"),
start: info.running("start.js"),
update: info.running("update.js"),
reset: info.running("reset.js")
}
// While install is running, show only the Installing entry.
if (running.install) {
return [{
default: true,
@@ -17,10 +21,13 @@ module.exports = {
text: "Installing",
href: "install.js",
}]
// Installed: the menu depends on whether the server (start.js) is running.
} else if (installed) {
if (running.start) {
// start.js saves the server URL in local state once it is ready.
let local = info.local("start.js")
if (local && local.url) {
// Server running with a known URL: links to the Web UI, Prefect, extension, login and terminal.
return [{
default: true,
icon: "fa-solid fa-rocket",
@@ -34,11 +41,16 @@ module.exports = {
icon: "fa-solid fa-puzzle-piece",
text: "Extension",
href: "ext.js",
}, {
icon: "fa-solid fa-key",
text: "Cloud login",
href: "login.js",
}, {
icon: 'fa-solid fa-terminal',
text: "Terminal",
href: "start.js",
}]
// Server running but URL not known yet: only the terminal.
} else {
return [{
default: true,
@@ -47,6 +59,7 @@ module.exports = {
href: "start.js",
}]
}
// Other jobs in progress: show only their status.
} else if (running.update) {
return [{
default: true,
@@ -62,6 +75,7 @@ module.exports = {
href: "reset.js",
}]
} else {
// Installed and idle: full menu.
return [{
default: true,
icon: "fa-solid fa-power-off",
@@ -71,6 +85,10 @@ module.exports = {
icon: "fa-solid fa-puzzle-piece",
text: "Extension",
href: "ext.js",
}, {
icon: "fa-solid fa-key",
text: "Cloud login",
href: "login.js",
}, {
icon: "fa-solid fa-plug",
text: "Update",
@@ -85,6 +103,7 @@ module.exports = {
href: "reset.js",
}]
}
// Not installed: only Install.
} else {
return [{
default: true,
+1 -2
View File
@@ -1,6 +1,5 @@
{
"title": "Teams Whisper",
"description": "Record Teams calls and turn them into meeting reports, fully local",
"platform": "win32",
"gpu": "nvidia"
"platform": "win32"
}
+1
View File
@@ -1,3 +1,4 @@
// Pinokio menu "Reset": deletes downloaded binaries and models so Install can run again.
module.exports = {
// keeps app/out (your meetings, reports, meetings.db)
run: [{
+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
+6
View File
@@ -1,7 +1,11 @@
// Pinokio menu "Start": runs the local server (server.py) and records its URL.
module.exports = {
// daemon: keeps the server running in the background until stopped from Pinokio.
daemon: true,
run: [
// Step 1: start the server.
{
// Run server.py in app/ with uv (its script dependencies are resolved by uv).
method: "shell.run",
params: {
path: "app",
@@ -10,12 +14,14 @@ module.exports = {
// port stays 18765: the browser extension's host_permissions hardcode it
message: "uv run --script server.py",
on: [{
// Wait for the URL the server prints (http://IP:port); the step is done once it matches.
event: "/(http:\\/\\/[0-9.:]+)/",
done: true
}]
}
},
{
// Step 2: save the URL so pinokio.js can show "Open Web UI".
method: "local.set",
params: {
url: "{{input.event[1]}}"
+2
View File
@@ -1,7 +1,9 @@
// Pinokio menu "Update": pulls the latest code from git.
module.exports = {
run: [{
method: "shell.run",
params: {
// Pull from the configured git remote.
message: "git pull"
}
}]