Add explanatory comments across codebase
This commit is contained in:
@@ -2,10 +2,15 @@
|
||||
import base64, collections, json, re, subprocess, urllib.error, urllib.request
|
||||
import db, llama
|
||||
|
||||
# Fallback result when a frame can't be read: all schema keys present, neutral values.
|
||||
EMPTY = {"kind": "other", "title": None, "app": None, "summary": "", "text": "", "entities": {}, "people": [], "presenter": None, "meeting_title": None, "content_box": None}
|
||||
# Kinds whose content is worth summarising in the report (the rest are chat/video/other).
|
||||
CONTENT_KINDS = {"slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket"}
|
||||
# Crop frames to the model-reported shared-content box (see _view).
|
||||
CROP_BOX = True
|
||||
# Allowed values for 'kind'; also the grammar enum in SCHEMA.
|
||||
KINDS = ["slide", "code", "terminal", "browser", "document", "spreadsheet", "diagram", "dashboard", "ticket", "chat", "video_tiles", "other"]
|
||||
# Schema shorthands: _S bounded string, _N nullable string, _L bounded string list.
|
||||
_S, _N, _L = {"type": "string", "maxLength": 300}, {"type": ["string", "null"], "maxLength": 200}, {"type": "array", "items": {"type": "string", "maxLength": 120}, "maxItems": 25}
|
||||
# json_schema -> llama.cpp grammar: valid JSON + valid kind every time (small models broke JSON / looped to max_tokens)
|
||||
SCHEMA = {"type": "object", "additionalProperties": False,
|
||||
@@ -17,6 +22,7 @@ SCHEMA = {"type": "object", "additionalProperties": False,
|
||||
"content_box": {"anyOf": [{"type": "array", "items": {"type": "integer"}, "minItems": 4, "maxItems": 4}, {"type": "null"}]}}}
|
||||
# v3: v1's inline JSON template (the model never sees the grammar: v2 without it -> kind=video_tiles, title=null) + every field defined
|
||||
# (v1 left title undefined), summary rules in Italian (v1 'ITALIAN' got echoed). Text before image: image-first measured worse.
|
||||
# Italian/English VLM prompt. Field list mirrors SCHEMA; the rules stop invented values.
|
||||
PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON: {"kind":"' + '|'.join(KINDS) + '","title":str|null,"app":str|null,"summary":str,"text":str,'
|
||||
'"entities":{"systems":[str],"tickets":[str],"urls":[str],"numbers":[str],"terms":[str]},"people":[str],"presenter":str|null,"meeting_title":str|null,"content_box":[x1,y1,x2,y2]|null}\n'
|
||||
'Look ONLY at the shared screen content: ignore the browser bookmarks bar, OS taskbar, Teams toolbar, video tiles and captions, except for people/presenter/meeting_title.\n'
|
||||
@@ -30,36 +36,46 @@ PROMPT = ('Screenshot from a Microsoft Teams meeting recording. Reply ONLY JSON:
|
||||
'- content_box: bounding box of the shared screen area (excluding Teams toolbar, video tiles, captions) in 0-1000 coordinates of this image; null if nothing is shared.\n'
|
||||
'Never invent: use null or [] when absent.')
|
||||
|
||||
# Jira-style issue key, e.g. ABC-123 (2-10 char project prefix).
|
||||
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
|
||||
# http(s) URL; stops at whitespace, quotes or closing brackets.
|
||||
URL = re.compile(r"""https?://[^\s)\]>"']+""")
|
||||
# Simple e-mail address.
|
||||
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
|
||||
|
||||
|
||||
# Send one keyframe to the VLM. json_mode=False drops response_format for servers that reject it.
|
||||
def _ask(path, json_mode=True):
|
||||
img = base64.b64encode(path.read_bytes()).decode()
|
||||
body = {"max_tokens": 4000, "temperature": 0.1, # dense screens (mail/slides transcribed in "text") need ~2000 tok; 1200 truncated them -> empty cloud reply / bad JSON -> silent kind "other"
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": PROMPT},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img}}]}]}
|
||||
# Constrain output with the schema; plain json_object when no schema is set.
|
||||
if json_mode: body["response_format"] = {"type": "json_schema", "json_schema": {"name": "shot", "schema": SCHEMA}} if SCHEMA else {"type": "json_object"}
|
||||
return llama.content(llama.post(body, True, 900), f"shot {path.name}")
|
||||
|
||||
|
||||
# Read one frame. Two tries on bad JSON; always returns a full dict (EMPTY on failure).
|
||||
def read_shot(path):
|
||||
json_mode = True
|
||||
# Retry once: VLM replies are sometimes malformed.
|
||||
for _ in range(2):
|
||||
try:
|
||||
try: t = _ask(path, json_mode)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 400 or not json_mode: raise
|
||||
json_mode = False; t = _ask(path, False)
|
||||
# Drop reasoning blocks some models emit before the JSON.
|
||||
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
|
||||
# Keep only the outermost {...} in case of surrounding text.
|
||||
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
|
||||
if isinstance(d, dict): return {**EMPTY, **d}
|
||||
except (ValueError, KeyError, IndexError): pass # IndexError: cloud returned empty "choices" (content filter / transient)
|
||||
return dict(EMPTY)
|
||||
|
||||
|
||||
# Deduplicate case-insensitively, keep order, drop empties.
|
||||
def _dedupe(xs):
|
||||
seen, out = set(), []
|
||||
for x in xs:
|
||||
@@ -68,6 +84,7 @@ def _dedupe(xs):
|
||||
return out
|
||||
|
||||
|
||||
# Merge regex-found tickets/URLs/e-mails into the model's entities; edits d in place.
|
||||
def _augment(d):
|
||||
ent = d.get("entities") if isinstance(d.get("entities"), dict) else {}
|
||||
blob = f"{d.get('text') or ''} {d.get('summary') or ''}"
|
||||
@@ -81,11 +98,14 @@ def _augment(d):
|
||||
|
||||
def _bars(video, dur):
|
||||
"""ffmpeg crop filter trimming black side bars, or None. dur: seconds (webm has no container duration)."""
|
||||
# Frame width, to check the crop is a real side-bar removal.
|
||||
w = int(subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", str(video)],
|
||||
capture_output=True, text=True).stdout.strip() or 0)
|
||||
# cropdetect: black threshold 24, round 16 px, sampled at mid-video.
|
||||
r = subprocess.run(["ffmpeg", "-ss", str(dur / 2), "-i", str(video), "-vf", "cropdetect=24:16:0", "-frames:v", "60", "-f", "null", "-"],
|
||||
capture_output=True, text=True)
|
||||
m = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", r.stderr)
|
||||
# Reject if the detected width is under half the frame (not a side-bar case).
|
||||
if not m or not w or int(m[-1][0]) < 0.5 * w: return None
|
||||
return "crop=" + ":".join(m[-1])
|
||||
|
||||
@@ -93,11 +113,15 @@ def _bars(video, dur):
|
||||
def _view(path, box):
|
||||
"""Crop the shared content out of a keyframe; returns the file name to display."""
|
||||
from PIL import Image
|
||||
# Fall back to the full frame when no usable box was returned.
|
||||
if not CROP_BOX or not isinstance(box, list) or len(box) != 4 or not all(isinstance(v, (int, float)) for v in box): return path.name
|
||||
im = Image.open(path); W, H = im.size
|
||||
# Model boxes are 0-1000 normalised; any value >1000 means pixel coordinates.
|
||||
sx, sy = (1, 1) if max(box) > 1000 else (W / 1000, H / 1000)
|
||||
x1, x2 = sorted((box[0] * sx, box[2] * sx)); y1, y2 = sorted((box[1] * sy, box[3] * sy))
|
||||
# 1% padding so text at the edge is not cut.
|
||||
x1, x2 = max(0, x1 - W * .01), min(W, x2 + W * .01); y1, y2 = max(0, y1 - H * .01), min(H, y2 + H * .01)
|
||||
# Ignore crops under 25% of the frame in either direction.
|
||||
if x2 - x1 < .25 * W or y2 - y1 < .25 * H: return path.name
|
||||
out = path.with_name(f"view_{path.stem}.jpg")
|
||||
im.crop((int(x1), int(y1), int(x2), int(y2))).convert("RGB").save(out, quality=90)
|
||||
@@ -105,26 +129,33 @@ def _view(path, box):
|
||||
|
||||
|
||||
def _times(video, scene, bars=None):
|
||||
# fps=2 sampling at 640 px wide; keep frames on scene change, the first frame, or >=60 s since the last kept one. showinfo prints pts_time to stderr.
|
||||
r = subprocess.run(["ffmpeg", "-i", str(video), "-vf",
|
||||
(bars + "," if bars else "") + f"fps=2,scale=640:-2,select='gt(scene,{scene})+isnan(prev_selected_t)+gte(t-prev_selected_t,60)',showinfo",
|
||||
"-f", "null", "-"], capture_output=True, text=True)
|
||||
# Timestamps (seconds) parsed from showinfo output.
|
||||
return [float(m) for m in re.findall(r"pts_time:([\d.]+)", r.stderr)]
|
||||
|
||||
|
||||
# Extract scene-change keyframes, dedupe, read each with the VLM, write shots.json and glossary, derive share/presence events.
|
||||
def run(name, max_frames=60, scene=0.05):
|
||||
import imagehash
|
||||
from PIL import Image
|
||||
d = db.out_dir(name)
|
||||
# media() returns (audio, video); index 1 is the video.
|
||||
video = db.media(name)[1]
|
||||
# No video: write empty outputs and stop.
|
||||
if video is None:
|
||||
db.replace_shots(name, [])
|
||||
(d / "shots.json").write_text("[]"); (d / "glossary.json").write_text("[]")
|
||||
return
|
||||
sd = d / "shots"
|
||||
sd.mkdir(exist_ok=True)
|
||||
# Clear frames from a previous run.
|
||||
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
|
||||
db.tick(name, 0, 0, "estrazione dei fotogrammi dal video")
|
||||
kept = [] # (t, path, hash)
|
||||
# Duration from DB, used for the black-bar detection.
|
||||
bars = _bars(video, (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [0])[0] or 0)
|
||||
for t in _times(video, scene, bars):
|
||||
p = sd / f"shot_{int(t)//60:02d}m{int(t)%60:02d}s.jpg"
|
||||
@@ -133,8 +164,10 @@ def run(name, max_frames=60, scene=0.05):
|
||||
*(["-vf", bars] if bars else []), "-q:v", "3", str(p)], check=True)
|
||||
if not p.exists(): continue
|
||||
h = imagehash.phash(Image.open(p))
|
||||
# pHash distance <=8 = near-duplicate of the last kept frame: drop it.
|
||||
if kept and h - kept[-1][2] <= 8: p.unlink(); continue
|
||||
kept.append((t, p, h))
|
||||
# Too many frames: keep evenly spaced ones up to max_frames.
|
||||
if len(kept) > max_frames:
|
||||
keep = sorted({round(i * (len(kept) - 1) / (max_frames - 1)) for i in range(max_frames)})
|
||||
for i, k in enumerate(kept):
|
||||
@@ -142,6 +175,7 @@ def run(name, max_frames=60, scene=0.05):
|
||||
kept = [kept[i] for i in keep]
|
||||
|
||||
db.tick(name, 0, len(kept), "avvio del modello di visione")
|
||||
# srv is None if llama-server was already running (we do not stop someone else's).
|
||||
srv = llama.start(log=db.logs(name) / "llama.log") # None if already running
|
||||
rows = []
|
||||
try:
|
||||
@@ -151,19 +185,24 @@ def run(name, max_frames=60, scene=0.05):
|
||||
r["view"] = _view(p, r.pop("content_box", None))
|
||||
rows.append({"t": t, "file": p.name, **r}); print(f"{t:6.1f}s {r['kind']} {(r['title'] or '')[:60]}", flush=True)
|
||||
finally:
|
||||
# Stop only the server this function started.
|
||||
if srv: srv.terminate()
|
||||
|
||||
# Duration from DB; fall back to last frame time + 60 s.
|
||||
dur = (db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone() or [None])[0]
|
||||
if dur is None: dur = rows[-1]["t"] + 60 if rows else 0
|
||||
prev = None
|
||||
# lead=False when a row repeats the previous kind+title (continuation of the same topic).
|
||||
for i, r in enumerate(rows):
|
||||
r["t_end"] = rows[i + 1]["t"] if i + 1 < len(rows) else dur
|
||||
key = (r["kind"], (r["title"] or "").lower()) if r["title"] else None
|
||||
r["lead"] = not (key and key == prev)
|
||||
prev = key
|
||||
# Persist to file and DB.
|
||||
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
db.replace_shots(name, rows)
|
||||
|
||||
# Glossary: terms appearing in the most frames (3-40 chars), top 150.
|
||||
cnt = collections.Counter()
|
||||
for r in rows:
|
||||
e = r["entities"]
|
||||
@@ -171,13 +210,17 @@ def run(name, max_frames=60, scene=0.05):
|
||||
(d / "glossary.json").write_text(json.dumps([w for w, _ in cnt.most_common(150)], ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
c = db.connect()
|
||||
# Derive events only if the call has no roster presence events yet (avoid duplicates).
|
||||
if c.execute("SELECT count(*) FROM call_events WHERE name=? AND kind='present' AND who_key<>'video'", (name,)).fetchone()[0] == 0:
|
||||
# Replace any video-derived events from an earlier run.
|
||||
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
|
||||
ev = []
|
||||
# People shown on video tiles -> 'present' events. Names with a space and >4 chars only (skips initials).
|
||||
for r in rows:
|
||||
ppl = [n for n in (db.norm_name(x) for x in r["people"]) if " " in n and len(n) > 4]
|
||||
if ppl: ev.append((r["t"], "present", "video", "", json.dumps([{"key": "video", "who": n} for n in ppl], ensure_ascii=False)))
|
||||
last = None
|
||||
# Presenter changes -> share_start / share_stop pairs.
|
||||
for r in rows:
|
||||
pr = db.norm_name(r["presenter"]) if r["presenter"] else None
|
||||
if pr != last:
|
||||
|
||||
Reference in New Issue
Block a user