"""Single-shot slide review bundle. Pre-computes everything the 8 read-only slide-reviewer tools used to fetch one tool-call at a time, and packs it into a single dataclass that the single-shot Slide Reviewer agent receives in its first (and only) turn. The 8 tools the agentic mode uses are pure deterministic projections of ``AuditContext`` (parsed deck + rubric + render result): * ``list_rubric_categories`` → ``rubric_full["categories"]`` * ``get_rubric_section(category)`` → ``rubric_full["sections"]`` * ``get_slide_image(slide_n)`` → ``image_b64`` / ``image_path`` * ``get_slide_text(slide_n)`` → ``slide_text`` + ``parsed_shapes`` * ``get_slide_notes(slide_n)`` → ``slide_notes`` * ``check_palette_color(hex)`` → ``palette_check`` (pre-run on every non-grayscale hex on the slide) * ``check_confidentiality_statement`` → ``confidentiality_check`` * ``find_text_markers`` → ``text_markers`` (must-flag terms) This module does NOT reimplement those checks — it reuses the same helpers the ``@function_tool`` wrappers call (``check_confidentiality_pure``, ``find_text_markers_pure`` and the pure-Python rubric / palette logic). Public API: * :class:`SlideReviewBundle` — the dataclass. * :func:`build_rubric_full` — once-per-audit rubric snapshot. * :func:`build_slide_bundle` — once-per-slide bundle. * :func:`bundle_to_prompt_payload` — JSON-safe dict suitable for prompt serialisation (omits the ``image_b64`` blob — that is sent as a separate ``input_image`` content part). """ from __future__ import annotations import base64 from dataclasses import dataclass, field from pathlib import Path from typing import Any from rubric.loader import Rubric from schemas.parsed import ParsedDeck from services.confidentiality import ConfidentialityCheck, check_confidentiality_pure from services.markers import Hit, find_text_markers_pure from services.renderer import RenderResult # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- # The fixed must-flag terms the runner already pre-scans. Mirroring them here # rather than importing from ``agents.runner`` keeps this module free of a # back-reference (and avoids an import cycle: runner imports the bundle). MUST_FLAG_TERMS: tuple[str, ...] = ("DRAFT", "TW question", "Page to be updated") # --------------------------------------------------------------------------- # Bundle dataclass # --------------------------------------------------------------------------- @dataclass class SlideReviewBundle: """All deterministic per-slide context the single-shot agent needs. The single-shot agent receives this serialised into its prompt PLUS the rendered PNG as a separate multimodal ``input_image`` content part (when the slide has been rendered). """ # --- identity --- slide_number: int # --- raw slide content (what get_slide_text / get_slide_notes returned) --- slide_text: str slide_notes: str # Compact shape metadata: each entry has shape_id, shape_type, name, EMU # bbox (left/top/width/height), and de-duped non-None font sizes + RGB # hex colors gathered from text runs. Same shape as ``ShapeMetadata`` in # ``agents.tools``. parsed_shapes: list[dict[str, Any]] = field(default_factory=list) # --- rendered image (deck-renderable; may be absent for skipped/failed) --- image_path: str | None = None image_b64: str | None = None # base64-encoded PNG bytes (no data: prefix) # --- rubric snapshot, deck-wide. Same content as the previous tools' # ``list_rubric_categories`` + ``get_rubric_section`` outputs, but # pre-flattened so the model sees the whole rubric at once. --- rubric_full: dict[str, Any] = field(default_factory=dict) # --- pre-computed deterministic checks --- # Per-color palette check for every non-grayscale hex found on the slide. # Shape: { "checks": [ {"hex": "...", "in_palette": bool}, ... ], # "allowed": [ "#RRGGBB", ... ] } palette_check: dict[str, Any] = field(default_factory=dict) # Result of services.confidentiality.check_confidentiality_pure, flattened # to a JSON-safe dict. confidentiality_check: dict[str, Any] = field(default_factory=dict) # Result of services.markers.find_text_markers_pure for the fixed # must-flag terms. List of Hit dicts. text_markers: list[dict[str, Any]] = field(default_factory=list) # --------------------------------------------------------------------------- # Rubric snapshot (cached once per audit) # --------------------------------------------------------------------------- def build_rubric_full(rubric: Rubric) -> dict[str, Any]: """Build the deck-wide rubric snapshot the agent sees in every prompt. Mirrors what ``list_rubric_categories`` + ``get_rubric_section(category)`` would have produced, walked once and folded into a single dict so the agent does not need any tool calls to consult the rubric. Returns ------- { "version": str, "categories": [str, ...], "sections": { "": [ { "rule_id": ..., "rule_text": ..., "severity_default": ..., "detection_type": ..., "examples_do": ..., "examples_dont": ..., "source_ref": ..., "metadata": { # subset — same as get_rubric_section "allowed_hex": [...]?, "canonical_text": ...? } }, ... ], ... }, "must_flag_markers": { term: { category, severity_default, title_template, rule_id }, ... } } """ categories: list[str] = [] sections: dict[str, list[dict[str, Any]]] = {} for rule in rubric.rules: if rule.category not in sections: sections[rule.category] = [] categories.append(rule.category) meta: dict[str, Any] = {} if rule.metadata: if rule.metadata.allowed_hex is not None: meta["allowed_hex"] = list(rule.metadata.allowed_hex) if rule.metadata.canonical_text is not None: meta["canonical_text"] = rule.metadata.canonical_text sections[rule.category].append( { "rule_id": rule.id, "rule_text": rule.rule_text, "severity_default": rule.severity_default, "detection_type": rule.detection_type, "examples_do": rule.examples.do if rule.examples else None, "examples_dont": rule.examples.dont if rule.examples else None, "source_ref": rule.source_ref, "metadata": meta, } ) must_flag: dict[str, dict[str, Any]] = {} for term, mf in rubric.metadata.must_flag_markers.items(): must_flag[term] = { "category": mf.category, "severity_default": mf.severity_default, "title_template": mf.title_template, "rule_id": mf.rule_id, } return { "version": rubric.version, "categories": categories, "sections": sections, "must_flag_markers": must_flag, } # --------------------------------------------------------------------------- # Helpers (pure) # --------------------------------------------------------------------------- def _slide_image_path(render_result: RenderResult, slide_n: int) -> Path | None: """Mirror of ``agents.tools._slide_image_path`` so the bundle can build without importing ``agents.tools`` (which would pull the SDK).""" idx = slide_n - 1 if render_result.skipped or render_result.render_failed: return None if idx < 0 or idx >= len(render_result.slide_paths): return None p = render_result.slide_paths[idx] if not p.exists(): return None return p def _is_grayscale(hex_str: str) -> bool: """Return True if an RGB hex string represents a pure grayscale color (R == G == B). Accepts ``"#RRGGBB"`` or ``"RRGGBB"``.""" s = hex_str.lstrip("#").upper() if len(s) != 6: return False try: r, g, b = int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16) except ValueError: return False return r == g == b def _allowed_palette(rubric: Rubric) -> list[str]: """Pull the allowed palette hex list from the rubric (or [] if absent).""" for rule in rubric.rules: if ( rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex ): return list(rule.metadata.allowed_hex) return [] def _canonical_confidentiality_text(rubric: Rubric) -> str | None: """Pull canonical confidentiality text from the rubric.""" for rule in rubric.rules: if ( rule.category == "confidentiality_statement" and rule.metadata and rule.metadata.canonical_text ): return rule.metadata.canonical_text return None def _color_in_palette(hex_str: str, allowed: list[str]) -> bool: """Replicates ``_impl_check_palette_color`` matching logic.""" norm = hex_str.lstrip("#").upper() return any(entry.lstrip("#").upper() == norm for entry in allowed) def _build_parsed_shapes(deck: ParsedDeck, slide_n: int) -> list[dict[str, Any]]: """Mirror of ``_impl_get_slide_text``'s shape projection — JSON-safe dicts. Same fields as ``agents.tools.ShapeMetadata`` so the agent sees a structurally identical view to the agentic-mode tool output. """ slide = deck.slides[slide_n - 1] out: list[dict[str, Any]] = [] for sh in slide.shapes: font_sizes = sorted( {r.font_size_pt for r in sh.runs if r.font_size_pt is not None} ) colors = sorted( {r.color_rgb for r in sh.runs if r.color_rgb is not None} ) out.append( { "shape_id": sh.shape_id, "shape_type": sh.shape_type, "name": sh.name, "left": sh.left, "top": sh.top, "width": sh.width, "height": sh.height, "font_sizes": font_sizes, "colors": colors, } ) return out def _collect_slide_hex_colors(deck: ParsedDeck, slide_n: int) -> list[str]: """Return the de-duped, uppercase set of non-grayscale RGB hex colors that appear in any text run on the slide. Stable order: first-seen. Shape-level fill colors are not in the parser today (only run colors are captured), so we mirror ``check_palette_color`` which is fed run colors from ``ShapeMetadata.colors``. """ seen: list[str] = [] seen_set: set[str] = set() slide = deck.slides[slide_n - 1] for sh in slide.shapes: for run in sh.runs: if run.color_rgb is None: continue norm = run.color_rgb.lstrip("#").upper() if not norm or len(norm) != 6: continue if _is_grayscale(norm): continue if norm in seen_set: continue seen_set.add(norm) seen.append(norm) return seen # --------------------------------------------------------------------------- # Public builder # --------------------------------------------------------------------------- def build_slide_bundle( slide_number: int, parsed_deck: ParsedDeck, render_result: RenderResult, rubric: Rubric, *, rubric_full: dict[str, Any] | None = None, include_image_b64: bool = True, marker_hits: list[Hit] | None = None, ) -> SlideReviewBundle: """Build the single-shot review bundle for *slide_number* (1-indexed). Parameters ---------- slide_number: 1-indexed slide number. parsed_deck, render_result, rubric: Same objects the runner already has on its ``AuditContext``. rubric_full: Pass the cached output of :func:`build_rubric_full` to avoid recomputing it on every slide. When ``None``, this function rebuilds it (slower; primarily for unit tests). include_image_b64: When True, base64-encode the rendered PNG into ``image_b64``. Set to False for tests / dry runs where the bytes aren't needed. marker_hits: Optional pre-computed must-flag hits (the runner already pre-scans every slide). When ``None``, this function runs the same scan. """ if slide_number < 1 or slide_number > parsed_deck.slide_count: raise ValueError( f"slide_number={slide_number} out of range; deck has " f"{parsed_deck.slide_count} slide(s)" ) slide = parsed_deck.slides[slide_number - 1] # --- text + shapes --- parsed_shapes = _build_parsed_shapes(parsed_deck, slide_number) # --- image --- image_path: str | None = None image_b64: str | None = None png_path = _slide_image_path(render_result, slide_number) if png_path is not None: image_path = str(png_path) if include_image_b64: image_b64 = base64.b64encode(png_path.read_bytes()).decode("ascii") # --- palette check (every non-grayscale hex) --- allowed = _allowed_palette(rubric) hexes = _collect_slide_hex_colors(parsed_deck, slide_number) palette_check: dict[str, Any] = { "allowed": [f"#{h.lstrip('#').upper()}" for h in allowed], "checks": [ { "hex": f"#{h}", "in_palette": _color_in_palette(h, allowed), } for h in hexes ], } # --- confidentiality --- canonical = _canonical_confidentiality_text(rubric) if canonical is None: # Same hard-fail behaviour as the @function_tool implementation: the # rubric is malformed and we don't want to silently emit an empty # confidentiality finding. raise ValueError( "Rubric does not contain a canonical_text for 'confidentiality_statement'" ) cc = check_confidentiality_pure(parsed_deck, slide_number, canonical) confidentiality_check: dict[str, Any] = { "present": cc.present, "exact_match": cc.exact_match, "position_hint": cc.position_hint, "matched_excerpt": cc.matched_excerpt, "matching_shape_id": cc.matching_shape_id, } # --- markers --- if marker_hits is None: marker_hits = find_text_markers_pure( parsed_deck, slide_number, list(MUST_FLAG_TERMS) ) text_markers: list[dict[str, Any]] = [ { "term": h.term, "offset": h.offset, "context_window": h.context_window, "source": h.source, "shape_id": h.shape_id, } for h in marker_hits ] return SlideReviewBundle( slide_number=slide_number, slide_text=slide.extracted_text, slide_notes=slide.notes_text, parsed_shapes=parsed_shapes, image_path=image_path, image_b64=image_b64, rubric_full=rubric_full if rubric_full is not None else build_rubric_full(rubric), palette_check=palette_check, confidentiality_check=confidentiality_check, text_markers=text_markers, ) # --------------------------------------------------------------------------- # Prompt serialisation # --------------------------------------------------------------------------- def bundle_to_prompt_payload(bundle: SlideReviewBundle) -> dict[str, Any]: """Convert *bundle* into a JSON-safe dict for prompt serialisation. Drops ``image_b64`` (sent separately as an ``input_image`` content part) and ``image_path`` (a server-local detail the model doesn't need). """ return { "slide_number": bundle.slide_number, "slide_text": bundle.slide_text, "slide_notes": bundle.slide_notes, "parsed_shapes": bundle.parsed_shapes, "image_available": bundle.image_b64 is not None, "rubric": bundle.rubric_full, "palette_check": bundle.palette_check, "confidentiality_check": bundle.confidentiality_check, "text_markers": bundle.text_markers, } __all__ = [ "MUST_FLAG_TERMS", "SlideReviewBundle", "build_rubric_full", "build_slide_bundle", "bundle_to_prompt_payload", ]