Files
teams-whisper/app/review.py
T

206 lines
8.9 KiB
Python

# /// script
# dependencies = []
# ///
"""Quality gate for meeting reports. uv run --script review.py <name> [<name>...]; exit 1 if any fails. No network/LLM."""
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 _sim
from shots import CONTENT_KINDS
# Stopwords used by english() to tell English from Italian text.
ENG = {"the", "and", "of", "with", "is", "shows", "showing", "screenshot", "meeting", "displays"}
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(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(path):
data = path.read_bytes()
index = 2
while index < len(data):
# Skip non-marker bytes.
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
# SOF0-SOF2: frame header holds height, then width (2 bytes each).
if marker in (0xC0, 0xC1, 0xC2):
return struct.unpack(">H", data[index + 7 : index + 9])[0]
# Jump over this segment using its length field.
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):
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).
def fail(code, detail):
return fails.append(f"FAIL {code} {str(detail)[:200]}")
# R1: no generic 'Speaker N' labels left in the report.
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.
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 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).
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}")
shot_by_name = {}
# Index shots by file name and by cropped view name, for R4.
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 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/([^)]+)\)", 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((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(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).
section = re.search(r"## Partecipanti\n(.*?)(?=\n## )", markdown_text, re.S)
people = []
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 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 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.
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.
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.
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 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 markdown_text:
fail("R9", "missing Documentazione correlata")
urls = {item["url"] for item in items}
# Citation icon links in the markdown.
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_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(encoded)) <= 5000:
fail("R10", "tiny image")
# R11: transcript must not be included in the report.
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 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}] {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(name) for name in sys.argv[1:]) else 1)