Apply ruff lint and rename cryptic identifiers to readable names

This commit is contained in:
Stefano Zini
2026-11-05 09:09:20 +01:00
parent 19de4654ff
commit ead33657c7
24 changed files with 4459 additions and 1856 deletions
+383 -130
View File
@@ -1,40 +1,124 @@
"""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
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}
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"}
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}
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.
# 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'
'- 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.')
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."
)
# 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")
@@ -46,13 +130,31 @@ 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}}]}]}
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"}
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}")
@@ -62,170 +164,321 @@ def read_shot(path):
# 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)
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.
t = re.sub(r"<think>.*?</think>", "", t, flags=re.S)
text = re.sub(r"<think>.*?</think>", "", text, 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)
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(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 _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(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 _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)."""
# 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)
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.
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)
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 m or not w or int(m[-1][0]) < 0.5 * w: return None
return "crop=" + ":".join(m[-1])
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
# 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
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.
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))
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.
x1, x2 = max(0, x1 - W * .01), min(W, x2 + W * .01); y1, y2 = max(0, y1 - H * .01), min(H, y2 + H * .01)
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 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
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=90
)
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.
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)
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(m) for m in re.findall(r"pts_time:([\d.]+)", r.stderr)]
return [float(match) for match in re.findall(r"pts_time:([\d.]+)", result.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)
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)
shots_dir = out_dir / "shots"
shots_dir.mkdir(exist_ok=True)
# Clear frames from a previous run.
for p in [*sd.glob("shot_*.jpg"), *sd.glob("view_*.jpg")]: p.unlink()
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)
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))
bars = _bars(
video,
(
db.connect()
.execute("SELECT duration_s FROM recordings WHERE name=?", (name,))
.fetchone()
or [0]
)[0]
or 0,
)
for timestamp in _times(video, scene, bars):
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),
"-i",
str(video),
"-frames:v",
"1",
*(["-vf", bars] if bars else []),
"-q:v",
"3",
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 h - kept[-1][2] <= 8: p.unlink(); continue
kept.append((t, p, h))
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 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
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:
# Stop only the server this function started.
if srv: srv.terminate()
if server:
server.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
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
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)
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.
(d / "shots.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
(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.
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")
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()
connection = 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:
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.
c.execute("DELETE FROM call_events WHERE name=? AND who_key='video'", (name,))
ev = []
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 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)))
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 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)
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)