Spaces:
Sleeping
Sleeping
File size: 16,720 Bytes
fdfe81a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | """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": {
"<category>": [
{
"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",
]
|