"""Screen content extraction: scene-change keyframes -> local VLM reads each into structured JSON.""" 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 # 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": _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. # 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, 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). 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." ) # 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): 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," + 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: 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".*?", "", 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) # 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 # 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, duration): """ffmpeg crop filter trimming black side bars, or None. dur: seconds (webm has no container duration).""" # Frame width, to check the crop is a real side-bar removal. 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, content_box): """Crop the shared content out of a keyframe; returns the file name to display.""" from PIL import Image # Fall back to the full frame when no usable box was returned. if ( not CROP_BOX or not isinstance(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): # 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 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, []) (out_dir / "shots.json").write_text("[]") (out_dir / "glossary.json").write_text("[]") return 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) # 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(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 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 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: # Stop only the server this function started. if server: server.terminate() # 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 # 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 # 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) # 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", ) 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 # 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")