298 lines
12 KiB
Python
298 lines
12 KiB
Python
"""Find related Confluence/Jira docs for a meeting via twg; writes out/<name>/docs.json. Never fails the flow."""
|
|
|
|
import contextlib
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
|
|
# report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address.
|
|
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")
|
|
# Prompt: 4 short search queries (3-6 words) from the meeting description.
|
|
SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.'
|
|
# Prompt: relevance score 0-3 for each numbered candidate doc.
|
|
SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).'
|
|
# Full Jira key match (anchored).
|
|
KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$")
|
|
# Confluence checkbox line ("* [ ] text" or "* [x] text"); group 1 = text. Used to harvest people names.
|
|
PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M)
|
|
|
|
|
|
# Run twg. Returns parsed JSON for "-o json" calls, else stdout (None on failure).
|
|
# 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 = {
|
|
key: value
|
|
for key, value in os.environ.items()
|
|
if key not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")
|
|
}
|
|
for attempt in range(2):
|
|
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(
|
|
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 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:
|
|
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 (
|
|
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}
|
|
|
|
|
|
# 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")
|
|
# Per-meeting output directory.
|
|
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((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(
|
|
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(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 += [
|
|
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({query.lower(): query for query in reversed(queries)}.values())[::-1]
|
|
|
|
# Candidates keyed by URL across all queries.
|
|
candidates = {}
|
|
for query in queries:
|
|
# Confluence: up to 6 hits per query; Jira: up to 4.
|
|
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.
|
|
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.
|
|
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.
|
|
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 = [
|
|
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 = {
|
|
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]:
|
|
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 entry in items:
|
|
if entry["key"] in known:
|
|
entry["title"], entry["status"] = known[entry["key"]]
|
|
# Add mentioned Jira tickets not already in items.
|
|
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 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 = {}
|
|
unscored = [entry for entry in items if not entry["mentioned"]]
|
|
# Only score non-mentioned items, if any.
|
|
if unscored:
|
|
# Numbered candidate list appended to the meeting description.
|
|
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 index, entry in enumerate(unscored):
|
|
entry["score"] = scores.get(index, 0)
|
|
# Mentioned items score 3 unless already set.
|
|
for entry in items:
|
|
entry.setdefault("score", 3 if entry["mentioned"] else 0)
|
|
# Keep mentioned items plus those scored >= 2, best first.
|
|
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.
|
|
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 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 = 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 index, entry in enumerate(keep):
|
|
entry["i"] = index
|
|
# People names: checkbox lines in bodies, multi-word only, deduped.
|
|
people = []
|
|
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:
|
|
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"
|
|
)
|