Files
teams-whisper/app/shots.py
T
pinokioandClaude Opus 5.5 a64d3fb275 Hardware-aware install, per-step LLM profiles, tuned llama.cpp for 4 GB VRAM
Benchmarked on RTX 500 Ada 4 GB (~3.2 GB usable on Windows) + Core Ultra 7 155H.

- install.js: log GPU/VRAM/RAM, abort without NVIDIA >= 4 GB VRAM; always
  install Qwen3.5-4B Q4_K_S, Qwen3.6-35B-A3B only with >= 48 GB RAM.
- llama.py: model registry with vision (shots) and text (report/ask)
  profiles; KV q8, image tokens 1024-1536.
  - 35B: vision encoder on GPU, -ngl 30 (shot 142 -> ~50 s); text: -ub 2048.
  - 4B: vision encoder on GPU, FFN of layers 19-31 in RAM (shot 36 -> 22 s);
    text fully on GPU (~30 tok/s, report 4.5 min).
  - Per-step choice in out/llm.txt: default 4B for shots, biggest for report.
- flow.py: restart llama in text profile after shots (no mmproj for report).
- shots.py: prompt v3 (inline template + defined fields, Italian summary
  rules) and bounded json_schema; stops 4B loops, title 1/38 -> 36/38.
- server.py: shots/report model selects, POST /cancel + stop button, reaper
  thread that honours Prefect "Cancel" and closes runs whose process died.
- diarize.py: cut same-speaker paragraphs every 60 s (one 11-min paragraph
  truncated every report at 28:52); 8 threads; CUDA provider with CPU
  fallback via sherpa-onnx cuda12.cudnn9 wheel (CUDA path not yet verified).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:20:19 +01:00

191 lines
12 KiB
Python

"""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"}
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}
# 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"}]}}}
# 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,'
'"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'
'- 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'
'- 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.')
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
URL = re.compile(r"""https?://[^\s)\]>"']+""")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def _ask(path, json_mode=True):
img = base64.b64encode(path.read_bytes()).decode()
body = {"model": llama.current(True), "max_tokens": 1200, "temperature": 0.1,
"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 json.load(_open(req, timeout=900))["choices"][0]["message"]["content"]
def read_shot(path):
json_mode = True
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
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
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 [])
def _bars(video, dur):
"""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])
def _view(path, 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
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)]
def run(name, max_frames=60, scene=0.05):
import imagehash
from PIL import Image
d = db.out_dir(name)
video = db.media(name)[1]
if video is None:
db.replace_shots(name, [])
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]")
return
sd = d / "shots"
sd.mkdir(exist_ok=True)
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
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))
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]
srv = llama.start(log=d / "llama.log") # None if already running
rows = []
try:
for t, p, _ in kept:
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)
finally:
if srv: srv.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
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)
prev = key
(d / "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")
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)))
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, ""))
titles = collections.Counter(r["meeting_title"] for r in rows if r["meeting_title"])
if titles: ev.append((0, "meta", "video", "", json.dumps({"title": titles.most_common(1)[0][0], "call_elapsed": "", "url": ""}, ensure_ascii=False)))
db.add_events(name, ev)