"""Topic summaries (local llama-server) + report.md / report.html rendering."""
import base64, difflib, json, re, unicodedata, urllib.request
import db, llama
from shots import CONTENT_KINDS
API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
LINE = re.compile(r"^\[(\d+):(\d+)\] (?:(Speaker \d+): )?(.*)$")
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
'Se parlato e schermo divergono, riportalo nel summary. Usa solo fatti presenti nel testo. '
'Usa i nomi dei partecipanti solo se compaiono nel testo come nomi propri; non citare mai le etichette "Speaker N": usa forme impersonali ("si conferma", "viene proposto"). Ogni argomento copre almeno 3 minuti di discussione: non creare un argomento per ogni schermata. Scrivi tutto in italiano. Se non sei sicuro, ometti. '
'Glossario dei termini corretti letti dallo schermo (la trascrizione può storpiarli, usa la grafia del glossario): ')
SYS_B = 'Dato l\'elenco degli argomenti, rispondi SOLO JSON: {"title":str,"tldr":[str]}. title: titolo breve della riunione (max 8 parole). Massimo 5 punti in tldr, in italiano, forma impersonale, senza etichette "Speaker N". Usa solo fatti presenti.'
SYS_D = ('Hai un argomento di una riunione e alcuni estratti di documentazione aziendale numerati. Rispondi SOLO JSON: {"summary":[{"text":str,"doc":int|null}],"from_docs":[{"text":str,"doc":int}]}. '
'"summary": riscrivi i punti della sintesi mantenendo tutti i fatti della riunione; puoi completarli o correggerli con la documentazione indicando in "doc" il numero dell\'estratto usato (null se il punto viene solo dalla riunione). '
'Se riunione e documentazione divergono, riporta entrambe ("in riunione …; secondo la documentazione …"). "from_docs": massimo 3 fatti della documentazione pertinenti all\'argomento e non detti in riunione. Non citare etichette "Speaker N". Non inventare. Scrivi in italiano.')
CLUSTER, TIDY_MIN, DOC_MIN = 0.82, 120, 3
GUI = "http://127.0.0.1:18765"
def mmss(s): s = int(s); return f"{s // 60:02d}:{s % 60:02d}"
def secs(s):
m = re.match(r"(\d+):(\d+)", str(s))
return int(m[1]) * 60 + int(m[2]) if m else 0
def chat(system, user, max_tokens, retries=2):
body = {"model": llama.current(False), "temperature": 0.2, "max_tokens": max_tokens,
"chat_template_kwargs": {"enable_thinking": False}, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
for _ in range(retries):
try:
try:
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
except urllib.error.HTTPError as e:
if e.code != 400: raise
body.pop("response_format", None)
r = _open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=1800)
t = json.load(r)["choices"][0]["message"]["content"]
t = re.sub(r".*?", "", t, flags=re.S)
d = json.loads(t[t.find("{"):t.rfind("}") + 1])
if isinstance(d, dict): return d
except (ValueError, KeyError): pass
return None
def _transcript(name):
p = db.OUT / f"{name}.spk.txt"
if not p.exists(): p = db.OUT / f"{name}.txt"
rows = []
for l in p.read_text(encoding="utf-8").splitlines() if p.exists() else []:
m = LINE.match(l)
if m: rows.append((int(m[1]) * 60 + int(m[2]), m[3], m[4]))
return rows
def _load(name, f, default):
p = db.out_dir(name) / f
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else default
def _shares(evs, dur):
out, open_ = [], {}
for e in evs:
if e["kind"] == "share_start": open_[e["who"]] = e["t"]
elif e["kind"] == "share_stop" and e["who"] in open_: out.append({"who": e["who"], "start": open_.pop(e["who"]), "end": e["t"]})
out += [{"who": w, "start": s, "end": dur} for w, s in open_.items()]
return sorted(out, key=lambda x: x["start"])
def _subst(s, names):
return re.sub(r"\bSpeaker (\d+)\b", lambda m: names.get(m[0]) or m[0], s) if isinstance(s, str) else s
def _deep(o, f):
if isinstance(o, str): return f(o)
if isinstance(o, list): return [_deep(x, f) for x in o]
if isinstance(o, dict): return {k: _deep(v, f) for k, v in o.items()}
return o
def _merge(topics):
out = []
for t in topics:
if out and out[-1]["title"].lower() == t["title"].lower():
p = out[-1]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): p[k] = p[k] + t[k]
p["end_s"] = t["end_s"]
else: out.append(t)
return out
def _key(n): return " ".join(sorted(unicodedata.normalize("NFKD", n).encode("ascii", "ignore").decode().lower().split()))
def _sim(a, b): return difflib.SequenceMatcher(None, _key(a), _key(b)).ratio()
def canon(counts, known, video=False, thr=CLUSTER):
"""raw name -> canonical spelling (known list first, else most frequent of a similarity cluster); dropped names have no entry."""
out, clusters = {}, []
for raw, c in sorted(counts.items(), key=lambda x: -x[1]):
if " " not in raw or len(raw) <= 4 or "..." in raw or "…" in raw: continue
best = max(((_sim(raw, k), k) for k in known), default=(0, None))
if best[0] >= .75: out[raw] = best[1]; continue
cl = next((x for x in clusters if _sim(raw, x[0]) >= thr), None)
if cl: cl[1] += c; cl[2].append(raw)
else: clusters.append([raw, c, [raw]])
for rep, tot, mem in clusters:
if video and tot < 2: continue
for m in mem: out[m] = rep
return out
def _canon_att(att, cmap):
out = {}
for a in att.values():
c = cmap.get(a["who"])
if not c: continue
x = out.setdefault(c, {"who": c, "first_t": a["first_t"], "last_t": a["last_t"]})
x["first_t"], x["last_t"] = min(x["first_t"], a["first_t"]), max(x["last_t"], a["last_t"])
return out
def _canon_shares(shares, cmap):
ss = sorted(({**s, "who": cmap[s["who"]]} for s in shares if s["who"] in cmap), key=lambda s: s["start"])
while True:
out = []
for s in ss:
if out and out[-1]["who"] == s["who"] and s["start"] - out[-1]["end"] <= 60: out[-1]["end"] = max(out[-1]["end"], s["end"])
else: out.append(dict(s))
kept = [s for s in out if s["end"] - s["start"] >= 20]
if len(kept) == len(ss): return kept
ss = kept
def _tidy(topics, dur, min_s=TIDY_MIN):
"""Sort, de-overlap, merge topics shorter than min_s into a neighbour, keep only screen facts timed inside the topic."""
topics.sort(key=lambda t: t["start_s"])
prev = 0
for t in topics: t["start_s"] = max(t["start_s"], prev); t["end_s"] = max(t["end_s"], t["start_s"] + 1); prev = t["end_s"]
ln = lambda t: t["end_s"] - t["start_s"]
while len(topics) > 1:
i = next((i for i, t in enumerate(topics) if ln(t) < min_s), None)
if i is None: break
j = i - 1 if i else 1
lo, hi = min(i, j), max(i, j)
a, b = topics[lo], topics[hi]
m = dict(a)
m["title"] = (a if ln(a) >= ln(b) else b)["title"]
for k in ("summary", "shown", "decisions", "actions", "open_questions"): m[k] = a[k] + b[k]
m["start_s"], m["end_s"] = min(a["start_s"], b["start_s"]), max(a["end_s"], b["end_s"])
topics[lo:hi + 1] = [m]
for t in topics:
t["shown"] = [x for x in t["shown"] if (m := re.search(r"(\d\d):(\d\d)", str(x))) and t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30]
return topics
def _words(s): return {w for w in re.findall(r"\w+", s.lower()) if len(w) >= 5}
def _pass_d(t, docs):
"""Complete/correct a topic's summary with the best-matching docs; sets t['summary'] and t['from_docs'] as {text, doc} dicts."""
w = _words(" ".join([t["title"], *(x["text"] for x in t["summary"]), *t["shown"]]))
top = sorted(((len(w & _words(d["title"] + " " + d["body"])), d) for d in docs), key=lambda x: -x[0])
top = [d for n, d in top[:3] if n >= DOC_MIN]
if not top: return
user = f"ARGOMENTO: {t['title']}\nSINTESI:\n" + "\n".join(f"- {x['text']}" for x in t["summary"]) + "\n\nDOCUMENTI:\n" + "\n\n".join(
f"[{n}] {d['title']} ({d['source']})\n{d['body'][:2500]}" for n, d in enumerate(top, 1))
r = chat(SYS_D, user, 2500) or {}
ref = lambda n: top[n - 1]["i"] if isinstance(n, int) and 1 <= n <= len(top) else None
fix = lambda l: [{"text": str(x["text"]), "doc": ref(x.get("doc"))} for x in l if isinstance(x, dict) and x.get("text")]
s = fix(r.get("summary") or [])
if s: t["summary"] = s
t["from_docs"] = [x for x in fix(r.get("from_docs") or [])[:3] if x["doc"] is not None]
def run(name, window_words=3000):
rec = db.connect().execute("SELECT duration_s FROM recordings WHERE name=?", (name,)).fetchone()
tx = _transcript(name)
dur = (rec and rec[0]) or (tx[-1][0] + 5 if tx else 0)
shots = _load(name, "shots.json", []); glossary = _load(name, "glossary.json", [])
crop_ok = any((s.get("view") or "").startswith("view_") for s in shots) # when crops exist, frames without one show no shared content
usable = lambda s: s["kind"] in CONTENT_KINDS and (not crop_ok or (s.get("view") or "").startswith("view_"))
evs = db.events(name, "meta", "present", "share_start", "share_stop", "chat", "hand")
names = db.speaker_names(name)
meta = [json.loads(e["text"]) for e in evs if e["kind"] == "meta"]
title = (meta[-1].get("title") or "") if meta else ""
shares = _shares(evs, dur)
att, src, counts = {}, set(), {}
for e in evs:
if e["kind"] != "present": continue
for p in json.loads(e["text"] or "[]"):
a = att.setdefault(p["who"], {"who": p["who"], "first_t": e["t"], "last_t": e["t"]})
a["last_t"] = max(a["last_t"], e["t"])
src.add("video" if e["who_key"] == "video" else "teams")
counts[p["who"]] = counts.get(p["who"], 0) + 1
attendees_source = "teams" if "teams" in src else "video" if src else "none"
for s in shots:
if s.get("presenter"): n = db.norm_name(s["presenter"]); counts[n] = counts.get(n, 0) + 1
for s in shares: counts[s["who"]] = counts.get(s["who"], 0) + 1
known = list(dict.fromkeys(_load(name, "docs.json", {"people": []}).get("people", []) +
[p["who"] for e in evs if e["kind"] == "present" and e["who_key"] != "video" for p in json.loads(e["text"] or "[]")]))
cmap = canon(counts, known, video=attendees_source == "video")
att, shares = _canon_att(att, cmap), _canon_shares(shares, cmap)
chats = [{"t": e["t"], "who": e["who"], "text": e["text"]} for e in evs if e["kind"] == "chat"]
# timeline items: (t, line)
items = [(t, f"[{mmss(t)}] " + (f"{names.get(sp, sp)}: " if sp else "") + x, len(x.split())) for t, sp, x in tx]
prev_text = None
for s in filter(usable, shots):
sh = next((x["who"] for x in shares if x["start"] <= s["t"] < x["end"]), None)
l = f"[{mmss(s['t'])}] [SCHERMO {s['kind']}{', condiviso da ' + sh if sh else ''}] {s.get('title') or ''}: {s.get('summary') or ''}"
if s.get("text") and s["text"] != prev_text: l += "\n testo: " + s["text"].replace("\n", " / ")[:600]
prev_text = s.get("text"); items.append((s["t"], l, len(l.split())))
items += [(c["t"], f"[{mmss(c['t'])}] [CHAT] {c['who']}: {c['text']}", 0) for c in chats]
items += [(e["t"], f"[{mmss(e['t'])}] [MANO ALZATA] {e['who']}", 0) for e in evs if e["kind"] == "hand"]
items.sort(key=lambda x: x[0])
system = SYS_A + (", ".join(glossary) or "nessuno")
topics, buf, words, wstart = [], [], 0, 0
def flush(end):
nonlocal buf, words
if not buf: return
d = chat(system, "\n".join(buf), 4000)
ts = d.get("topics") if d else None
if not ts:
ts = [{"title": f"Parte {mmss(wstart)}–{mmss(end)}", "start": mmss(wstart), "end": mmss(end), "summary": ["(riassunto non disponibile)"]}]
for t in ts:
t = {"title": str(t.get("title") or "Argomento"), "summary": list(t.get("summary") or []), "shown": list(t.get("shown") or []),
"decisions": list(t.get("decisions") or []), "actions": [a for a in (t.get("actions") or []) if isinstance(a, dict)],
"open_questions": list(t.get("open_questions") or []),
"start_s": secs(t.get("start")), "end_s": secs(t.get("end"))}
t["end_s"] = min(max(t["end_s"], t["start_s"] + 1), max(dur, t["start_s"] + 1))
topics.append(t)
buf, words = [], 0
for t, l, w in items:
if not buf: wstart = t
buf.append(l); words += w
if words >= window_words: flush(t)
flush(items[-1][0] if items else 0)
topics = _tidy(topics, dur)
for t in topics:
for a in t["actions"]:
if re.fullmatch(r"Speaker \d+", str(a.get("who", ""))) and a["who"] not in names: a["who"] = ""
docs = _load(name, "docs.json", {"items": [], "people": []})["items"]
for t in topics:
t["summary"] = [{"text": str(s), "doc": None} for s in t["summary"]]
t["from_docs"] = []
if docs: _pass_d(t, docs)
ov = chat(SYS_B, json.dumps([{"title": t["title"], "summary": [x["text"] for x in t["summary"]], "shown": t["shown"], "decisions": t["decisions"], "actions": t["actions"]} for t in topics], ensure_ascii=False), 800) or {}
tldr = [str(x) for x in (ov.get("tldr") or [])][:5]
title = title or str(ov.get("title") or "").strip()
good = [s for s in shots if s.get("lead") and usable(s) and len(s.get("text") or "") >= 40]
for t in topics: t["shots"] = []
for s in good:
if not topics: break
tp = next((t for t in topics if t["start_s"] <= s["t"] <= t["end_s"]), None) or min(topics, key=lambda t: abs(t["start_s"] - s["t"]))
tp["shots"].append(s)
for t in topics:
best = sorted(t["shots"], key=lambda s: -len(s.get("text") or ""))[:2]
t["shots"] = sorted(best, key=lambda s: s["t"])
cshots = [s for s in shots if usable(s)]
refs = {"tickets": {}, "urls": {}, "systems": {}, "emails": {}, "numbers": {}}
sysn = {}
for s in cshots:
e = s.get("entities") or {}
for k in ("urls", "emails", "numbers"):
for v in e.get(k, []): refs[k].setdefault(v, s["t"])
for v in e.get("systems", []): sysn.setdefault(v.lower(), (v, set()))[1].add(s["file"])
alltx = " ".join(x for _, _, x in tx).lower()
for low, (v, files) in sysn.items():
if len(v) >= 3 and (len(files) >= 2 or low in alltx):
refs["systems"][v] = min(s["t"] for s in cshots if s["file"] in files)
for t, _, x in tx:
for k in TICKET.findall(x): refs["tickets"].setdefault(k, t)
references = {"tickets": [{"key": k, "first_t": t} for k, t in refs["tickets"].items()],
"urls": [{"url": k, "first_t": t} for k, t in refs["urls"].items()],
"systems": [{"name": k, "first_t": t} for k, t in refs["systems"].items()],
"emails": [{"email": k, "first_t": t} for k, t in refs["emails"].items()],
"numbers": [{"value": k, "t": t} for k, t in refs["numbers"].items()]}
screen = []
for s in shots:
if not s.get("lead") or not usable(s): continue
r = {k: s.get(k) for k in ("t", "t_end", "kind", "title", "summary")}
if screen and (screen[-1]["title"] or "").lower() == (r["title"] or "").lower(): screen[-1]["t_end"] = r["t_end"]
else: screen.append(r)
m = re.match(r"(?:teams|meet)_(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-\d\d", name)
rep = {"name": name, "date": f"{m[1]} {m[2]}:{m[3]}" if m else "", "duration_s": dur, "meeting_title": title,
"tldr": tldr, "attendees": list(att.values()), "attendees_source": attendees_source, "known_spelling": bool(known),
"name_map": cmap, "shares": shares, "chat": chats, "references": references, "screen": screen, "topics": topics}
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
db.replace_topics(name, topics)
def _head(i, t): return f"{i}. {t['title']} ({mmss(t['start_s'])}–{mmss(t['end_s'])})"
def named(name, rep):
nm = rep.get("name_map", {})
names = {l: nm.get(p, p) for l, p in db.speaker_names(name).items()}
return _deep(rep, lambda s: re.sub(r"\bSpeaker \d+\b", "un partecipante", _subst(s, names))), names
def render(name):
import markdown
from markdown.extensions.toc import slugify
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
docs = _load(name, "docs.json", None)
items = {x["i"]: x for x in (docs or {}).get("items", [])}
rep, names = named(name, rep)
segs = _load(name, "diar_segments.json", [])
link = lambda s: TICKET.sub(lambda m: f"[{m[0]}]({JIRA_BROWSE}/{m[0]})", s)
q = lambda s: re.sub(r'[\[\]"]', "", s or "")
md = [f"# {rep['meeting_title'] or 'Riunione'} — {rep['date']}", "", f"**Durata:** {int(rep['duration_s'] // 60)} min", "", "## In breve", ""]
md += [f"- {x}" for x in rep["tldr"]] + [""]
# participants
talk = {}
for s in segs:
p = names.get(s["label"])
if p: talk[p] = talk.get(p, 0) + s["end"] - s["start"]
video = rep["attendees_source"] == "video"
if video:
people = sorted({a["who"] for a in rep["attendees"]})
if talk or people: md += ["## Partecipanti", ""]
if talk: md += ["| Partecipante | Parlato |", "|---|---|"] + [f"| {p} | {int(v // 60)} min |" for p, v in talk.items()] + [""]
if people:
md += ["*Nomi letti dai fotogrammi (ortografia verificata sulla documentazione): verificare.*" if rep.get("known_spelling") else "*Nomi letti dai fotogrammi: verificare.*", "", ", ".join(people), ""]
else:
rows = {p: [v, None] for p, v in talk.items()}
for a in rep["attendees"]:
k = next((p for p in rows if p.lower() == a["who"].lower()), a["who"])
rows.setdefault(k, [0, None])[1] = f"{mmss(a['first_t'])}–{mmss(a['last_t'])}"
if rows:
md += ["## Partecipanti", "", "| Partecipante | Parlato | Presente |", "|---|---|---|"]
md += [f"| {p} | {f'{int(v[0] // 60)} min' if v[0] else '—'} | {v[1] or '—'} |" for p, v in rows.items()] + [""]
if rep["shares"]:
md += ["## Condivisioni schermo", ""] + [f"- {mmss(s['start'])}–{mmss(s['end'])} {s['who']}" for s in rep["shares"]] + [""]
heads = []
md += ["## Argomenti", ""]
for i, t in enumerate(rep["topics"], 1):
h = _head(i, t)
heads.append(h)
md.append(f"{i}. [{t['title']}](#{slugify(h, '-')})")
md.append("")
def cite(x):
x = x if isinstance(x, dict) else {"text": x, "doc": None}
c = f' [📄]({items[x["doc"]]["url"]} "{q(items[x["doc"]]["title"])}")' if x.get("doc") in items else ""
return f"- {x['text']}{c}"
for h, t in zip(heads, rep["topics"]):
md += [f"## {h}", "", "### Sintesi", ""] + [cite(x) for x in t["summary"]] + [""]
fd = [x for x in t.get("from_docs", []) if x.get("doc") in items]
if fd: md += ["### Dalla documentazione", ""] + [f"- 📄 {x['text']} — [{q(items[x['doc']]['title'])}]({items[x['doc']]['url']})" for x in fd] + [""]
pv = t.get("previous") or []
if pv: md += ["### Dalle riunioni precedenti", ""] + [f"- **{x['status']}** — {x['text']} — [{q(x.get('meeting') or x['name'])} {x['date']}, {q(x['topic'])} {mmss(x['t'])}]({GUI}/report?name={x['name']}#{x['anchor']})" for x in pv] + [""]
if t["shown"]: md += ["### Mostrato a schermo", ""] + [f"- {link(x)}" for x in t["shown"]] + [""]
if t["decisions"]: md += ["### Decisioni", ""] + [f"- {x}" for x in t["decisions"]] + [""]
if t["open_questions"]: md += ["### Domande aperte", ""] + [f"- {x}" for x in t["open_questions"]] + [""]
if t["actions"]:
md += ["### Azioni", "", "| Chi | Cosa | Quando |", "|---|---|---|"]
md += [f"| {a.get('who', '')} | {a.get('what', '')} | {a.get('when', '')} |" for a in t["actions"]] + [""]
for s in t["shots"]:
alt = re.sub(r"[\[\]()]", "", s.get("title") or "")
sh = next((x["who"] for x in rep["shares"] if x["start"] <= s["t"] < x["end"]), None)
cap = f"{mmss(s['t'])} — " + (f"condiviso da {sh} — " if sh else "") + f"{s.get('title') or ''} — {s.get('summary') or ''}"
md += [f" or s['file']})", "", f"*{cap}*", ""]
if items:
md += ["## Documentazione correlata", ""]
for x in items.values():
md.append((f"- 🎫 [{q(x['key'])} — {q(x['title'])}]({x['url']}) — {x['status'] or ''}" if x["source"] == "jira" else f"- 📄 [{q(x['title'])}]({x['url']}) — Confluence")
+ (" — citato in riunione" if x.get("mentioned") else ""))
md.append("")
if rep["chat"]:
md += ["## Chat", ""] + [f"[{mmss(c['t'])}] **{c['who']}:** {c['text']} " for c in rep["chat"]] + [""]
r = rep["references"]
tk = ([f"[{x['key']}]({x['url']}) — {q(x['title'])}" for x in items.values() if x["source"] == "jira" and x.get("mentioned")] if docs is not None
else [f"[{x['key']}]({JIRA_BROWSE}/{x['key']}) — {mmss(x['first_t'])}" for x in r["tickets"]])
sy = [f"{x['name']} — {mmss(x['first_t'])}" for x in r["systems"]]
if tk or sy:
md += ["## Riferimenti", ""]
for k, v in (("Ticket", tk), ("Sistemi", sy)):
if v: md += [f"**{k}**", ""] + [f"- {x}" for x in v] + [""]
if rep["screen"]:
md += [f'Cronologia schermo ({len(rep["screen"])} schermate)
', "",
"## Cronologia schermo", "", "| Da | A | Tipo | Titolo | Sintesi |", "|---|---|---|---|---|"]
cell = lambda x: (x or "").replace("|", "/").replace("\n", " ")
md += [f"| {mmss(s['t'])} | {mmss(s['t_end'] or 0)} | {s['kind']} | {cell(s['title'])} | {cell(s['summary'])} |" for s in rep["screen"]]
md += ["", " ", ""]
text = "\n".join(md)
(d / "report.md").write_text(text, encoding="utf-8")
body = markdown.markdown(text, extensions=["tables", "toc", "md_in_html"])
body = re.sub(r'src="shots/([^"]+)"', lambda m: 'src="data:image/jpeg;base64,' + base64.b64encode((d / "shots" / m[1]).read_bytes()).decode() + '"', body)
h1 = re.sub(r"[#]+ ", "", md[0])
css = """:root{--bg:#faf9f5;--card:#fff;--soft:#f0eee6;--line:#e8e6dc;--fg:#141413;--mut:#6b6a64;--acc:#c96442}
@media screen and (prefers-color-scheme:dark){:root{--bg:#262624;--card:#30302e;--soft:#1f1e1d;--line:#3e3e38;--fg:#f5f4ed;--mut:#a3a29a;--acc:#d97757}}
*{box-sizing:border-box}body{max-width:860px;margin:auto;padding:56px 24px 96px;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,"Segoe UI",sans-serif}
h1,h2{font-family:ui-serif,Georgia,"Times New Roman",serif;font-weight:500;line-height:1.25;letter-spacing:-.01em}
h1{font-size:2.2em;margin:0 0 .2em}h1+p{color:var(--mut);margin-top:0}
h2{font-size:1.5em;margin:2em 0 .6em;padding-top:1em;border-top:1px solid var(--line)}
h3{font-size:.78em;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--mut);margin:1.8em 0 .4em}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
ul,ol{padding-left:1.4em}li{margin:.3em 0}li::marker{color:var(--acc)}
#in-breve{border-top:0}#in-breve+ul{background:var(--soft);border-left:3px solid var(--acc);border-radius:10px;padding:16px 20px 16px 2.4em}
table{border-collapse:separate;border-spacing:0;width:100%;background:var(--card);border:1px solid var(--line);border-radius:12px;overflow:hidden;font-size:.92em}
td,th{padding:9px 14px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tr:last-child td{border-bottom:0}th{background:var(--soft);font-weight:600}
img{width:100%;border:1px solid var(--line);border-radius:12px;margin-top:.8em}p>em{color:var(--mut);font-size:.88em}
details{margin-top:2.4em;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 18px}summary{cursor:pointer;color:var(--acc);font-weight:500}
code{background:var(--soft);border-radius:5px;padding:.1em .35em;font-size:.9em}"""
(d / "report.html").write_text(f'
{h1}\n{body}', encoding="utf-8")