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
+137 -80
View File
@@ -2,10 +2,17 @@
# dependencies = []
# ///
"""Quality gate for meeting reports. uv run --script review.py <name> [<name>...]; exit 1 if any fails. No network/LLM."""
import base64, json, re, struct, sys
import base64
import json
import re
import struct
import sys
import db
# Shared helpers from report.py: ticket regex, key normaliser, name similarity.
from report import TICKET, _key, _sim
from report import _sim
from shots import CONTENT_KINDS
# Stopwords used by english() to tell English from Italian text.
@@ -14,135 +21,185 @@ ITA = {"il", "la", "di", "che", "con", "della", "viene", "mostra", "sono", "per"
# True if text is mostly English: at least 3 English stopwords and more than Italian ones.
def english(s):
w = re.findall(r"[a-zà-ú]+", str(s).lower())
e, i = sum(x in ENG for x in w), sum(x in ITA for x in w)
return e >= 3 and e > i
def english(text):
words = re.findall(r"[a-zà-ú]+", str(text).lower())
english_count, italian_count = (
sum(word in ENG for word in words),
sum(word in ITA for word in words),
)
return english_count >= 3 and english_count > italian_count
# Read image width from the JPEG SOF marker (0 if not found).
def jpeg_w(p):
b = p.read_bytes(); i = 2
while i < len(b):
def jpeg_w(path):
data = path.read_bytes()
index = 2
while index < len(data):
# Skip non-marker bytes.
if b[i] != 0xFF: i += 1; continue
m = b[i + 1]
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
# SOF0-SOF2: frame header holds height, then width (2 bytes each).
if m in (0xC0, 0xC1, 0xC2): return struct.unpack(">H", b[i + 7:i + 9])[0]
if marker in (0xC0, 0xC1, 0xC2):
return struct.unpack(">H", data[index + 7 : index + 9])[0]
# Jump over this segment using its length field.
i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
index += 2 + struct.unpack(">H", data[index + 2 : index + 4])[0]
return 0
# Run all quality rules on one meeting's outputs; print failures; True if none.
def review(name):
d = db.out_dir(name)
rep = json.loads((d / "report.json").read_text(encoding="utf-8"))
md = (d / "report.md").read_text(encoding="utf-8")
html = (d / "report.html").read_text(encoding="utf-8")
shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else []
docs = json.loads((d / "docs.json").read_text(encoding="utf-8")) if (d / "docs.json").exists() else None
out_dir = db.out_dir(name)
report = json.loads((out_dir / "report.json").read_text(encoding="utf-8"))
markdown_text = (out_dir / "report.md").read_text(encoding="utf-8")
html_text = (out_dir / "report.html").read_text(encoding="utf-8")
shots = (
json.loads((out_dir / "shots.json").read_text(encoding="utf-8"))
if (out_dir / "shots.json").exists()
else []
)
docs = (
json.loads((out_dir / "docs.json").read_text(encoding="utf-8"))
if (out_dir / "docs.json").exists()
else None
)
items = (docs or {}).get("items", [])
fails = []
# Record a failure with its rule code (R1-R12).
F = lambda code, detail: fails.append(f"FAIL {code} {str(detail)[:200]}")
def fail(code, detail):
return fails.append(f"FAIL {code} {str(detail)[:200]}")
# R1: no generic 'Speaker N' labels left in the report.
for m in re.finditer(r"\bSpeaker \d+\b", md): F("R1", md[max(0, m.start() - 40):m.end() + 40].replace("\n", " "))
for match in re.finditer(r"\bSpeaker \d+\b", markdown_text):
fail("R1", markdown_text[max(0, match.start() - 40) : match.end() + 40].replace("\n", " "))
# R2: topic count between dur/900 and dur/150 (min 3 / 4), so long calls get more topics.
T, dur = rep["topics"], rep["duration_s"]
if not max(3, dur / 900) <= len(T) <= max(4, dur / 150): F("R2", f"{len(T)} topics for {dur / 60:.0f} min")
topics, duration = report["topics"], report["duration_s"]
if not max(3, duration / 900) <= len(topics) <= max(4, duration / 150):
fail("R2", f"{len(topics)} topics for {duration / 60:.0f} min")
# R2: every topic except the last must span at least 2 min.
for t in T[:-1]:
if t["end_s"] - t["start_s"] < 120: F("R2", f"short topic {t['title']} {t['end_s'] - t['start_s']}s")
for t in T:
for x in t["shown"]:
for topic in topics[:-1]:
if topic["end_s"] - topic["start_s"] < 120:
fail("R2", f"short topic {topic['title']} {topic['end_s'] - topic['start_s']}s")
for topic in topics:
for shown_time in topic["shown"]:
# R3: each shown timestamp must fall inside the topic span (+/-30 s).
m = re.search(r"(\d\d):(\d\d)", x)
if not m or not t["start_s"] - 30 <= int(m[1]) * 60 + int(m[2]) <= t["end_s"] + 30: F("R3", f"{t['title']}: {x}")
match = re.search(r"(\d\d):(\d\d)", shown_time)
if (
not match
or not topic["start_s"] - 30
<= int(match[1]) * 60 + int(match[2])
<= topic["end_s"] + 30
):
fail("R3", f"{topic['title']}: {shown_time}")
byfile = {}
shot_by_name = {}
# Index shots by file name and by cropped view name, for R4.
for s in shots: byfile[s["file"]] = byfile[s.get("view") or s["file"]] = s
for shot in shots:
shot_by_name[shot["file"]] = shot_by_name[shot.get("view") or shot["file"]] = shot
# R4: at most 2 images per section.
for sec in re.split(r"\n(?=## )", md):
imgs = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", sec)
if len(imgs) > 2: F("R4", f">2 images in {sec[:40]!r}")
for section in re.split(r"\n(?=## )", markdown_text):
images = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", section)
if len(images) > 2:
fail("R4", f">2 images in {section[:40]!r}")
# R4: every image used must be a content screen (CONTENT_KINDS).
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", md)
for f in used:
if byfile.get(f, {}).get("kind") not in CONTENT_KINDS: F("R4", f"{f} kind {byfile.get(f, {}).get('kind')}")
used = re.findall(r"!\[[^\]]*\]\(shots/([^)]+)\)", markdown_text)
for file_name in used:
if shot_by_name.get(file_name, {}).get("kind") not in CONTENT_KINDS:
fail("R4", f"{file_name} kind {shot_by_name.get(file_name, {}).get('kind')}")
# R4: if cropping was applied, every image must be a cropped view_ file.
if any((s.get("view") or "").startswith("view_") for s in shots):
for f in used:
if not f.startswith("view_"): F("R4", f"uncropped image {f}")
if any((shot.get("view") or "").startswith("view_") for shot in shots):
for file_name in used:
if not file_name.startswith("view_"):
fail("R4", f"uncropped image {file_name}")
# R5: collect all prose fields to check for English.
texts = list(rep["tldr"])
for t in T:
texts += [x["text"] if isinstance(x, dict) else x for x in t["summary"]] + [x["text"] for x in t.get("from_docs", [])]
texts += [s.get("summary") or "" for s in t["shots"]]
for x in texts:
if english(x): F("R5", x)
texts = list(report["tldr"])
for topic in topics:
texts += [item["text"] if isinstance(item, dict) else item for item in topic["summary"]] + [
item["text"] for item in topic.get("from_docs", [])
]
texts += [shot.get("summary") or "" for shot in topic["shots"]]
for text in texts:
if english(text):
fail("R5", text)
# R6: read the participants section (table rows or comma list).
sec = re.search(r"## Partecipanti\n(.*?)(?=\n## )", md, re.S)
section = re.search(r"## Partecipanti\n(.*?)(?=\n## )", markdown_text, re.S)
people = []
for l in (sec[1].splitlines() if sec else []):
if l.startswith("|"):
c = l.split("|")[1].strip()
if c not in ("Partecipante", "") and not c.startswith("-"): people.append(c)
elif l.strip() and not l.startswith("*"): people += [x.strip() for x in l.split(",")]
for line in section[1].splitlines() if section else []:
if line.startswith("|"):
cell = line.split("|")[1].strip()
if cell not in ("Partecipante", "") and not cell.startswith("-"):
people.append(cell)
elif line.strip() and not line.startswith("*"):
people += [name_part.strip() for name_part in line.split(",")]
# R6: no initials or truncated names.
for p in people:
if re.fullmatch(r"[A-Z]{1,3}", p) or "..." in p or "…" in p: F("R6", f"initials/truncated {p}")
for person in people:
if re.fullmatch(r"[A-Z]{1,3}", person) or "..." in person or "…" in person:
fail("R6", f"initials/truncated {person}")
# R6: no two participants that look like the same person (similarity >= 0.82).
for i, a in enumerate(people):
for b in people[i + 1:]:
if _sim(a, b) >= 0.82: F("R6", f"{a} ~ {b}")
for index, first in enumerate(people):
for second in people[index + 1 :]:
if _sim(first, second) >= 0.82:
fail("R6", f"{first} ~ {second}")
# R7: share segments must be >= 20 s and not split by a gap of <= 60 s.
S = rep["shares"]
for s in S:
if s["end"] - s["start"] < 20: F("R7", f"short share {s}")
for a, b in zip(S, S[1:]):
if a["who"] == b["who"] and b["start"] - a["end"] <= 60: F("R7", f"mergeable {a['who']} {a['end']}->{b['start']}")
shares = report["shares"]
for share in shares:
if share["end"] - share["start"] < 20:
fail("R7", f"short share {share}")
for previous, current in zip(shares, shares[1:], strict=False):
if previous["who"] == current["who"] and current["start"] - previous["end"] <= 60:
fail("R7", f"mergeable {previous['who']} {previous['end']}->{current['start']}")
# R8: ticket keys from the report's Ticket section.
rs = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", md, re.S)
ticket_section = re.search(r"\*\*Ticket\*\*\n\n(.*?)(?=\n\n|\Z)", markdown_text, re.S)
# R8: allowed keys: Jira-verified when docs ran, else keys from references.
ok = ({x["key"] for x in items if x["source"] == "jira" and x.get("mentioned")} if docs is not None
else {x["key"] for x in rep["references"]["tickets"]})
for k in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", rs[1] if rs else ""):
if k not in ok: F("R8", f"ticket {k}")
allowed_keys = (
{item["key"] for item in items if item["source"] == "jira" and item.get("mentioned")}
if docs is not None
else {item["key"] for item in report["references"]["tickets"]}
)
for key in re.findall(r"\[([A-Z][A-Z0-9]+-\d+)\]", ticket_section[1] if ticket_section else ""):
if key not in allowed_keys:
fail("R8", f"ticket {key}")
# R8: no raw number or e-mail lists.
if "Numeri a schermo" in md or "**Email**" in md: F("R8", "numbers/email lists present")
if "Numeri a schermo" in markdown_text or "**Email**" in markdown_text:
fail("R8", "numbers/email lists present")
# R9: docs section must exist and citation links must point to fetched docs.
if items:
if "## Documentazione correlata" not in md: F("R9", "missing Documentazione correlata")
urls = {x["url"] for x in items}
if "## Documentazione correlata" not in markdown_text:
fail("R9", "missing Documentazione correlata")
urls = {item["url"] for item in items}
# Citation icon links in the markdown.
for u in re.findall(r"\[📄\]\(([^ )]+)", md):
if u not in urls: F("R9", f"citation url not in docs {u}")
for url in re.findall(r"\[📄\]\(([^ )]+)", markdown_text):
if url not in urls:
fail("R9", f"citation url not in docs {url}")
# R10: HTML must embed images, not reference shots/ paths.
if 'src="shots/' in html: F("R10", "unembedded image")
for b in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html):
if 'src="shots/' in html_text:
fail("R10", "unembedded image")
for encoded in re.findall(r"data:image/jpeg;base64,([A-Za-z0-9+/=]+)", html_text):
# R10: an embedded image under 5000 bytes is a placeholder.
if len(base64.b64decode(b)) <= 5000: F("R10", "tiny image")
if len(base64.b64decode(encoded)) <= 5000:
fail("R10", "tiny image")
# R11: transcript must not be included in the report.
if "## Trascrizione" in md: F("R11", "transcript present")
for f in set(used):
if "## Trascrizione" in markdown_text:
fail("R11", "transcript present")
for file_name in set(used):
# R12: cropped views must be at least 600 px wide.
if f.startswith("view_") and jpeg_w(d / "shots" / f) < 600: F("R12", f"{f} narrow {jpeg_w(d / 'shots' / f)}px")
if file_name.startswith("view_") and jpeg_w(out_dir / "shots" / file_name) < 600:
fail("R12", f"{file_name} narrow {jpeg_w(out_dir / 'shots' / file_name)}px")
print("\n".join(f"[{name}] {x}" for x in fails))
print("\n".join(f"[{name}] {item}" for item in fails))
print(f"{name}: " + ("PASS" if not fails else f"{len(fails)} failures"))
return not fails
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
sys.exit(0 if all([review(n) for n in sys.argv[1:]]) else 1)
sys.exit(0 if all(review(name) for name in sys.argv[1:]) else 1)