189 lines
12 KiB
Python
189 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
|
|
|
|
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 = {"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"}
|
|
return llama.content(llama.post(body, True, 900), f"shot {path.name}")
|
|
|
|
|
|
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, 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
|
|
|
|
|
|
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()
|
|
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))
|
|
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]
|
|
|
|
db.tick(name, 0, len(kept), "avvio del modello di visione")
|
|
srv = 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)
|
|
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, ""))
|
|
db.add_events(name, ev)
|