Apply ruff lint and rename cryptic identifiers to readable names
This commit is contained in:
+198
-78
@@ -4,9 +4,17 @@
|
||||
# ///
|
||||
"""Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db.
|
||||
uv run --script memory.py --reindex"""
|
||||
import contextlib, json, re, sys, urllib.request
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
import db
|
||||
import llama
|
||||
import numpy as np
|
||||
import db, llama, report
|
||||
import report
|
||||
|
||||
# bge-m3 embeddings endpoint on the local embedding server.
|
||||
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
|
||||
@@ -15,126 +23,209 @@ MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
|
||||
# Direct opener bypassing the corp proxy (the embedding server is localhost).
|
||||
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
|
||||
# Italian prompt: link current-meeting topics to earlier excerpts; JSON output.
|
||||
SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
|
||||
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
|
||||
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.')
|
||||
SYS_M = (
|
||||
'Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
|
||||
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
|
||||
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.'
|
||||
)
|
||||
# Prompt for ask(): answer from numbered excerpts only, cite as [n].
|
||||
SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi in testo semplice (niente JSON). Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.'
|
||||
SYS_ASK = "Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi in testo semplice (niente JSON). Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso."
|
||||
# Valid link statuses; anything else from the LLM is dropped.
|
||||
STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
|
||||
|
||||
|
||||
# Start the CPU embedding server for the block; stop it on exit only if this call started it.
|
||||
@contextlib.contextmanager
|
||||
def embedder(log):
|
||||
p = llama.start_embed(log=log)
|
||||
try: yield
|
||||
def embedder(log_path):
|
||||
embed_process = llama.start_embed(log=log_path)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if p is not None: p.terminate()
|
||||
if embed_process is not None:
|
||||
embed_process.terminate()
|
||||
|
||||
|
||||
# Embed texts via the local embedding server, 32 per request, each cut to 2000 chars.
|
||||
def embed(texts):
|
||||
out = []
|
||||
for i in range(0, len(texts), 32):
|
||||
body = {"input": [x[:2000] for x in texts[i:i + 32]], "model": "bge-m3"}
|
||||
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
|
||||
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])]
|
||||
v = np.array(out, dtype=np.float32)
|
||||
vectors = []
|
||||
for start in range(0, len(texts), 32):
|
||||
body = {"input": [text[:2000] for text in texts[start : start + 32]], "model": "bge-m3"}
|
||||
response = json.load(
|
||||
_open(
|
||||
urllib.request.Request(
|
||||
API, json.dumps(body).encode(), {"Content-Type": "application/json"}
|
||||
),
|
||||
timeout=600,
|
||||
)
|
||||
)
|
||||
vectors += [
|
||||
item["embedding"] for item in sorted(response["data"], key=lambda item: item["index"])
|
||||
]
|
||||
matrix = np.array(vectors, dtype=np.float32)
|
||||
# L2-normalize so dot products are cosine similarities.
|
||||
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
|
||||
return matrix / np.maximum(np.linalg.norm(matrix, axis=1, keepdims=True), 1e-9)
|
||||
|
||||
|
||||
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
|
||||
def _stamp(n):
|
||||
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n)
|
||||
return m[0] if m else ""
|
||||
def _stamp(name):
|
||||
match = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", name)
|
||||
return match[0] if match else ""
|
||||
|
||||
|
||||
# Load memory rows matching pred and stack their vectors into an (n, dim) matrix.
|
||||
def _rows(pred):
|
||||
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k.
|
||||
rows = [r for r in db.connect().execute("SELECT * FROM memory") if pred(r)]
|
||||
if not rows: return [], None
|
||||
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1)
|
||||
rows = [row for row in db.connect().execute("SELECT * FROM memory") if pred(row)]
|
||||
if not rows:
|
||||
return [], None
|
||||
return rows, np.frombuffer(b"".join(row["vec"] for row in rows), np.float32).reshape(
|
||||
len(rows), -1
|
||||
)
|
||||
|
||||
|
||||
# Summary entries may be dicts {"text": ...} or plain strings.
|
||||
def _txt(x): return x["text"] if isinstance(x, dict) else str(x)
|
||||
def _summary_text(item):
|
||||
return item["text"] if isinstance(item, dict) else str(item)
|
||||
|
||||
|
||||
# Topic as one string: title (optional), summary, decisions, open questions.
|
||||
def _topic_text(t, title=True):
|
||||
parts = ([t["title"]] if title else []) + [_txt(x) for x in t.get("summary", [])] + list(t.get("decisions", [])) + list(t.get("open_questions", []))
|
||||
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p)
|
||||
def _topic_text(topic, title=True):
|
||||
parts = (
|
||||
([topic["title"]] if title else [])
|
||||
+ [_summary_text(item) for item in topic.get("summary", [])]
|
||||
+ list(topic.get("decisions", []))
|
||||
+ list(topic.get("open_questions", []))
|
||||
)
|
||||
return (
|
||||
". ".join(part for part in parts if part)
|
||||
if title
|
||||
else " ".join(part for part in parts if part)
|
||||
)
|
||||
|
||||
|
||||
# Embed one meeting's report items into the memory table (replaces its previous rows).
|
||||
def index(name):
|
||||
# slugify matches the report's heading anchors.
|
||||
from markdown.extensions.toc import slugify
|
||||
rep = report._load(name, "report.json", None)
|
||||
if rep is None: return
|
||||
rep, _ = report.named(name, rep)
|
||||
|
||||
report_json = report._load(name, "report.json", None)
|
||||
if report_json is None:
|
||||
return
|
||||
report_json, _ = report.named(name, report_json)
|
||||
items = []
|
||||
# One item per topic summary, decision, action and open question.
|
||||
for i, t in enumerate(rep["topics"], 1):
|
||||
for topic_index, topic in enumerate(report_json["topics"], 1):
|
||||
# Shared fields of every item of this topic: (name, position, start, meeting, date, title, anchor).
|
||||
base = (name, i, t["start_s"], rep["meeting_title"], rep["date"], t["title"], slugify(report._head(i, t), "-"))
|
||||
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])]
|
||||
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])]
|
||||
its += [("open_question", x) for x in t.get("open_questions", [])]
|
||||
items += [(base, k, x) for k, x in its if x]
|
||||
base = (
|
||||
name,
|
||||
topic_index,
|
||||
topic["start_s"],
|
||||
report_json["meeting_title"],
|
||||
report_json["date"],
|
||||
topic["title"],
|
||||
slugify(report._head(topic_index, topic), "-"),
|
||||
)
|
||||
topic_items = [("topic", _topic_text(topic, False))] + [
|
||||
("decision", decision) for decision in topic.get("decisions", [])
|
||||
]
|
||||
topic_items += [
|
||||
(
|
||||
"action",
|
||||
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key)),
|
||||
)
|
||||
for action in topic.get("actions", [])
|
||||
]
|
||||
topic_items += [("open_question", question) for question in topic.get("open_questions", [])]
|
||||
items += [(base, kind, text) for kind, text in topic_items if text]
|
||||
# Nothing to index: clear the old rows for this meeting.
|
||||
if not items: db.replace_memory(name, []); return
|
||||
if not items:
|
||||
db.replace_memory(name, [])
|
||||
return
|
||||
# Prefix the title so each item's vector carries its topic context.
|
||||
V = embed([f"{b[5]}: {x}" for b, _, x in items])
|
||||
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)])
|
||||
vectors = embed([f"{base[5]}: {text}" for base, _, text in items])
|
||||
db.replace_memory(
|
||||
name,
|
||||
[
|
||||
(*base[:2], kind, *base[2:], text, vector.tobytes())
|
||||
for (base, kind, text), vector in zip(items, vectors, strict=False)
|
||||
],
|
||||
)
|
||||
print(f"memory: indexed {len(items)} items")
|
||||
|
||||
|
||||
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, text.
|
||||
def _prev_line(n, r): return f"[{n}] {r['date']} «{r['meeting']}» — {r['topic']} ({r['kind']}): {r['text']}"
|
||||
def _prev_line(number, row):
|
||||
return f"[{number}] {row['date']} «{row['meeting']}» — {row['topic']} ({row['kind']}): {row['text']}"
|
||||
|
||||
|
||||
# Link this meeting's topics to earlier meetings; results go into report.json.
|
||||
def _link(name):
|
||||
rep = report._load(name, "report.json", None)
|
||||
if rep is None: return
|
||||
named_rep, _ = report.named(name, rep)
|
||||
report_json = report._load(name, "report.json", None)
|
||||
if report_json is None:
|
||||
return
|
||||
named_report, _ = report.named(name, report_json)
|
||||
# Stamp of this meeting, from its folder name.
|
||||
cur = _stamp(name)
|
||||
current_stamp = _stamp(name)
|
||||
# Only strictly earlier meetings; stamps sort lexicographically.
|
||||
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur)
|
||||
rows, matrix = _rows(
|
||||
lambda row: current_stamp and _stamp(row["name"]) and _stamp(row["name"]) < current_stamp
|
||||
)
|
||||
# Clear old links so re-running the step does not accumulate them.
|
||||
for t in rep["topics"]: t["previous"] = []
|
||||
for topic in report_json["topics"]:
|
||||
topic["previous"] = []
|
||||
if rows:
|
||||
# Query vectors: each current topic as title + content.
|
||||
Q = embed([_topic_text(t) for t in named_rep["topics"]])
|
||||
query_vectors = embed([_topic_text(topic) for topic in named_report["topics"]])
|
||||
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
|
||||
S = Q @ M.T
|
||||
for t, nt, s in zip(rep["topics"], named_rep["topics"], S):
|
||||
similarity = query_vectors @ matrix.T
|
||||
for topic, named_topic, similarities in zip(
|
||||
report_json["topics"], named_report["topics"], similarity, strict=False
|
||||
):
|
||||
# Best K_TOPIC candidates above the MEM_MIN similarity threshold.
|
||||
top = [j for j in np.argsort(-s)[:K_TOPIC] if s[j] >= MEM_MIN]
|
||||
if not top: continue
|
||||
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", []))
|
||||
top = [
|
||||
index
|
||||
for index in np.argsort(-similarities)[:K_TOPIC]
|
||||
if similarities[index] >= MEM_MIN
|
||||
]
|
||||
if not top:
|
||||
continue
|
||||
actions = "; ".join(
|
||||
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key))
|
||||
for action in named_topic.get("actions", [])
|
||||
)
|
||||
# Prompt: current topic, then numbered earlier excerpts the model may cite as [n].
|
||||
user = (f"ARGOMENTO: {nt['title']}\nSINTESI: {' '.join(_txt(x) for x in nt.get('summary', []))}\nDECISIONI: {'; '.join(nt.get('decisions', []))}\n"
|
||||
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n"
|
||||
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1)))
|
||||
user = (
|
||||
f"ARGOMENTO: {named_topic['title']}\nSINTESI: {' '.join(_summary_text(item) for item in named_topic.get('summary', []))}\nDECISIONI: {'; '.join(named_topic.get('decisions', []))}\n"
|
||||
f"AZIONI: {actions}\nDOMANDE APERTE: {'; '.join(named_topic.get('open_questions', []))}\n\nPRECEDENTI:\n"
|
||||
+ "\n".join(_prev_line(number, rows[index]) for number, index in enumerate(top, 1))
|
||||
)
|
||||
# report.chat returns parsed JSON or None; None -> no links.
|
||||
r = report.chat(SYS_M, user, 1500) or {}
|
||||
response = report.chat(SYS_M, user, 1500) or {}
|
||||
# Cap at 4 links per topic (matches the prompt).
|
||||
for l in (r.get("links") or [])[:4]:
|
||||
for link in (response.get("links") or [])[:4]:
|
||||
# Validate LLM output: ref in range, known status, non-empty text.
|
||||
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip()
|
||||
except (KeyError, TypeError, ValueError): continue
|
||||
if 1 <= ref <= len(top) and st in STATUSES and tx:
|
||||
p = rows[top[ref - 1]]
|
||||
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"],
|
||||
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]})
|
||||
try:
|
||||
ref, status, text = int(link["ref"]), link["status"], str(link["text"]).strip()
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if 1 <= ref <= len(top) and status in STATUSES and text:
|
||||
previous = rows[top[ref - 1]]
|
||||
topic["previous"].append(
|
||||
{
|
||||
"text": text,
|
||||
"status": status,
|
||||
"name": previous["name"],
|
||||
"meeting": previous["meeting"],
|
||||
"date": previous["date"],
|
||||
"topic": previous["topic"],
|
||||
"anchor": previous["anchor"],
|
||||
"t": previous["t"],
|
||||
}
|
||||
)
|
||||
# Write links into report.json; run() re-renders from it.
|
||||
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
(db.out_dir(name) / "report.json").write_text(
|
||||
json.dumps(report_json, ensure_ascii=False, indent=1), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def run(name, link=True):
|
||||
@@ -143,27 +234,55 @@ def run(name, link=True):
|
||||
# Embedder lives for linking and indexing; its log sits with the meeting logs.
|
||||
with embedder(db.logs(name) / "embed.log"):
|
||||
if link:
|
||||
try: _link(name)
|
||||
except Exception as e: print("memory link skipped:", repr(e))
|
||||
try:
|
||||
_link(name)
|
||||
except Exception as error:
|
||||
print("memory link skipped:", repr(error))
|
||||
index(name)
|
||||
except Exception as e: print("memory index skipped:", repr(e))
|
||||
except Exception as error:
|
||||
print("memory index skipped:", repr(error))
|
||||
# Render even when the memory steps failed.
|
||||
report.render(name)
|
||||
|
||||
|
||||
# Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n].
|
||||
# Generator: first {"sources": [...]}, then {"t": text delta} events as the model writes.
|
||||
def ask_stream(q):
|
||||
def ask_stream(question):
|
||||
# Cosine search over the normalized matrix; keep the best K_ASK excerpts.
|
||||
rows, M = _rows(lambda r: True)
|
||||
if not rows: yield {"sources": []}; yield {"t": "Nessuna riunione indicizzata."}; return
|
||||
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK]
|
||||
rs = [rows[j] for j in top]
|
||||
yield {"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]}
|
||||
body = {"temperature": 0.2, "max_tokens": 1500, "chat_template_kwargs": {"enable_thinking": False},
|
||||
"messages": [{"role": "system", "content": SYS_ASK},
|
||||
{"role": "user", "content": f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1))}]}
|
||||
for d in llama.stream(body, 1800): yield {"t": d}
|
||||
rows, matrix = _rows(lambda row: True)
|
||||
if not rows:
|
||||
yield {"sources": []}
|
||||
yield {"t": "Nessuna riunione indicizzata."}
|
||||
return
|
||||
top = np.argsort(-(matrix @ embed([question])[0]))[:K_ASK]
|
||||
selected = [rows[index] for index in top]
|
||||
yield {
|
||||
"sources": [
|
||||
{
|
||||
"n": number,
|
||||
**{
|
||||
key: row[key]
|
||||
for key in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")
|
||||
},
|
||||
}
|
||||
for number, row in enumerate(selected, 1)
|
||||
]
|
||||
}
|
||||
body = {
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 1500,
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
"messages": [
|
||||
{"role": "system", "content": SYS_ASK},
|
||||
{
|
||||
"role": "user",
|
||||
"content": f"DOMANDA: {question}\n\nESTRATTI:\n"
|
||||
+ "\n".join(_prev_line(number, row) for number, row in enumerate(selected, 1)),
|
||||
},
|
||||
],
|
||||
}
|
||||
for delta in llama.stream(body, 1800):
|
||||
yield {"t": delta}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -172,4 +291,5 @@ if __name__ == "__main__":
|
||||
# CLI: rebuild the memory index for every meeting that has a report.json.
|
||||
if "--reindex" in sys.argv:
|
||||
with embedder(db.GLOBAL / "embed.log"):
|
||||
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
|
||||
for path in sorted(db.OUT.glob("*/report.json")):
|
||||
index(path.parent.name)
|
||||
|
||||
Reference in New Issue
Block a user