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
+221 -79
View File
@@ -1,7 +1,16 @@
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow."""
import json, os, re, shutil, subprocess
import contextlib
import json
import os
import re
import shutil
import subprocess
# report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address.
import db, llama, report
import db
import llama
import report
# twg CLI: from PATH, else the default per-user install location.
TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe")
@@ -19,21 +28,45 @@ PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
# Retries once through the proxy when the failure looks like a network/proxy error.
def _twg(*args, timeout=120):
# Child env without Python home vars that would confuse twg.
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
env = {
key: value
for key, value in os.environ.items()
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
}
for attempt in range(2):
r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
result = subprocess.run(
[TWG, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
env=env,
)
# JSON mode: parse stdout; twg may instead print a YAML envelope pointing at a spooled file.
if "-o" in args and "json" in args:
try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON
except ValueError: out = None
try:
return json.loads(
result.stdout
) # rovo exits 3 on partial results but still prints JSON
except ValueError:
output = None
# twg >= 1.3 spools large results to a file and prints a YAML envelope: output_files: stdout: "<path>"
if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)):
try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError): pass
if match := re.search(r'^\s*stdout:\s*"(.+?\.json)"', result.stdout, re.M):
try:
return json.loads(open(match[1].replace("\\\\", "\\"), encoding="utf-8").read())
except (OSError, ValueError):
pass
# Plain-text mode: stdout only on success.
else: out = r.stdout if r.returncode == 0 else None
else:
output = result.stdout if result.returncode == 0 else None
# Stop unless this is the first attempt and stderr looks like a network/proxy error.
if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out
if (
output is not None
or attempt
or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", result.stderr)
):
return output
# Second attempt goes through the proxy.
env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY}
@@ -41,115 +74,224 @@ def _twg(*args, timeout=120):
# Gather candidate docs for a meeting: queries, Confluence/Jira search, Jira key lookups, LLM relevance scoring.
# Returns the docs.json payload; raises on hard failure (run() catches it).
def _run(name):
if not os.path.exists(TWG): raise FileNotFoundError("twg not found")
if not os.path.exists(TWG):
raise FileNotFoundError("twg not found")
# Per-meeting output directory.
d = db.out_dir(name)
meta = [json.loads(e["text"]) for e in db.events(name, "meta") if e["who_key"] != "video"] # Teams topic only, never a shot guess
meeting_dir = db.out_dir(name)
meta = [
json.loads(entry["text"])
for entry in db.events(name, "meta")
if entry["who_key"] != "video"
] # Teams topic only, never a shot guess
title = (meta[-1].get("title") or "") if meta else ""
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else []
shots = (
json.loads((meeting_dir / "shots.json").read_text(encoding="utf-8"))
if (meeting_dir / "shots.json").exists()
else []
)
glossary = (
json.loads((meeting_dir / "glossary.json").read_text(encoding="utf-8"))
if (meeting_dir / "glossary.json").exists()
else []
)
from shots import CONTENT_KINDS
# Titles of lead content screens: deduped, max 30.
screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30]
tx = db.out_dir(name) / "transcript.txt"
txt = tx.read_text(encoding="utf-8") if tx.exists() else ""
screens = list(
dict.fromkeys(
shot["title"]
for shot in shots
if shot.get("lead") and shot["kind"] in CONTENT_KINDS and shot.get("title")
)
)[:30]
transcript_file = db.out_dir(name) / "transcript.txt"
transcript = transcript_file.read_text(encoding="utf-8") if transcript_file.exists() else ""
# Meeting description for the LLM: title, screen titles, glossary, first 800 words of transcript.
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}"
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(glossary[:40])}\nTrascrizione (inizio): {' '.join(transcript.split()[:800])}"
# Title is always a query; add up to 4 LLM-generated ones.
queries = [title] if title else []
queries += [q for q in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4] if isinstance(q, str)]
queries += [
query
for query in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4]
if isinstance(query, str)
]
# Case-insensitive de-dup of queries.
queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1]
queries = list({query.lower(): query for query in reversed(queries)}.values())[::-1]
# Candidates keyed by URL across all queries.
cand = {}
for q in queries:
candidates = {}
for query in queries:
# Confluence: up to 6 hits per query; Jira: up to 4.
for app, lim in (("confluence", 6), ("jira", 4)):
for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []:
for source_app, limit in (("confluence", 6), ("jira", 4)):
for item in (
_twg(
"rovo",
"search",
query,
"--app",
source_app,
"--limit",
str(limit),
"-o",
"json",
)
or {}
).get("items") or []:
# Skip results without a URL or already seen.
u = it.get("url")
if not u or u in cand: continue
url = item.get("url")
if not url or url in candidates:
continue
# Jira key from /browse/KEY-N URLs; Confluence page id from /pages/ID URLs.
jk = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", u); cid = re.search(r"/pages/(\d+)", u)
cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None,
"title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False}
items = list(cand.values())
jira_match = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", url)
confluence_match = re.search(r"/pages/(\d+)", url)
candidates[url] = {
"source": "jira" if "/browse/" in url else "confluence",
"key": jira_match[1] if jira_match else None,
"id": confluence_match[1] if confluence_match else None,
"title": item.get("title") or "",
"url": url,
"status": None,
"snippet": (item.get("snippet") or "")[:400],
"mentioned": False,
}
items = list(candidates.values())
# Text to scan for ticket keys: transcript plus shot OCR text.
blob = [txt] + [s.get("text") or "" for s in shots]
text_blocks = [transcript] + [shot.get("text") or "" for shot in shots]
# Ticket keys found in the content (valid format), then keys already on candidates.
keys = [k for k in dict.fromkeys(m for b in blob for m in report.TICKET.findall(b)) if KEY.match(k)]
keys += [k for k in (e["key"] for e in items) if k and k not in keys]
keys = [
key
for key in dict.fromkeys(
ticket for block in text_blocks for ticket in report.TICKET.findall(block)
)
if KEY.match(key)
]
keys += [key for key in (entry["key"] for entry in items) if key and key not in keys]
# Keys literally mentioned in the meeting content.
mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)})
mentioned = {
key
for key in keys
if key in {ticket for block in text_blocks for ticket in report.TICKET.findall(block)}
}
# Jira lookup: summary + status for keys, one batch of up to 26.
known = {}
# Only call twg when there are keys.
if keys[:20 + 6]:
r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for it in (r.get("data") or {}).get("items") or []:
if it.get("ok") and it.get("data"):
x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "")
if keys[: 20 + 6]:
response = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {}
for item in (response.get("data") or {}).get("items") or []:
if item.get("ok") and item.get("data"):
data = item["data"]
known[data["key"]] = (
data.get("summary") or "",
(data.get("status") or {}).get("name") or "",
)
# Apply Jira summary/status to candidates that have a key.
for e in items:
if e["key"] in known: e["title"], e["status"] = known[e["key"]]
for entry in items:
if entry["key"] in known:
entry["title"], entry["status"] = known[entry["key"]]
# Add mentioned Jira tickets not already in items.
have = {e["key"] for e in items if e["key"]}
for k in keys:
if k in known and k in mentioned and k not in have:
items.append({"source": "jira", "key": k, "id": None, "title": known[k][0], "url": f"{report.JIRA_BROWSE}/{k}", "status": known[k][1], "snippet": "", "mentioned": True})
have = {entry["key"] for entry in items if entry["key"]}
for key in keys:
if key in known and key in mentioned and key not in have:
items.append(
{
"source": "jira",
"key": key,
"id": None,
"title": known[key][0],
"url": f"{report.JIRA_BROWSE}/{key}",
"status": known[key][1],
"snippet": "",
"mentioned": True,
}
)
# Flag items mentioned in the meeting and resolved in Jira.
for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known)
for entry in items:
entry["mentioned"] = entry["mentioned"] or bool(
entry["key"] in mentioned and entry["key"] in known
)
# Relevance: LLM scores non-mentioned items; missing score = 0.
scores = {}
rel = [e for e in items if not e["mentioned"]]
unscored = [entry for entry in items if not entry["mentioned"]]
# Only score non-mentioned items, if any.
if rel:
if unscored:
# Numbered candidate list appended to the meeting description.
u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel))
# Score indices refer to positions in rel.
for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []:
try: scores[int(s["i"])] = int(s["score"])
except (KeyError, TypeError, ValueError): pass
prompt = (
desc
+ "\n\nDOCUMENTI:\n"
+ "\n".join(
f"[{index}] {entry['title']} — {entry['snippet'][:300]}"
for index, entry in enumerate(unscored)
)
)
# Score indices refer to positions in unscored.
for score_row in (report.chat(SYS_R, prompt, 800) or {}).get("scores") or []:
with contextlib.suppress(KeyError, TypeError, ValueError):
scores[int(score_row["i"])] = int(score_row["score"])
# Non-mentioned items keep the LLM score (0 if missing).
for i, e in enumerate(rel): e["score"] = scores.get(i, 0)
for index, entry in enumerate(unscored):
entry["score"] = scores.get(index, 0)
# Mentioned items score 3 unless already set.
for e in items:
e.setdefault("score", 3 if e["mentioned"] else 0)
for entry in items:
entry.setdefault("score", 3 if entry["mentioned"] else 0)
# Keep mentioned items plus those scored >= 2, best first.
keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"])
keep = sorted(
[entry for entry in items if entry["mentioned"] or entry["score"] >= 2],
key=lambda entry: -entry["score"],
)
# Cap per source: 8 Confluence; Jira: up to 6 non-mentioned plus all mentioned.
conf = [e for e in keep if e["source"] == "confluence"][:8]
jira = [e for e in keep if e["source"] == "jira" and not e["mentioned"]][:6] + [e for e in keep if e["mentioned"]]
keep = conf + jira
confluence_items = [entry for entry in keep if entry["source"] == "confluence"][:8]
jira_items = [entry for entry in keep if entry["source"] == "jira" and not entry["mentioned"]][
:6
] + [entry for entry in keep if entry["mentioned"]]
keep = confluence_items + jira_items
# Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body.
for e in keep:
if e["source"] == "confluence" and e["id"]:
b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or ""
for entry in keep:
if entry["source"] == "confluence" and entry["id"]:
body = (
_twg(
"confluence",
"content",
"get",
entry["id"],
"--detail",
"full",
"--format",
"md",
"--body-only",
)
or ""
)
# twg prefixes the body with a "Content loaded." banner line; drop it.
lines = b.splitlines()
if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:]
e["body"] = "\n".join(lines)[:6000]
else: e["body"] = f"{e['key']} {e['title']} ({e['status']})"
lines = body.splitlines()
if lines and lines[0].strip() == "+ Content loaded.":
lines = lines[1:]
entry["body"] = "\n".join(lines)[:6000]
else:
entry["body"] = f"{entry['key']} {entry['title']} ({entry['status']})"
# Stable index used to reference docs from report.py.
for i, e in enumerate(keep): e["i"] = i
for index, entry in enumerate(keep):
entry["i"] = index
# People names: checkbox lines in bodies, multi-word only, deduped.
people = []
for e in keep:
for m in PEOPLE.finditer(e["body"]):
n = db.norm_name(m[1])
if " " in n and n not in people: people.append(n)
for entry in keep:
for match in PEOPLE.finditer(entry["body"]):
person = db.norm_name(match[1])
if " " in person and person not in people:
people.append(person)
return {"queries": queries, "items": keep, "people": people, "error": None}
# Entry point. Never fails the flow: errors are recorded in docs.json (error field) instead of raised.
def run(name):
try: out = _run(name)
except Exception as e:
print("docs failed:", repr(e), flush=True)
out = {"queries": [], "items": [], "people": [], "error": repr(e)[:300]}
(db.out_dir(name) / "docs.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
try:
output = _run(name)
except Exception as error:
print("docs failed:", repr(error), flush=True)
output = {"queries": [], "items": [], "people": [], "error": repr(error)[:300]}
(db.out_dir(name) / "docs.json").write_text(
json.dumps(output, ensure_ascii=False, indent=1), encoding="utf-8"
)