Skip to main content

adk_surface/
viewer.rs

1//! The annotated viewer (spec 3.7 §8.2, X12): looking at what an agent saw.
2//!
3//! Every perception call of the vision tools leaves an answer record beside its image in the
4//! session — `vision-answer-<run>.<call id>.json`, the image itself as `vision-<hex>.<ext>` — with
5//! the call's `RegionSet` in source pixels, each region's backend, coordinate frame and
6//! transform chain, a read's blocks in reading order, and each backend call's duration and
7//! cost. The engine reads those records through the [`Source`](crate::Source) and projects
8//! them into a [`ViewerView`]; it never depends on `adk-vision`, whose JSON is the contract
9//! (`adk-vision/schema/region-set.json`).
10//!
11//! | The view | From |
12//! |---|---|
13//! | The picture, its size and digest | The record's `image`; the bytes from the source, checked against the digest |
14//! | Regions, filterable by label, score and track | The `RegionSet`; a read's block kinds, texts and reading order |
15//! | Backend, model and frame per region, and the transform chain | Each region's `origin`; the record's `models` |
16//! | Measurements, tracks | The record's `measurements` and `tracks`, when a feature adds them |
17//! | The run and the call | The record's `agent`, `invocationId`, `callId` and `calls` |
18//! | Two backends on one image | Two records for the same digest, matched by box overlap |
19//!
20//! A person may save a region, corrected or kept, as a labelled example: an `adk-eval` case
21//! that points at the image by path and digest with `expected_vision`, so `cargo adk eval`
22//! scores an agent against it. Saving never changes the run's answer.
23
24use std::collections::BTreeMap;
25
26use chrono::{DateTime, FixedOffset, Utc};
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use serde_json::{Value, json};
30
31use crate::evidence::short_digest;
32
33/// The artifact name prefix of an answer record `adk-vision` keeps for each perception call.
34pub const VISION_ANSWER_PREFIX: &str = "vision-answer-";
35
36/// The vision tools whose answers the viewer shows.
37pub const VIEWER_TOOLS: [&str; 4] =
38    ["vision_detect", "vision_segment", "vision_read", "vision_describe"];
39
40/// Whether `tool`'s answer is about an image the viewer can show.
41pub(crate) fn answers_about_image(tool: &str) -> bool {
42    VIEWER_TOOLS.contains(&tool)
43}
44
45/// The score a region needs to be shown before a person moves the slider (board choice V3).
46pub const DEFAULT_MIN_SCORE: f64 = 0.5;
47
48// ---------------------------------------------------------------------------
49// The record, as adk-vision writes it
50// ---------------------------------------------------------------------------
51
52/// One answer record, parsed loosely: a field this version does not know is skipped, and a
53/// shape or transform kind it does not know is kept as `Other` and not drawn.
54#[derive(Debug, Clone, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub(crate) struct Record {
57    #[serde(default)]
58    pub(crate) tool: String,
59    #[serde(default)]
60    pub(crate) call_id: String,
61    #[serde(default)]
62    pub(crate) invocation_id: String,
63    #[serde(default)]
64    pub(crate) agent: String,
65    #[serde(default)]
66    pub(crate) at: Option<DateTime<Utc>>,
67    pub(crate) image: RecordImage,
68    #[serde(default)]
69    pub(crate) args: Value,
70    pub(crate) region_set: WireRegionSet,
71    #[serde(default)]
72    pub(crate) page: Option<WirePage>,
73    #[serde(default)]
74    pub(crate) calls: Vec<WireCall>,
75    #[serde(default)]
76    pub(crate) models: BTreeMap<String, WireModel>,
77    #[serde(default)]
78    pub(crate) measurements: Vec<WireMeasurement>,
79    #[serde(default)]
80    pub(crate) tracks: Vec<WireTrack>,
81    #[serde(default)]
82    pub(crate) video: Option<WireVideo>,
83    #[serde(default)]
84    pub(crate) display: WireDisplay,
85}
86
87#[derive(Debug, Clone, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub(crate) struct RecordImage {
90    pub(crate) digest: String,
91    pub(crate) width: u32,
92    pub(crate) height: u32,
93    #[serde(default = "png")]
94    pub(crate) mime_type: String,
95    #[serde(default)]
96    pub(crate) artifact: Option<String>,
97    #[serde(default)]
98    pub(crate) name: Option<String>,
99    #[serde(default)]
100    pub(crate) provenance: Value,
101}
102
103fn png() -> String {
104    "image/png".into()
105}
106
107/// What a feature says about an answer's picture that the record cannot: an Inspector's
108/// still, a video's title.
109#[derive(Debug, Clone, Default, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub(crate) struct WireDisplay {
112    #[serde(default)]
113    title: Option<String>,
114    #[serde(default)]
115    meta: Option<String>,
116    #[serde(default)]
117    run: Option<String>,
118    #[serde(default)]
119    caption: Option<String>,
120    #[serde(default)]
121    kept_until: Option<String>,
122    #[serde(default)]
123    min_score: Option<f64>,
124    #[serde(default)]
125    asked: Option<String>,
126    #[serde(default)]
127    covered: Option<String>,
128}
129
130/// The wire form of `adk_vision::RegionSet`.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub(crate) struct WireRegionSet {
133    pub(crate) image: String,
134    pub(crate) width: u32,
135    pub(crate) height: u32,
136    #[serde(default)]
137    pub(crate) regions: Vec<WireRegion>,
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub(crate) struct WireRegion {
142    #[serde(default)]
143    pub(crate) image: String,
144    pub(crate) shape: WireShape,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub(crate) label: Option<String>,
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub(crate) score: Option<f64>,
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub(crate) track: Option<u64>,
151    pub(crate) origin: WireOrigin,
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[serde(rename_all = "camelCase", tag = "kind")]
156pub(crate) enum WireShape {
157    Point {
158        x: f64,
159        y: f64,
160    },
161    Box {
162        x0: f64,
163        y0: f64,
164        x1: f64,
165        y1: f64,
166    },
167    Polygon {
168        points: Vec<[f64; 2]>,
169    },
170    Mask {
171        width: u32,
172        height: u32,
173        counts: Vec<u32>,
174    },
175    Keypoints {
176        #[serde(default)]
177        skeleton: String,
178        points: Vec<WireKeypoint>,
179    },
180    #[serde(other)]
181    Other,
182}
183
184#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185pub(crate) struct WireKeypoint {
186    x: f64,
187    y: f64,
188    #[serde(default)]
189    visible: bool,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    score: Option<f64>,
192}
193
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195#[serde(rename_all = "camelCase")]
196pub(crate) struct WireOrigin {
197    #[serde(default)]
198    pub(crate) backend: String,
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub(crate) manifest: Option<String>,
201    pub(crate) frame: WireFrame,
202    pub(crate) chain: WireChain,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub(crate) escalated_from: Option<WireEscalatedFrom>,
205}
206
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase", tag = "kind")]
209pub(crate) enum WireFrame {
210    SentPixels,
211    Normalized {
212        scale: u32,
213        order: String,
214    },
215    ModelInput {
216        width: u32,
217        height: u32,
218        letterbox: String,
219    },
220    #[serde(other)]
221    Other,
222}
223
224/// The wire form of `adk_vision::TransformChain`: the source size and the steps, in order.
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226#[serde(rename_all = "camelCase")]
227pub(crate) struct WireChain {
228    pub(crate) source_width: u32,
229    pub(crate) source_height: u32,
230    #[serde(default)]
231    pub(crate) steps: Vec<WireTransform>,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase", tag = "op")]
236pub(crate) enum WireTransform {
237    Crop {
238        x: u32,
239        y: u32,
240        width: u32,
241        height: u32,
242    },
243    Resize {
244        width: u32,
245        height: u32,
246    },
247    Pad {
248        left: u32,
249        top: u32,
250        right: u32,
251        bottom: u32,
252    },
253    Rotate {
254        #[serde(rename = "quarterTurns")]
255        quarter_turns: u8,
256    },
257    Redact,
258    #[serde(other)]
259    Other,
260}
261
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264pub(crate) struct WireEscalatedFrom {
265    #[serde(default)]
266    pub(crate) backend: String,
267    #[serde(default)]
268    pub(crate) reason: Value,
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub(crate) label: Option<String>,
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub(crate) score: Option<f64>,
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub(crate) text: Option<String>,
275}
276
277#[derive(Debug, Clone, Deserialize)]
278#[serde(rename_all = "camelCase")]
279pub(crate) struct WirePage {
280    #[serde(default)]
281    pub(crate) blocks: Vec<WireBlock>,
282    #[serde(default)]
283    pub(crate) reading_order: Vec<usize>,
284}
285
286#[derive(Debug, Clone, Deserialize)]
287pub(crate) struct WireBlock {
288    #[serde(default)]
289    pub(crate) kind: String,
290    #[serde(default)]
291    pub(crate) text: String,
292    #[serde(default)]
293    pub(crate) confidence: Option<f64>,
294}
295
296#[derive(Debug, Clone, Deserialize)]
297#[serde(rename_all = "camelCase")]
298pub(crate) struct WireCall {
299    #[serde(default)]
300    task: String,
301    #[serde(default)]
302    backend: String,
303    #[serde(default)]
304    locality: Value,
305    #[serde(default)]
306    egress: Vec<String>,
307    #[serde(default)]
308    cost_micro_usd: Option<u64>,
309    #[serde(default)]
310    duration_ms: u64,
311    #[serde(default)]
312    escalation: Option<Value>,
313    /// A tracker's library, when a feature names it: "trackforge 0.5".
314    #[serde(default)]
315    library: Option<String>,
316    /// The prompts a segmenter was given, when a feature names them: "from the box".
317    #[serde(default)]
318    prompted: Option<String>,
319}
320
321#[derive(Debug, Clone, Default, Deserialize)]
322#[serde(rename_all = "camelCase")]
323pub(crate) struct WireModel {
324    #[serde(default)]
325    revision: Option<String>,
326    #[serde(default)]
327    licence: Option<String>,
328    #[serde(default)]
329    built_in: bool,
330    /// What a person calls it: "RF-DETR S".
331    #[serde(default)]
332    name: Option<String>,
333    /// "your fine-tune".
334    #[serde(default)]
335    note: Option<String>,
336}
337
338#[derive(Debug, Clone, Deserialize)]
339#[serde(rename_all = "camelCase")]
340pub(crate) struct WireMeasurement {
341    region: usize,
342    /// The measuring call, when it was its own: `c-2208`.
343    #[serde(default)]
344    call: Option<String>,
345    /// Its tool: `vision_measure`.
346    #[serde(default)]
347    tool: Option<String>,
348    #[serde(default)]
349    longest_mm: Option<f64>,
350    #[serde(default)]
351    longest_uncertainty_mm: Option<f64>,
352    #[serde(default)]
353    area_mm2: Option<f64>,
354    #[serde(default)]
355    area_uncertainty_mm2: Option<f64>,
356    #[serde(default)]
357    line: Option<[[f64; 2]; 2]>,
358    calibration: WireCalibration,
359}
360
361#[derive(Debug, Clone, Deserialize)]
362#[serde(rename_all = "camelCase")]
363pub(crate) struct WireCalibration {
364    reference_mm: f64,
365    reference_px: f64,
366    /// "the belt's plane".
367    plane: String,
368    /// "the fiducial".
369    from: String,
370    /// The reference region, when it is one of the answer's.
371    #[serde(default)]
372    region: Option<usize>,
373}
374
375#[derive(Debug, Clone, Deserialize)]
376#[serde(rename_all = "camelCase")]
377pub(crate) struct WireTrack {
378    id: u64,
379    #[serde(default)]
380    label: Option<String>,
381    #[serde(default)]
382    frames: u64,
383    /// When it is seen, in seconds of the video.
384    #[serde(default)]
385    spans: Vec<[f64; 2]>,
386    /// Where it was, oldest first, in this frame's pixels.
387    #[serde(default)]
388    trail: Vec<[f64; 2]>,
389    #[serde(default)]
390    blurred: bool,
391}
392
393#[derive(Debug, Clone, Deserialize)]
394#[serde(rename_all = "camelCase")]
395pub(crate) struct WireVideo {
396    frame: u64,
397    at_s: f64,
398    length_s: f64,
399    sampled_per_s: u32,
400}
401
402impl Record {
403    /// The answer's identifier in a session: its run and its call, since a model may reuse a
404    /// call id in a later turn.
405    pub(crate) fn id(&self) -> String {
406        if self.invocation_id.is_empty() {
407            self.call_id.clone()
408        } else {
409            format!("{}:{}", self.invocation_id, self.call_id)
410        }
411    }
412
413    /// Parses an answer record.
414    ///
415    /// # Errors
416    ///
417    /// A sentence naming what is wrong when `value` is not an answer record.
418    pub(crate) fn parse(value: Value) -> std::result::Result<Self, String> {
419        serde_json::from_value(value)
420            .map_err(|error| format!("not a vision answer record: {error}"))
421    }
422}
423
424// ---------------------------------------------------------------------------
425// Geometry: the transform chain
426// ---------------------------------------------------------------------------
427
428/// The size of the image after each step of `chain`, starting from the source.
429pub(crate) fn chain_sizes(chain: &WireChain) -> Vec<(u32, u32)> {
430    let mut size = (chain.source_width, chain.source_height);
431    let mut sizes = vec![size];
432    for step in &chain.steps {
433        size = match *step {
434            WireTransform::Crop { width, height, .. } | WireTransform::Resize { width, height } => {
435                (width, height)
436            }
437            WireTransform::Pad { left, top, right, bottom } => {
438                (size.0 + left + right, size.1 + top + bottom)
439            }
440            WireTransform::Rotate { quarter_turns } if quarter_turns % 2 == 1 => (size.1, size.0),
441            WireTransform::Rotate { .. } | WireTransform::Redact | WireTransform::Other => size,
442        };
443        sizes.push(size);
444    }
445    sizes
446}
447
448/// A point in the source image's pixels, carried through `chain` into the pixels the backend
449/// saw.
450#[cfg(test)]
451pub(crate) fn to_backend(chain: &WireChain, point: [f64; 2]) -> [f64; 2] {
452    let sizes = chain_sizes(chain);
453    let mut p = point;
454    for (index, step) in chain.steps.iter().enumerate() {
455        let (w, h) = (f64::from(sizes[index].0), f64::from(sizes[index].1));
456        p = match *step {
457            WireTransform::Crop { x, y, .. } => [p[0] - f64::from(x), p[1] - f64::from(y)],
458            WireTransform::Resize { width, height } => {
459                [p[0] * f64::from(width) / w, p[1] * f64::from(height) / h]
460            }
461            WireTransform::Pad { left, top, .. } => [p[0] + f64::from(left), p[1] + f64::from(top)],
462            WireTransform::Rotate { quarter_turns } => rotate(p, quarter_turns, w, h),
463            WireTransform::Redact | WireTransform::Other => p,
464        };
465    }
466    p
467}
468
469/// A point in the pixels the backend saw, carried back through `chain` into the source
470/// image's pixels: the inverse of `to_backend`.
471#[cfg(test)]
472pub(crate) fn to_source(chain: &WireChain, point: [f64; 2]) -> [f64; 2] {
473    let sizes = chain_sizes(chain);
474    let mut p = point;
475    for (index, step) in chain.steps.iter().enumerate().rev() {
476        let (w, h) = (f64::from(sizes[index].0), f64::from(sizes[index].1));
477        p = match *step {
478            WireTransform::Crop { x, y, .. } => [p[0] + f64::from(x), p[1] + f64::from(y)],
479            WireTransform::Resize { width, height } => {
480                [p[0] * w / f64::from(width), p[1] * h / f64::from(height)]
481            }
482            WireTransform::Pad { left, top, .. } => [p[0] - f64::from(left), p[1] - f64::from(top)],
483            WireTransform::Rotate { quarter_turns } => {
484                // Undoing a turn is turning the rest of the way, in the turned image.
485                let (tw, th) = if quarter_turns % 2 == 1 { (h, w) } else { (w, h) };
486                rotate(p, (4 - quarter_turns % 4) % 4, tw, th)
487            }
488            WireTransform::Redact | WireTransform::Other => p,
489        };
490    }
491    p
492}
493
494/// `p` in a `w` × `h` image turned clockwise by `quarter_turns`.
495#[cfg(test)]
496fn rotate(p: [f64; 2], quarter_turns: u8, w: f64, h: f64) -> [f64; 2] {
497    match quarter_turns % 4 {
498        1 => [h - p[1], p[0]],
499        2 => [w - p[0], h - p[1]],
500        3 => [p[1], w - p[0]],
501        _ => p,
502    }
503}
504
505/// The bounds of a mask, run-length encoded in COCO's column-major order with the unset run
506/// first, and how many pixels it sets; `None` when it sets none.
507pub(crate) fn mask_bounds(width: u32, height: u32, counts: &[u32]) -> Option<([f64; 4], u64)> {
508    if width == 0 || height == 0 {
509        return None;
510    }
511    let (mut x0, mut y0, mut x1, mut y1) = (u64::MAX, u64::MAX, 0u64, 0u64);
512    let (mut at, mut area) = (0u64, 0u64);
513    let h = u64::from(height);
514    for (run, &count) in counts.iter().enumerate() {
515        let count = u64::from(count);
516        if run % 2 == 1 && count > 0 {
517            area += count;
518            let (first, last) = (at, at + count - 1);
519            let (c0, c1) = (first / h, last / h);
520            x0 = x0.min(c0);
521            x1 = x1.max(c1 + 1);
522            if c0 == c1 {
523                y0 = y0.min(first % h);
524                y1 = y1.max(last % h + 1);
525            } else {
526                // The run wraps a column: it reaches both the top and the bottom of the image.
527                y0 = 0;
528                y1 = h;
529            }
530        }
531        at += count;
532    }
533    (area > 0).then_some(([x0 as f64, y0 as f64, x1 as f64, y1 as f64], area))
534}
535
536/// The bounds of a shape in source pixels, clamped to the image.
537pub(crate) fn shape_bounds(shape: &WireShape, width: u32, height: u32) -> Option<[f64; 4]> {
538    let (w, h) = (f64::from(width), f64::from(height));
539    let bounds = match shape {
540        WireShape::Box { x0, y0, x1, y1 } => [*x0, *y0, *x1, *y1],
541        WireShape::Point { x, y } => [*x - 1.0, *y - 1.0, *x + 1.0, *y + 1.0],
542        WireShape::Polygon { points } => bounds_of(points.iter().copied())?,
543        WireShape::Keypoints { points, .. } => bounds_of(points.iter().map(|p| [p.x, p.y]))?,
544        WireShape::Mask { width, height, counts } => mask_bounds(*width, *height, counts)?.0,
545        WireShape::Other => return None,
546    };
547    if !bounds.iter().all(|v| v.is_finite()) {
548        return None;
549    }
550    let clamped = [
551        bounds[0].clamp(0.0, w),
552        bounds[1].clamp(0.0, h),
553        bounds[2].clamp(0.0, w),
554        bounds[3].clamp(0.0, h),
555    ];
556    (clamped[2] > clamped[0] && clamped[3] > clamped[1]).then_some(clamped)
557}
558
559fn bounds_of(points: impl Iterator<Item = [f64; 2]>) -> Option<[f64; 4]> {
560    let mut out: Option<[f64; 4]> = None;
561    for [x, y] in points {
562        out = Some(match out {
563            None => [x, y, x, y],
564            Some([x0, y0, x1, y1]) => [x0.min(x), y0.min(y), x1.max(x), y1.max(y)],
565        });
566    }
567    out
568}
569
570/// The overlap of two boxes over their union, from 0 to 1.
571pub(crate) fn iou(a: [f64; 4], b: [f64; 4]) -> f64 {
572    let w = (a[2].min(b[2]) - a[0].max(b[0])).max(0.0);
573    let h = (a[3].min(b[3]) - a[1].max(b[1])).max(0.0);
574    let inter = w * h;
575    let area = |r: [f64; 4]| (r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0);
576    let union = area(a) + area(b) - inter;
577    if union <= 0.0 { 0.0 } else { (inter / union).clamp(0.0, 1.0) }
578}
579
580// ---------------------------------------------------------------------------
581// The view
582// ---------------------------------------------------------------------------
583
584/// What kind of picture an answer is about, which decides its layers and words.
585#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
586#[serde(rename_all = "camelCase")]
587pub enum PictureKind {
588    /// A photo or a still: regions, masks and measurements.
589    Photo,
590    /// A document page: blocks by kind in reading order.
591    Document,
592    /// A frame of a video: regions with tracks, trails and a timeline.
593    VideoFrame,
594}
595
596/// The kind of a region's shape.
597#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
598#[serde(rename_all = "camelCase")]
599pub enum ShapeKind {
600    /// A point.
601    Point,
602    /// A box.
603    Box,
604    /// A polygon.
605    Polygon,
606    /// A mask.
607    Mask,
608    /// Keypoints.
609    Keypoints,
610}
611
612/// How part of a fact reads.
613#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
614#[serde(rename_all = "camelCase")]
615pub enum FactStyle {
616    /// Plain words.
617    Plain,
618    /// Data: an identifier, a box, a digest.
619    Mono,
620    /// A quieter note after the value.
621    Muted,
622    /// Bold, quoted words.
623    Strong,
624}
625
626/// One part of a fact's value.
627#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
628#[serde(rename_all = "camelCase")]
629pub struct FactPart {
630    /// The words.
631    pub text: String,
632    /// How they read.
633    pub style: FactStyle,
634}
635
636/// A labelled line of a region's details: "Answered in · Model-input pixels, 960 × 960,
637/// letterboxed".
638#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
639#[serde(rename_all = "camelCase")]
640pub struct Fact {
641    /// "Answered in".
642    pub label: String,
643    /// The value, in parts.
644    pub parts: Vec<FactPart>,
645}
646
647impl Fact {
648    fn new(label: &str) -> Self {
649        Self { label: label.into(), parts: Vec::new() }
650    }
651
652    fn plain(mut self, text: impl Into<String>) -> Self {
653        self.parts.push(FactPart { text: text.into(), style: FactStyle::Plain });
654        self
655    }
656
657    fn mono(mut self, text: impl Into<String>) -> Self {
658        self.parts.push(FactPart { text: text.into(), style: FactStyle::Mono });
659        self
660    }
661
662    fn muted(mut self, text: impl Into<String>) -> Self {
663        self.parts.push(FactPart { text: text.into(), style: FactStyle::Muted });
664        self
665    }
666}
667
668/// A value replaced by an escalation (board choice V6): what the local backend read, what
669/// the escalation reads now, and the released crop's digest.
670#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
671#[serde(rename_all = "camelCase")]
672pub struct EscalationView {
673    /// What the first backend read: `PO-7781S`.
674    #[serde(default, skip_serializing_if = "Option::is_none")]
675    pub read_as: Option<String>,
676    /// Its score.
677    #[serde(default, skip_serializing_if = "Option::is_none")]
678    pub read_as_score: Option<f64>,
679    /// Who escalated: "Gemini".
680    pub by: String,
681    /// The released crop's digest, short.
682    #[serde(default, skip_serializing_if = "Option::is_none")]
683    pub crop_digest: Option<String>,
684}
685
686/// A mask to draw: COCO run-length encoding, column-major, unset run first.
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
688#[serde(rename_all = "camelCase")]
689pub struct MaskView {
690    /// Width of the mask's raster.
691    pub width: u32,
692    /// Height of the mask's raster.
693    pub height: u32,
694    /// The runs.
695    pub counts: Vec<u32>,
696    /// Pixels set.
697    pub area: u64,
698}
699
700/// One region of an answer, as the viewer draws and lists it.
701#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
702#[serde(rename_all = "camelCase")]
703pub struct RegionView {
704    /// Its place in the answer's `RegionSet`: what an example and the export name.
705    pub index: u32,
706    /// Its place in reading order, from 1, for a page.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub order: Option<u32>,
709    /// The label or block kind: "handwriting", "seal tear".
710    pub label: String,
711    /// The shape's kind.
712    pub shape: ShapeKind,
713    /// The text it reads, for a page's block.
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    pub text: Option<String>,
716    /// The list's quieter words: the text, "mask · 14.3 mm", "box · at the edge".
717    pub detail: String,
718    /// The score.
719    #[serde(default, skip_serializing_if = "Option::is_none")]
720    pub score: Option<f64>,
721    /// The score as the list shows it: "0.58".
722    pub score_text: String,
723    /// The track, for a video frame.
724    #[serde(default, skip_serializing_if = "Option::is_none")]
725    pub track: Option<u64>,
726    /// "T4".
727    #[serde(default, skip_serializing_if = "Option::is_none")]
728    pub track_name: Option<String>,
729    /// Left edge in source pixels.
730    pub x0: f64,
731    /// Top edge in source pixels.
732    pub y0: f64,
733    /// Right edge in source pixels, exclusive.
734    pub x1: f64,
735    /// Bottom edge in source pixels, exclusive.
736    pub y1: f64,
737    /// The box as the details show it: `1250, 466 → 1532, 540`, in source pixels.
738    pub box_text: String,
739    /// The mask, when the shape is one.
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub mask: Option<MaskView>,
742    /// The polygon's points, when the shape is one.
743    #[serde(default, skip_serializing_if = "Vec::is_empty")]
744    pub polygon: Vec<[f64; 2]>,
745    /// The tag over the picture: "part · 0.96", "seal tear · 0.91 · 14.3 mm".
746    pub tag: String,
747    /// The details' heading: "5 · handwriting", "Seal tear", "T4 · forklift".
748    pub heading: String,
749    /// The details, in order (board choices V4, V5, V6).
750    pub facts: Vec<Fact>,
751    /// The transform chain as steps (board choice V4).
752    pub chain: Vec<String>,
753    /// A value an escalation replaced.
754    #[serde(default, skip_serializing_if = "Option::is_none")]
755    pub escalation: Option<EscalationView>,
756    /// Its measurement in one line: "14.3 mm".
757    #[serde(default, skip_serializing_if = "Option::is_none")]
758    pub measurement: Option<String>,
759    /// It touches the picture's edge.
760    pub at_edge: bool,
761    /// Its pixels are blurred in the picture: a person.
762    pub blurred: bool,
763}
764
765/// A label and how many regions carry it: a filter chip.
766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
767#[serde(rename_all = "camelCase")]
768pub struct LabelCount {
769    /// The label.
770    pub label: String,
771    /// How many.
772    pub count: u32,
773}
774
775/// A measurement tile (board choice V9).
776#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
777#[serde(rename_all = "camelCase")]
778pub struct MeasureTile {
779    /// "Longest".
780    pub label: String,
781    /// "14.3 mm".
782    pub value: String,
783    /// "± 0.3 mm".
784    pub uncertainty: String,
785}
786
787/// An answer's measurements (board choice V9).
788#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
789#[serde(rename_all = "camelCase")]
790pub struct MeasurementsView {
791    /// The region measured.
792    pub region: u32,
793    /// The tiles.
794    pub tiles: Vec<MeasureTile>,
795    /// "In the belt's plane, from the fiducial: 40.0 mm is 245 px, so 6.12 px per mm. Valid
796    /// only in that plane."
797    pub calibration: String,
798    /// The longest length's ends, in source pixels.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub line: Option<[[f64; 2]; 2]>,
801}
802
803/// One track of a video (board choice V10).
804#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
805#[serde(rename_all = "camelCase")]
806pub struct TrackView {
807    /// The track's identifier.
808    pub id: u64,
809    /// "T4".
810    pub name: String,
811    /// "forklift".
812    pub label: String,
813    /// "139", "1.2k": frames seen.
814    pub frames_text: String,
815    /// When it is seen, in seconds.
816    pub spans: Vec<[f64; 2]>,
817    /// Where it was, oldest first.
818    pub trail: Vec<[f64; 2]>,
819    /// People are blurred.
820    pub blurred: bool,
821}
822
823/// The video a frame comes from (board choice V10).
824#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
825#[serde(rename_all = "camelCase")]
826pub struct VideoView {
827    /// "10:34.1".
828    pub at_text: String,
829    /// "20:00".
830    pub length_text: String,
831    /// "frame 19,023 · sampled 5 a second".
832    pub frame_text: String,
833    /// Where the frame is, in seconds.
834    pub at_s: f64,
835    /// How long the video is, in seconds.
836    pub length_s: f64,
837    /// The tracks.
838    pub tracks: Vec<TrackView>,
839    /// "Tracks are anonymous …".
840    pub note: String,
841}
842
843/// An answer with nothing in it (board choice V12): an answer, not an error.
844#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
845#[serde(rename_all = "camelCase")]
846pub struct EmptyView {
847    /// "Nothing found".
848    pub title: String,
849    /// The sentence, in parts.
850    pub text: Vec<FactPart>,
851    /// Asked, Sent, Cost, Run.
852    pub facts: Vec<Fact>,
853    /// "Hidden by your filters." and its line.
854    pub hidden: Vec<FactPart>,
855    /// "The call failed." and its line.
856    pub failed: Vec<FactPart>,
857}
858
859/// The answer `id` names among `records` (oldest first): by its run and call, or by its call
860/// alone — a thread's tool line knows only the call — the newest such answer.
861pub(crate) fn find<'a>(records: &'a [Record], id: &str) -> Option<&'a Record> {
862    records
863        .iter()
864        .rev()
865        .find(|record| record.id() == id)
866        .or_else(|| records.iter().rev().find(|record| record.call_id == id))
867}
868
869/// The run and the call that produced an answer.
870#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
871#[serde(rename_all = "camelCase")]
872pub struct RunView {
873    /// "Document desk · 10:31".
874    pub text: String,
875    /// The agent, by its name in the runtime.
876    pub agent: String,
877    /// The tool and the call: "vision_read · c-31", in parts.
878    pub call: Vec<FactPart>,
879}
880
881/// One answer for the picture, as the "Answer from" picker lists it.
882#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
883#[serde(rename_all = "camelCase")]
884pub struct AnswerChoice {
885    /// The call's identifier.
886    pub id: String,
887    /// "PP-OCRv6 small".
888    pub name: String,
889    /// "on this computer", "Meta, in the cloud".
890    pub place: String,
891    /// The tool.
892    pub tool: String,
893}
894
895/// One answer, in full.
896#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
897#[serde(rename_all = "camelCase")]
898pub struct AnswerView {
899    /// The call's identifier.
900    pub id: String,
901    /// The tool.
902    pub tool: String,
903    /// "PP-OCRv6 small".
904    pub name: String,
905    /// "on this computer".
906    pub place: String,
907    /// The regions, in the `RegionSet`'s order; a page's in reading order.
908    pub regions: Vec<RegionView>,
909    /// Labels with counts, in first-seen order.
910    pub labels: Vec<LabelCount>,
911    /// "11 regions", "1.1 s", "$0".
912    pub stats: Vec<String>,
913    /// The run and the call.
914    pub run: RunView,
915    /// When the answer holds nothing.
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub empty: Option<EmptyView>,
918    /// Measurements.
919    #[serde(default, skip_serializing_if = "Option::is_none")]
920    pub measurements: Option<MeasurementsView>,
921    /// The video and its tracks, for a frame.
922    #[serde(default, skip_serializing_if = "Option::is_none")]
923    pub video: Option<VideoView>,
924    /// The region selected first: the escalated or lowest-scored one on a page, the measured
925    /// one in a photo, the first otherwise.
926    #[serde(default, skip_serializing_if = "Option::is_none")]
927    pub selected: Option<u32>,
928}
929
930/// How a region of one answer stands against the other (board choice V11).
931#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
932#[serde(rename_all = "camelCase")]
933pub enum Agreement {
934    /// Both found it, with the same reading.
935    Agree,
936    /// Both found it and read it differently.
937    Differ,
938    /// Only this answer found it.
939    OnlyHere,
940}
941
942/// A region's standing in a comparison.
943#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
944#[serde(rename_all = "camelCase")]
945pub struct CompareMark {
946    /// The region's index in its answer.
947    pub index: u32,
948    /// How it stands.
949    pub agreement: Agreement,
950    /// The tag over it: its reading where they differ, "only here".
951    #[serde(default, skip_serializing_if = "Option::is_none")]
952    pub tag: Option<String>,
953}
954
955/// One side of a comparison.
956#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
957#[serde(rename_all = "camelCase")]
958pub struct ComparePane {
959    /// The answer.
960    pub answer: AnswerView,
961    /// "PP-OCRv6" — the short name the differences use.
962    pub short_name: String,
963    /// Each region's standing.
964    pub marks: Vec<CompareMark>,
965}
966
967/// One difference between two answers.
968#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
969#[serde(rename_all = "camelCase")]
970pub struct Difference {
971    /// The region's number: its reading order, or its place.
972    pub number: u32,
973    /// Its label.
974    pub label: String,
975    /// "handwriting · read differently", "text · only B found it".
976    pub title: String,
977    /// What A answered: "PO-7781S · 0.58", or "—".
978    pub a: String,
979    /// What B answered.
980    pub b: String,
981    /// The region in A.
982    #[serde(default, skip_serializing_if = "Option::is_none")]
983    pub a_region: Option<u32>,
984    /// The region in B.
985    #[serde(default, skip_serializing_if = "Option::is_none")]
986    pub b_region: Option<u32>,
987}
988
989/// Two answers for one image, side by side (board choice V11).
990#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
991#[serde(rename_all = "camelCase")]
992pub struct CompareView {
993    /// A.
994    pub a: ComparePane,
995    /// B.
996    pub b: ComparePane,
997    /// Regions both found and read alike.
998    pub agree: u32,
999    /// Regions both found and read differently.
1000    pub differ: u32,
1001    /// Regions only one found.
1002    pub only_one: u32,
1003    /// "Where both found a region, the boxes overlap closely (mean IoU 0.94)."
1004    pub overlap_text: String,
1005    /// The differences, A's order first.
1006    pub differences: Vec<Difference>,
1007}
1008
1009/// The picture.
1010#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1011#[serde(rename_all = "camelCase")]
1012pub struct ViewerImage {
1013    /// `sha256:<hex>` in full.
1014    pub digest: String,
1015    /// `sha256:556b49…a22654` (board choice S4).
1016    pub digest_short: String,
1017    /// Width in pixels.
1018    pub width: u32,
1019    /// Height in pixels.
1020    pub height: u32,
1021    /// `image/png`.
1022    pub mime_type: String,
1023    /// Where the surface loads it with the viewer's own authorisation.
1024    pub href: String,
1025}
1026
1027/// Where a labelled example may be saved (board choice V13).
1028#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1029#[serde(rename_all = "camelCase")]
1030pub struct ExamplesView {
1031    /// The source saves examples.
1032    pub can_save: bool,
1033    /// The eval fixture files there are, relative to the fixtures' root.
1034    pub files: Vec<String>,
1035    /// The file picked first.
1036    pub file: String,
1037    /// The case name offered first, for the selected region.
1038    pub case_name: String,
1039}
1040
1041/// What the annotated viewer shows of one image in one session (spec 3.7 §8.2, X12).
1042#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1043#[serde(rename_all = "camelCase")]
1044pub struct ViewerView {
1045    /// The session.
1046    pub session_id: String,
1047    /// The picture.
1048    pub image: ViewerImage,
1049    /// What kind of picture it is.
1050    pub kind: PictureKind,
1051    /// "INV-2291 · page 1".
1052    pub title: String,
1053    /// "1654 × 2339 · INV-2291.pdf, page 1 at 200 dpi".
1054    pub meta: String,
1055    /// The agent the back link returns to.
1056    pub agent: String,
1057    /// Its display name: "Document desk".
1058    pub agent_name: String,
1059    /// Every answer for this image in the session, newest first.
1060    pub answers: Vec<AnswerChoice>,
1061    /// The answer shown, when there is one.
1062    #[serde(default, skip_serializing_if = "Option::is_none")]
1063    pub answer: Option<AnswerView>,
1064    /// Two answers side by side, when asked.
1065    #[serde(default, skip_serializing_if = "Option::is_none")]
1066    pub compare: Option<CompareView>,
1067    /// A feature's line under the picture.
1068    #[serde(default, skip_serializing_if = "Option::is_none")]
1069    pub caption: Option<String>,
1070    /// The score a region needs to be shown at first.
1071    pub min_score: f64,
1072    /// Saving labelled examples.
1073    pub examples: ExamplesView,
1074}
1075
1076// ---------------------------------------------------------------------------
1077// Words
1078// ---------------------------------------------------------------------------
1079
1080/// What a person calls a backend or a model by its identifier.
1081fn display_name(id: &str, models: &BTreeMap<String, WireModel>) -> String {
1082    if let Some(name) = models.get(id).and_then(|model| model.name.clone()) {
1083        return name;
1084    }
1085    match id {
1086        "rf-detr-n" => "RF-DETR Nano",
1087        "rf-detr-s" => "RF-DETR S",
1088        "rf-detr-m" => "RF-DETR M",
1089        "rf-detr-seg-n" => "RF-DETR-Seg Nano",
1090        "sam2.1-tiny" | "sam2-tiny" => "SAM 2.1 Tiny",
1091        "efficientsam-ti" => "EfficientSAM-Ti",
1092        "siglip2-base" => "SigLIP 2",
1093        "pp-ocrv6" | "pp-ocrv6-small" => "PP-OCRv6 small",
1094        "pp-ocrv6-tiny" => "PP-OCRv6 tiny",
1095        "paddleocr-vl" | "paddleocr-vl-1.6" => "PaddleOCR-VL-1.6",
1096        "bytetrack" => "ByteTrack",
1097        "qwen3-vl-2b-instruct" => "Qwen3-VL 2B",
1098        other => other,
1099    }
1100    .to_string()
1101}
1102
1103/// The name of a provider by the host it answers on.
1104fn provider_of(hosts: &[String]) -> Option<&'static str> {
1105    hosts.iter().find_map(|host| {
1106        Some(match host.as_str() {
1107            h if h.ends_with("meta.ai") || h.ends_with("llama.com") => "Meta",
1108            h if h.ends_with("anthropic.com") => "Anthropic",
1109            h if h.ends_with("googleapis.com") => "Google",
1110            h if h.ends_with("nvidia.com") => "NVIDIA",
1111            h if h.ends_with("openai.com") => "OpenAI",
1112            _ => return None,
1113        })
1114    })
1115}
1116
1117fn hosts_of(locality: &Value) -> Vec<String> {
1118    locality
1119        .get("hosts")
1120        .and_then(Value::as_array)
1121        .map(|hosts| hosts.iter().filter_map(Value::as_str).map(str::to_string).collect())
1122        .unwrap_or_default()
1123}
1124
1125fn is_remote(locality: &Value) -> bool {
1126    locality.get("kind").and_then(Value::as_str) == Some("remote")
1127}
1128
1129/// "on this computer" or "Meta, in the cloud".
1130fn place_of(locality: &Value) -> String {
1131    if is_remote(locality) {
1132        match provider_of(&hosts_of(locality)) {
1133            Some(provider) => format!("{provider}, in the cloud"),
1134            None => "in the cloud".to_string(),
1135        }
1136    } else {
1137        "on this computer".to_string()
1138    }
1139}
1140
1141/// "Gemini" for an escalation's backend: the model family a person knows.
1142fn escalation_name(backend: &str, locality: &Value) -> String {
1143    let lower = backend.to_ascii_lowercase();
1144    for (needle, name) in [
1145        ("gemini", "Gemini"),
1146        ("claude", "Claude"),
1147        ("sam-3", "sam-3.1"),
1148        ("nemotron", "NVIDIA Nemotron"),
1149        ("muse", "Muse"),
1150    ] {
1151        if lower.contains(needle) {
1152            return name.to_string();
1153        }
1154    }
1155    provider_of(&hosts_of(locality)).map_or_else(|| backend.to_string(), str::to_string)
1156}
1157
1158/// "Model-input pixels, 960 × 960, letterboxed" (board choice V4).
1159pub(crate) fn frame_words(frame: &WireFrame) -> String {
1160    match frame {
1161        WireFrame::SentPixels => "Pixels of the image as sent".to_string(),
1162        WireFrame::Normalized { scale, order } => {
1163            let order = if order == "yx" { "y before x" } else { "x before y" };
1164            format!("0–{scale} on each axis, {order}")
1165        }
1166        WireFrame::ModelInput { width, height, letterbox } => {
1167            let how = if letterbox == "stretch" { "stretched" } else { "letterboxed" };
1168            format!("Model-input pixels, {width} × {height}, {how}")
1169        }
1170        WireFrame::Other => "A frame this viewer does not know".to_string(),
1171    }
1172}
1173
1174/// The first step of a chain: what the source is.
1175fn source_words(record: &Record, width: u32, height: u32) -> String {
1176    let provenance = &record.image.provenance;
1177    match provenance.get("kind").and_then(Value::as_str) {
1178        Some("documentPage") => {
1179            let page = provenance.get("page").and_then(Value::as_u64).unwrap_or(1);
1180            let dpi = provenance.get("dpi").and_then(Value::as_u64);
1181            let name = document_name(record);
1182            match dpi {
1183                Some(dpi) => format!("Page {page} of {name} at {dpi} dpi · {width} × {height}"),
1184                None => format!("Page {page} of {name} · {width} × {height}"),
1185            }
1186        }
1187        Some("camera") => format!("Frame {width} × {height}"),
1188        Some("screen") => format!("Screenshot {width} × {height}"),
1189        _ if record.video.is_some() => format!("Video frame {width} × {height}"),
1190        _ => format!("Image {width} × {height}"),
1191    }
1192}
1193
1194fn document_name(record: &Record) -> String {
1195    record
1196        .image
1197        .provenance
1198        .get("name")
1199        .and_then(Value::as_str)
1200        .map(str::to_string)
1201        .or_else(|| record.image.name.clone().filter(|name| !name.starts_with("sha256:")))
1202        .unwrap_or_else(|| "the document".to_string())
1203}
1204
1205/// "Padded 140 left, 141 right · 960 × 960".
1206fn pad_words(left: u32, top: u32, right: u32, bottom: u32, after: (u32, u32)) -> String {
1207    let mut sides = Vec::new();
1208    if left > 0 && left == right {
1209        sides.push(format!("{left} left and right"));
1210    } else {
1211        if left > 0 {
1212            sides.push(format!("{left} left"));
1213        }
1214        if right > 0 {
1215            sides.push(format!("{right} right"));
1216        }
1217    }
1218    if top > 0 && top == bottom {
1219        sides.push(format!("{top} top and bottom"));
1220    } else {
1221        if top > 0 {
1222            sides.push(format!("{top} top"));
1223        }
1224        if bottom > 0 {
1225            sides.push(format!("{bottom} bottom"));
1226        }
1227    }
1228    format!("Padded {} · {} × {}", sides.join(", "), after.0, after.1)
1229}
1230
1231/// The chain as steps (board choice V4): what the source is, each transform, and how the
1232/// answer came back.
1233pub(crate) fn chain_words(record: &Record, origin: &WireOrigin, shape: ShapeKind) -> Vec<String> {
1234    let chain = &origin.chain;
1235    let sizes = chain_sizes(chain);
1236    let mut steps = vec![source_words(record, chain.source_width, chain.source_height)];
1237    for (index, step) in chain.steps.iter().enumerate() {
1238        let after = sizes[index + 1];
1239        steps.push(match *step {
1240            WireTransform::Crop { x, y, width, height } => {
1241                format!("Cut to {width} × {height} at {x}, {y}")
1242            }
1243            WireTransform::Resize { width, height } => format!("Resized to {width} × {height}"),
1244            WireTransform::Pad { left, top, right, bottom } => {
1245                pad_words(left, top, right, bottom, after)
1246            }
1247            WireTransform::Rotate { quarter_turns } => {
1248                format!("Turned {}°", u32::from(quarter_turns % 4) * 90)
1249            }
1250            WireTransform::Redact => "Covered before it left; the boxes did not move".to_string(),
1251            WireTransform::Other => "A step this viewer does not know".to_string(),
1252        });
1253    }
1254    steps.push(
1255        match (shape, record.page.is_some()) {
1256            (_, true) => "Answer mapped back to source pixels",
1257            (ShapeKind::Mask, _) => "Mask mapped back to source pixels",
1258            (ShapeKind::Polygon, _) => "Outline mapped back to source pixels",
1259            (ShapeKind::Point | ShapeKind::Keypoints, _) => "Points mapped back to source pixels",
1260            (ShapeKind::Box, _) => "Box mapped back to source pixels",
1261        }
1262        .to_string(),
1263    );
1264    steps
1265}
1266
1267/// `1250, 466 → 1532, 540`: a box in whole source pixels.
1268pub(crate) fn box_words(bounds: [f64; 4]) -> String {
1269    let r = |v: f64| v.round() as i64;
1270    format!("{}, {} → {}, {}", r(bounds[0]), r(bounds[1]), r(bounds[2]), r(bounds[3]))
1271}
1272
1273/// `2,412`.
1274fn thousands(n: u64) -> String {
1275    let digits = n.to_string();
1276    let mut out = String::new();
1277    for (i, c) in digits.chars().enumerate() {
1278        if i > 0 && (digits.len() - i).is_multiple_of(3) {
1279            out.push(',');
1280        }
1281        out.push(c);
1282    }
1283    out
1284}
1285
1286/// "139", "980", "1.2k".
1287fn count_words(n: u64) -> String {
1288    if n >= 1_000 { format!("{:.1}k", n as f64 / 1_000.0) } else { n.to_string() }
1289}
1290
1291/// "$0", "$0.0025".
1292fn cost_words(micro_usd: u64) -> String {
1293    if micro_usd == 0 { "$0".to_string() } else { crate::words::money(micro_usd) }
1294}
1295
1296/// "1.1 s".
1297fn seconds_words(ms: u64) -> String {
1298    format!("{:.1} s", ms as f64 / 1_000.0)
1299}
1300
1301/// "10:34.1" for a time in a video.
1302fn video_time(seconds: f64) -> String {
1303    let tenths = (seconds * 10.0).round() as u64;
1304    format!("{}:{:02}.{}", tenths / 600, (tenths / 10) % 60, tenths % 10)
1305}
1306
1307/// "20:00" for a video's length.
1308fn video_length(seconds: f64) -> String {
1309    let whole = seconds.round() as u64;
1310    format!("{}:{:02}", whole / 60, whole % 60)
1311}
1312
1313/// "Seal tear" from "seal tear".
1314fn capitalised(text: &str) -> String {
1315    let mut chars = text.chars();
1316    match chars.next() {
1317        Some(first) => first.to_uppercase().chain(chars).collect(),
1318        None => String::new(),
1319    }
1320}
1321
1322/// The call that answered, as the run shows it: `vision_read · c-31`; with its measuring
1323/// call, `vision_segment c-2207 · vision_measure c-2208`.
1324fn call_words(record: &Record) -> Vec<FactPart> {
1325    let mono = |text: &str| FactPart { text: text.to_string(), style: FactStyle::Mono };
1326    let plain = |text: String| FactPart { text, style: FactStyle::Plain };
1327    let measured = record.measurements.iter().find_map(|m| {
1328        Some((m.tool.clone().unwrap_or_else(|| "vision_measure".into()), m.call.clone()?))
1329    });
1330    match measured {
1331        Some((tool, call)) => vec![
1332            mono(&record.tool),
1333            plain(format!(" {} · ", record.call_id)),
1334            mono(&tool),
1335            plain(format!(" {call}")),
1336        ],
1337        None if record.video.is_some() => {
1338            vec![mono(&record.tool), plain(format!(" over sampled frames · {}", record.call_id))]
1339        }
1340        None => vec![mono(&record.tool), plain(format!(" · {}", record.call_id))],
1341    }
1342}
1343
1344/// What the call asked for: "torn seal", "person".
1345fn asked_of(args: &Value) -> Option<String> {
1346    for key in ["concepts", "classes"] {
1347        if let Some(list) = args.get(key).and_then(Value::as_array) {
1348            let words: Vec<&str> = list.iter().filter_map(Value::as_str).collect();
1349            if !words.is_empty() {
1350                return Some(words.join(", "));
1351            }
1352        }
1353    }
1354    args.get("question").and_then(Value::as_str).map(str::to_string)
1355}
1356
1357// ---------------------------------------------------------------------------
1358// Projection
1359// ---------------------------------------------------------------------------
1360
1361/// What the projection needs beyond the records.
1362pub(crate) struct ViewerInput<'a> {
1363    pub(crate) session: &'a str,
1364    pub(crate) agent_name: String,
1365    pub(crate) offset: FixedOffset,
1366    pub(crate) can_save: bool,
1367    pub(crate) files: Vec<String>,
1368}
1369
1370/// The kind of picture `record` is about.
1371fn kind_of(record: &Record) -> PictureKind {
1372    if record.page.is_some() || record.tool == "vision_read" {
1373        PictureKind::Document
1374    } else if record.video.is_some() || !record.tracks.is_empty() {
1375        PictureKind::VideoFrame
1376    } else {
1377        PictureKind::Photo
1378    }
1379}
1380
1381/// The backend calls that answered, not the escalations that replaced a value.
1382fn answering_calls(record: &Record) -> impl Iterator<Item = &WireCall> {
1383    record.calls.iter().filter(|call| call.escalation.is_none())
1384}
1385
1386/// "PP-OCRv6 small", "RF-DETR S + SAM 2.1 Tiny".
1387fn answer_name(record: &Record) -> String {
1388    let mut names: Vec<String> = Vec::new();
1389    for call in answering_calls(record) {
1390        let manifest = manifest_of(record, &call.backend);
1391        let name = display_name(&manifest, &record.models);
1392        if !names.contains(&name) {
1393            names.push(name);
1394        }
1395    }
1396    if names.is_empty() {
1397        names.extend(
1398            record
1399                .region_set
1400                .regions
1401                .first()
1402                .map(|r| display_name(&r.origin.backend, &record.models)),
1403        );
1404    }
1405    names.join(" + ")
1406}
1407
1408fn answer_place(record: &Record) -> String {
1409    answering_calls(record)
1410        .next()
1411        .map_or_else(|| "on this computer".to_string(), |c| place_of(&c.locality))
1412}
1413
1414/// The manifest a backend ran: from a region it answered, the backend's own id otherwise.
1415fn manifest_of(record: &Record, backend: &str) -> String {
1416    record
1417        .region_set
1418        .regions
1419        .iter()
1420        .find(|region| region.origin.backend == backend)
1421        .and_then(|region| region.origin.manifest.clone())
1422        .unwrap_or_else(|| backend.to_string())
1423}
1424
1425/// A model's line (board choice V5): `pp-ocrv6-small@3f2a9c1 · Apache-2.0`, or `· your
1426/// manifest` for one the built-in manifest does not hold.
1427fn model_fact(label: &str, record: &Record, id: &str, extra: Option<String>) -> Fact {
1428    let model = record.models.get(id).cloned().unwrap_or_default();
1429    let mut fact = Fact::new(label);
1430    fact = match model.revision.as_deref() {
1431        Some(revision) if model.built_in => {
1432            fact.mono(format!("{id}@{}", &revision[..revision.len().min(7)]))
1433        }
1434        _ => fact.mono(id),
1435    };
1436    // A built-in model's licence, unless the line says how it was prompted (board choice V5).
1437    let mut notes: Vec<String> = Vec::new();
1438    if model.built_in {
1439        if extra.is_none() {
1440            notes.extend(model.licence.clone());
1441        }
1442    } else if record.models.contains_key(id) {
1443        notes.push(match &model.note {
1444            Some(note) => format!("{note}, your manifest"),
1445            None => "your manifest".to_string(),
1446        });
1447    }
1448    notes.extend(extra);
1449    if !notes.is_empty() {
1450        fact = fact.muted(format!(" · {}", notes.join(" · ")));
1451    }
1452    fact
1453}
1454
1455/// The run's line: the feature's, or "Document desk · 10:31".
1456fn run_view(record: &Record, input: &ViewerInput<'_>) -> RunView {
1457    let text = record.display.run.clone().unwrap_or_else(|| match record.at {
1458        Some(at) => {
1459            format!("{} · {}", input.agent_name, at.with_timezone(&input.offset).format("%H:%M"))
1460        }
1461        None => input.agent_name.clone(),
1462    });
1463    RunView { text, agent: record.agent.clone(), call: call_words(record) }
1464}
1465
1466/// One answer, projected.
1467pub(crate) fn answer_view(record: &Record, input: &ViewerInput<'_>) -> AnswerView {
1468    let kind = kind_of(record);
1469    let (width, height) = (record.region_set.width, record.region_set.height);
1470    let order: Vec<usize> = match &record.page {
1471        Some(page) if !page.reading_order.is_empty() => page.reading_order.clone(),
1472        _ => (0..record.region_set.regions.len()).collect(),
1473    };
1474    let position: BTreeMap<usize, u32> =
1475        order.iter().enumerate().map(|(place, &index)| (index, place as u32 + 1)).collect();
1476    let measurement = record.measurements.first();
1477    let calibration_region = measurement.and_then(|m| m.calibration.region);
1478    let measured_text = |index: usize| {
1479        measurement
1480            .filter(|m| m.region == index)
1481            .and_then(|m| m.longest_mm)
1482            .map(|mm| format!("{mm:.1} mm"))
1483    };
1484    let tracks: BTreeMap<u64, &WireTrack> = record.tracks.iter().map(|t| (t.id, t)).collect();
1485    let segmented = record.calls.iter().any(|call| call.task == "segment");
1486
1487    let mut regions = Vec::new();
1488    for &index in &order {
1489        let Some(region) = record.region_set.regions.get(index) else { continue };
1490        let Some(bounds) = shape_bounds(&region.shape, width, height) else { continue };
1491        let shape = match &region.shape {
1492            WireShape::Point { .. } => ShapeKind::Point,
1493            WireShape::Box { .. } | WireShape::Other => ShapeKind::Box,
1494            WireShape::Polygon { .. } => ShapeKind::Polygon,
1495            WireShape::Mask { .. } => ShapeKind::Mask,
1496            WireShape::Keypoints { .. } => ShapeKind::Keypoints,
1497        };
1498        let block = record.page.as_ref().and_then(|page| page.blocks.get(index));
1499        let track = region.track.and_then(|id| tracks.get(&id).copied());
1500        let base_label = block
1501            .map(|b| b.kind.clone())
1502            .or_else(|| region.label.clone())
1503            .unwrap_or_else(|| "region".to_string());
1504        let blurred = track.is_some_and(|t| t.blurred);
1505        let label = if blurred { format!("{base_label} · blurred") } else { base_label.clone() };
1506        let text = block.map(|b| b.text.clone()).filter(|t| !t.is_empty());
1507        let measured = measured_text(index);
1508        let at_edge = bounds[0] <= 0.5
1509            || bounds[1] <= 0.5
1510            || bounds[2] >= f64::from(width) - 0.5
1511            || bounds[3] >= f64::from(height) - 0.5;
1512        let shape_word = if shape == ShapeKind::Mask { "mask" } else { "box" };
1513        let read_as = region.origin.escalated_from.as_ref().and_then(|from| from.text.clone());
1514        let detail = if let Some(text) = read_as.as_ref().or(text.as_ref()) {
1515            text.clone()
1516        } else if track.is_some() {
1517            String::new()
1518        } else {
1519            let mut words = vec![shape_word.to_string()];
1520            if let Some(mm) = &measured {
1521                words.push(mm.clone());
1522            } else if at_edge {
1523                words.push("at the edge".into());
1524            } else if calibration_region == Some(index) {
1525                words.push("calibration".into());
1526            }
1527            words.join(" · ")
1528        };
1529        // A page's region carries its block's confidence.
1530        let score = region.score.or(block.and_then(|b| b.confidence));
1531        let score_text = score.map(|s| format!("{s:.2}")).unwrap_or_default();
1532        let track_name = region.track.map(|id| format!("T{id}"));
1533        let tag = match (&track_name, kind) {
1534            (Some(name), _) => [
1535                Some(label.clone()),
1536                Some(name.clone()),
1537                (!score_text.is_empty()).then(|| score_text.clone()),
1538            ]
1539            .into_iter()
1540            .flatten()
1541            .collect::<Vec<_>>()
1542            .join(" · "),
1543            (None, PictureKind::Document) => {
1544                let number = position.get(&index).copied().unwrap_or(index as u32 + 1);
1545                format!("{number} · {base_label} · {score_text}")
1546            }
1547            _ => [
1548                Some(label.clone()),
1549                (!score_text.is_empty()).then(|| score_text.clone()),
1550                measured.clone(),
1551            ]
1552            .into_iter()
1553            .flatten()
1554            .collect::<Vec<_>>()
1555            .join(" · "),
1556        };
1557        let heading = match (kind, &track_name) {
1558            (_, Some(name)) => format!("{name} · {base_label}"),
1559            (PictureKind::Document, None) => {
1560                format!(
1561                    "{} · {base_label}",
1562                    position.get(&index).copied().unwrap_or(index as u32 + 1)
1563                )
1564            }
1565            _ => capitalised(&label),
1566        };
1567
1568        // The details (board choices V4–V6).
1569        let mut facts = Vec::new();
1570        let escalation = region.origin.escalated_from.as_ref().map(|from| {
1571            let call = record.calls.iter().find(|call| call.escalation.is_some());
1572            EscalationView {
1573                read_as: from.text.clone(),
1574                read_as_score: from.score,
1575                by: call.map_or_else(
1576                    || region.origin.backend.clone(),
1577                    |c| escalation_name(&c.backend, &c.locality),
1578                ),
1579                crop_digest: call.and_then(|c| c.egress.first()).map(|d| short_digest(d)),
1580            }
1581        });
1582        let primary = region
1583            .origin
1584            .escalated_from
1585            .as_ref()
1586            .map_or_else(|| region.origin.backend.clone(), |from| from.backend.clone());
1587        if let (Some(escalation), Some(text)) = (&escalation, &text) {
1588            let mut read_as = Fact::new("Read as");
1589            if let Some(was) = &escalation.read_as {
1590                read_as = read_as.mono(was.clone());
1591            }
1592            if let Some(score) = escalation.read_as_score {
1593                read_as = read_as.muted(format!(" · {score:.2}"));
1594            }
1595            facts.push(read_as);
1596            let mut now = Fact::new("Now").mono(text.clone()).muted(format!(
1597                " · {} read {} of it,",
1598                escalation.by,
1599                if escalation.crop_digest.is_some() { "a covered crop" } else { "a crop" }
1600            ));
1601            if let Some(digest) = &escalation.crop_digest {
1602                now = now.plain(" ").mono(digest.clone());
1603            }
1604            facts.push(now);
1605        }
1606        match (kind, &region.shape) {
1607            (PictureKind::Document, _) => {
1608                facts.push(Fact::new("Box").mono(box_words(bounds)).muted(" source pixels"));
1609                facts.push(model_fact(
1610                    "Model",
1611                    record,
1612                    &manifest_of_backend(record, region, &primary),
1613                    None,
1614                ));
1615            }
1616            (PictureKind::VideoFrame, _) => {
1617                if let Some(track) = track {
1618                    let mut seen = Fact::new("Seen");
1619                    // The stretch of the video this frame is in, else the first.
1620                    let at = record.video.as_ref().map_or(0.0, |video| video.at_s);
1621                    let span = track
1622                        .spans
1623                        .iter()
1624                        .find(|span| span[0] <= at && at <= span[1])
1625                        .or(track.spans.first());
1626                    if let Some(span) = span {
1627                        seen = seen.plain(format!(
1628                            "{} → {}",
1629                            video_time(span[0]),
1630                            video_time(span[1])
1631                        ));
1632                    }
1633                    facts.push(seen.muted(format!(" · {} frames", thousands(track.frames))));
1634                }
1635                facts.push(Fact::new("Box now").mono(box_words(bounds)));
1636                for call in answering_calls(record) {
1637                    match call.task.as_str() {
1638                        "detect" => facts.push(model_fact(
1639                            "Found by",
1640                            record,
1641                            &manifest_of(record, &call.backend),
1642                            None,
1643                        )),
1644                        "track" => {
1645                            let mut fact = Fact::new("Tracked by")
1646                                .plain(display_name(&call.backend, &record.models));
1647                            let mut note = Vec::new();
1648                            note.extend(call.library.clone());
1649                            note.push(place_of(&call.locality));
1650                            fact = fact.muted(format!(" · {}", note.join(", ")));
1651                            facts.push(fact);
1652                        }
1653                        _ => {}
1654                    }
1655                }
1656            }
1657            (PictureKind::Photo, WireShape::Mask { width: mw, height: mh, counts }) => {
1658                let area = mask_bounds(*mw, *mh, counts).map_or(0, |(_, area)| area);
1659                facts.push(
1660                    Fact::new("Shape")
1661                        .plain(format!("Mask, {} px · box ", thousands(area)))
1662                        .mono(box_words(bounds)),
1663                );
1664                photo_models(record, &mut facts, segmented);
1665            }
1666            (PictureKind::Photo, _) => {
1667                facts.push(Fact::new("Shape").plain("Box ").mono(box_words(bounds)));
1668                photo_models(record, &mut facts, false);
1669            }
1670        }
1671        facts.push(Fact::new("Answered in").plain(frame_words(&region.origin.frame)));
1672
1673        let (mask, polygon) = match &region.shape {
1674            WireShape::Mask { width, height, counts } => (
1675                Some(MaskView {
1676                    width: *width,
1677                    height: *height,
1678                    counts: counts.clone(),
1679                    area: mask_bounds(*width, *height, counts).map_or(0, |(_, area)| area),
1680                }),
1681                Vec::new(),
1682            ),
1683            WireShape::Polygon { points } => (None, points.clone()),
1684            _ => (None, Vec::new()),
1685        };
1686        regions.push(RegionView {
1687            index: index as u32,
1688            order: (kind == PictureKind::Document).then(|| position.get(&index).copied()).flatten(),
1689            label,
1690            shape,
1691            text,
1692            detail,
1693            score,
1694            score_text,
1695            track: region.track,
1696            track_name,
1697            x0: bounds[0],
1698            y0: bounds[1],
1699            x1: bounds[2],
1700            y1: bounds[3],
1701            box_text: box_words(bounds),
1702            mask,
1703            polygon,
1704            tag,
1705            heading,
1706            facts,
1707            chain: chain_words(record, &region.origin, shape),
1708            escalation,
1709            measurement: measured,
1710            at_edge,
1711            blurred,
1712        });
1713    }
1714    // Chips in the answer's own order (board choice V3).
1715    let mut labels: Vec<LabelCount> = Vec::new();
1716    let mut by_index: Vec<&RegionView> = regions.iter().collect();
1717    by_index.sort_by_key(|region| {
1718        if kind == PictureKind::Document { region.order.unwrap_or(0) } else { region.index }
1719    });
1720    for region in by_index {
1721        let label = region.label.trim_end_matches(" · blurred").to_string();
1722        match labels.iter_mut().find(|entry| entry.label == label) {
1723            Some(entry) => entry.count += 1,
1724            None => labels.push(LabelCount { label, count: 1 }),
1725        }
1726    }
1727    // A photo lists its measured region first, then the rest by score.
1728    if kind == PictureKind::Photo {
1729        let measured = measurement.map(|m| m.region as u32);
1730        regions.sort_by(|a, b| {
1731            let key = |r: &RegionView| (Some(r.index) != measured, r.shape != ShapeKind::Mask);
1732            key(a).cmp(&key(b)).then(b.score.unwrap_or(0.0).total_cmp(&a.score.unwrap_or(0.0)))
1733        });
1734        // The calibration reference goes last.
1735        if let Some(reference) = calibration_region
1736            && let Some(at) = regions.iter().position(|r| r.index as usize == reference)
1737        {
1738            let region = regions.remove(at);
1739            regions.push(region);
1740        }
1741    }
1742
1743    if kind == PictureKind::Document {
1744        // Chips in the order a page's kinds are read about: title first, then by first sight.
1745        labels.sort_by_key(|entry| match entry.label.as_str() {
1746            "title" => 0,
1747            "text" => 1,
1748            "table" => 2,
1749            "seal" => 3,
1750            "handwriting" => 4,
1751            "checkbox" => 5,
1752            _ => 6,
1753        });
1754    }
1755
1756    let duration: u64 = record.calls.iter().map(|call| call.duration_ms).sum();
1757    let cost: u64 = record.calls.iter().filter_map(|call| call.cost_micro_usd).sum();
1758    let stats = vec![
1759        format!("{} region{}", regions.len(), if regions.len() == 1 { "" } else { "s" }),
1760        seconds_words(duration),
1761        cost_words(cost),
1762    ];
1763
1764    let measurements = measurement.map(|m| {
1765        let mut tiles = Vec::new();
1766        if let Some(mm) = m.longest_mm {
1767            tiles.push(MeasureTile {
1768                label: "Longest".into(),
1769                value: format!("{mm:.1} mm"),
1770                uncertainty: format!("± {:.1} mm", m.longest_uncertainty_mm.unwrap_or(0.0)),
1771            });
1772        }
1773        if let Some(mm2) = m.area_mm2 {
1774            tiles.push(MeasureTile {
1775                label: "Area".into(),
1776                value: format!("{mm2:.1} mm²"),
1777                uncertainty: format!("± {:.1} mm²", m.area_uncertainty_mm2.unwrap_or(0.0)),
1778            });
1779        }
1780        let c = &m.calibration;
1781        let per_mm = if c.reference_mm > 0.0 { c.reference_px / c.reference_mm } else { 0.0 };
1782        MeasurementsView {
1783            region: m.region as u32,
1784            tiles,
1785            calibration: format!(
1786                "In {}, from {}: {:.1} mm is {} px, so {per_mm:.2} px per mm. Valid only in that plane.",
1787                c.plane,
1788                c.from,
1789                c.reference_mm,
1790                c.reference_px.round() as i64
1791            ),
1792            line: m.line,
1793        }
1794    });
1795
1796    let video = record.video.as_ref().map(|v| VideoView {
1797        at_text: video_time(v.at_s),
1798        length_text: video_length(v.length_s),
1799        frame_text: format!("frame {} · sampled {} a second", thousands(v.frame), v.sampled_per_s),
1800        at_s: v.at_s,
1801        length_s: v.length_s,
1802        tracks: record
1803            .tracks
1804            .iter()
1805            .map(|t| {
1806                let label = t.label.clone().unwrap_or_default();
1807                TrackView {
1808                    id: t.id,
1809                    name: format!("T{}", t.id),
1810                    label: if t.blurred { format!("{label} · blurred") } else { label },
1811                    frames_text: count_words(t.frames),
1812                    spans: t.spans.clone(),
1813                    trail: t.trail.clone(),
1814                    blurred: t.blurred,
1815                }
1816            })
1817            .collect(),
1818        note: "Tracks are anonymous and start again when the video is opened again. People are \
1819               blurred in every kept frame."
1820            .into(),
1821    });
1822
1823    let empty = regions.is_empty().then(|| empty_view(record, input, kind, cost));
1824    let selected = match kind {
1825        PictureKind::Document => regions
1826            .iter()
1827            .find(|r| r.escalation.is_some())
1828            .or_else(|| {
1829                regions
1830                    .iter()
1831                    .filter(|r| r.score.is_some_and(|s| s >= DEFAULT_MIN_SCORE))
1832                    .min_by(|a, b| a.score.unwrap_or(1.0).total_cmp(&b.score.unwrap_or(1.0)))
1833            })
1834            .or_else(|| regions.first())
1835            .map(|r| r.index),
1836        _ => regions.first().map(|r| r.index),
1837    };
1838    AnswerView {
1839        id: record.id(),
1840        tool: record.tool.clone(),
1841        name: answer_name(record),
1842        place: answer_place(record),
1843        regions,
1844        labels,
1845        stats,
1846        run: run_view(record, input),
1847        empty,
1848        measurements,
1849        video,
1850        selected,
1851    }
1852}
1853
1854fn manifest_of_backend(record: &Record, region: &WireRegion, backend: &str) -> String {
1855    if region.origin.backend == backend {
1856        region.origin.manifest.clone().unwrap_or_else(|| manifest_of(record, backend))
1857    } else {
1858        manifest_of(record, backend)
1859    }
1860}
1861
1862/// A photo's "Found by" and "Outlined by" lines.
1863fn photo_models(record: &Record, facts: &mut Vec<Fact>, segmented: bool) {
1864    for call in answering_calls(record) {
1865        let manifest = manifest_of(record, &call.backend);
1866        match call.task.as_str() {
1867            "detect" => facts.push(model_fact("Found by", record, &manifest, None)),
1868            "segment" if segmented => {
1869                facts.push(model_fact("Outlined by", record, &manifest, call.prompted.clone()));
1870            }
1871            "describe" => facts.push(model_fact("Described by", record, &manifest, None)),
1872            _ => {}
1873        }
1874    }
1875}
1876
1877/// "Nothing found … That is an answer, not an error." (board choice V12).
1878fn empty_view(record: &Record, input: &ViewerInput<'_>, kind: PictureKind, cost: u64) -> EmptyView {
1879    let call = answering_calls(record).next();
1880    let backend =
1881        call.map_or_else(|| record.tool.clone(), |c| display_name(&c.backend, &record.models));
1882    let picture = match kind {
1883        PictureKind::Document => "page",
1884        PictureKind::VideoFrame | PictureKind::Photo
1885            if record.image.provenance.get("kind").and_then(Value::as_str) == Some("camera") =>
1886        {
1887            "frame"
1888        }
1889        PictureKind::VideoFrame => "frame",
1890        PictureKind::Photo => "image",
1891    };
1892    let asked = record.display.asked.clone().or_else(|| asked_of(&record.args));
1893    let mut text = vec![FactPart {
1894        text: format!(
1895            "{backend} answered with an empty result: nothing in this {picture} matched "
1896        ),
1897        style: FactStyle::Plain,
1898    }];
1899    match &asked {
1900        Some(asked) => {
1901            text.push(FactPart { text: format!("“{asked}”"), style: FactStyle::Strong })
1902        }
1903        None => text.push(FactPart { text: "what it was asked".into(), style: FactStyle::Plain }),
1904    }
1905    text.push(FactPart {
1906        text: ". That is an answer, not an error.".into(),
1907        style: FactStyle::Plain,
1908    });
1909
1910    let mut asked_fact = Fact::new("Asked").mono(record.tool.clone());
1911    if let Some(asked) = &asked {
1912        let what = if record.args.get("concepts").is_some() { "concept" } else { "class" };
1913        asked_fact = asked_fact.plain(format!(" · {what} “{asked}”"));
1914    }
1915    asked_fact = asked_fact.plain(format!(" · {}", record.call_id));
1916    let mut facts = vec![asked_fact];
1917    if let Some(call) = call {
1918        let sent = if is_remote(&call.locality) {
1919            let mut fact = Fact::new("Sent").plain("A released copy to ");
1920            fact = fact.mono(hosts_of(&call.locality).join(", "));
1921            if let Some(covered) = &record.display.covered {
1922                fact = fact.plain(format!(" · {covered}"));
1923            }
1924            fact
1925        } else {
1926            Fact::new("Sent").plain("Nothing left this computer")
1927        };
1928        facts.push(sent);
1929    }
1930    let mut cost_fact = Fact::new("Cost").plain(cost_words(cost));
1931    if cost > 0 {
1932        cost_fact = cost_fact.muted(" · billed though nothing matched");
1933    }
1934    facts.push(cost_fact);
1935    facts.push(Fact::new("Run").plain(run_view(record, input).text));
1936    EmptyView {
1937        title: "Nothing found".into(),
1938        text,
1939        facts,
1940        hidden: vec![
1941            FactPart { text: "Hidden by your filters.".into(), style: FactStyle::Strong },
1942            FactPart {
1943                text: " “4 regions are hidden by Score at least 0.95.” ".into(),
1944                style: FactStyle::Plain,
1945            },
1946        ],
1947        failed: vec![
1948            FactPart { text: "The call failed.".into(), style: FactStyle::Strong },
1949            FactPart {
1950                text: format!(
1951                    " “{backend} was rate limited; tried 3 times.” No answer, so nothing to show or save."
1952                ),
1953                style: FactStyle::Plain,
1954            },
1955        ],
1956    }
1957}
1958
1959/// The viewer's title and meta line for `record`.
1960fn title_of(record: &Record) -> (String, String) {
1961    let (w, h) = (record.image.width, record.image.height);
1962    let provenance = &record.image.provenance;
1963    let page = (provenance.get("kind").and_then(Value::as_str) == Some("documentPage"))
1964        .then(|| provenance.get("page").and_then(Value::as_u64).unwrap_or(1));
1965    let name = record.image.name.clone().filter(|name| !name.starts_with("sha256:"));
1966    let stem = name.as_deref().map(|n| n.rsplit_once('.').map_or(n, |(stem, _)| stem).to_string());
1967    let title = record.display.title.clone().unwrap_or_else(|| match (&stem, page) {
1968        (Some(stem), Some(page)) => format!("{stem} · page {page}"),
1969        (Some(stem), None) => stem.clone(),
1970        (None, Some(page)) => format!("Page {page}"),
1971        (None, None) => "An image".to_string(),
1972    });
1973    let meta = record.display.meta.clone().unwrap_or_else(|| {
1974        let mut parts = vec![format!("{w} × {h}")];
1975        if let Some(page) = page {
1976            let dpi = provenance.get("dpi").and_then(Value::as_u64);
1977            let doc = document_name(record);
1978            parts.push(match dpi {
1979                Some(dpi) => format!("{doc}, page {page} at {dpi} dpi"),
1980                None => format!("{doc}, page {page}"),
1981            });
1982        } else if let Some(name) = &name {
1983            parts.push(name.clone());
1984        }
1985        if let Some(kept) = &record.display.kept_until {
1986            parts.push(format!("kept as evidence until {kept}"));
1987        }
1988        parts.join(" · ")
1989    });
1990    (title, meta)
1991}
1992
1993/// The web home's route for image `digest` of `session`, under `/api/surface`.
1994pub(crate) fn image_href(session: &str, digest: &str) -> String {
1995    format!(
1996        "/api/surface/vision/{}/images/{}",
1997        crate::evidence::percent_segment(session),
1998        crate::evidence::percent_segment(digest)
1999    )
2000}
2001
2002/// Where the viewer opens image `image` of `session` in the web home.
2003pub fn viewer_path(session: &str, image: &str) -> String {
2004    format!(
2005        "/ui/vision/{}/{}",
2006        crate::evidence::percent_segment(session),
2007        crate::evidence::percent_segment(image)
2008    )
2009}
2010
2011/// A slug for a case name: "inv-2291-p1-handwriting".
2012fn slug(text: &str) -> String {
2013    let mut out = String::new();
2014    for c in text.chars().flat_map(char::to_lowercase) {
2015        if c.is_ascii_alphanumeric() {
2016            out.push(c);
2017        } else if !out.ends_with('-') && !out.is_empty() {
2018            out.push('-');
2019        }
2020    }
2021    out.trim_end_matches('-').to_string()
2022}
2023
2024/// The viewer of the image `records` (every answer for one digest, oldest first) are about.
2025/// `answer` picks the answer shown — the newest otherwise — and `compare` a second one.
2026pub(crate) fn view(
2027    records: &[Record],
2028    answer: Option<&str>,
2029    compare: Option<&str>,
2030    input: &ViewerInput<'_>,
2031) -> Option<ViewerView> {
2032    let newest = records.last()?;
2033    let shown = answer.and_then(|id| find(records, id)).unwrap_or(newest);
2034    let (title, meta) = title_of(shown);
2035    let shown_view = answer_view(shown, input);
2036    let compare = compare
2037        .and_then(|id| find(records, id).filter(|other| other.id() != shown.id()))
2038        .map(|other| compare_view(shown_view.clone(), answer_view(other, input)));
2039    let selected = shown_view
2040        .selected
2041        .and_then(|index| shown_view.regions.iter().find(|r| r.index == index))
2042        .map_or_else(|| "region".to_string(), |r| r.label.clone());
2043    let files = input.files.clone();
2044    let file = files.first().cloned().unwrap_or_else(|| "evals/vision/examples.test.json".into());
2045    Some(ViewerView {
2046        session_id: input.session.to_string(),
2047        image: ViewerImage {
2048            digest: shown.image.digest.clone(),
2049            digest_short: short_digest(&shown.image.digest),
2050            width: shown.image.width,
2051            height: shown.image.height,
2052            mime_type: shown.image.mime_type.clone(),
2053            href: image_href(input.session, &shown.image.digest),
2054        },
2055        kind: kind_of(shown),
2056        title: title.clone(),
2057        meta,
2058        agent: shown.agent.clone(),
2059        agent_name: input.agent_name.clone(),
2060        answers: records
2061            .iter()
2062            .rev()
2063            .map(|record| AnswerChoice {
2064                id: record.id(),
2065                name: answer_name(record),
2066                place: answer_place(record),
2067                tool: record.tool.clone(),
2068            })
2069            .collect(),
2070        answer: Some(shown_view),
2071        compare,
2072        caption: shown.display.caption.clone(),
2073        min_score: shown.display.min_score.unwrap_or(DEFAULT_MIN_SCORE),
2074        examples: ExamplesView {
2075            can_save: input.can_save,
2076            files,
2077            file,
2078            // "INV-2291 · page 1" and "handwriting": `inv-2291-p1-handwriting`.
2079            case_name: slug(&format!("{} {selected}", title.replace("page ", "p"))),
2080        },
2081    })
2082}
2083
2084/// The size of an encoded PNG, GIF or JPEG from its header; `None` for anything else.
2085pub(crate) fn encoded_size(bytes: &[u8]) -> Option<(u32, u32)> {
2086    let be32 =
2087        |at: usize| bytes.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
2088    let be16 =
2089        |at: usize| bytes.get(at..at + 2).map(|b| u32::from(u16::from_be_bytes([b[0], b[1]])));
2090    let le16 =
2091        |at: usize| bytes.get(at..at + 2).map(|b| u32::from(u16::from_le_bytes([b[0], b[1]])));
2092    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
2093        return Some((be32(16)?, be32(20)?));
2094    }
2095    if bytes.starts_with(b"GIF8") {
2096        return Some((le16(6)?, le16(8)?));
2097    }
2098    if bytes.starts_with(&[0xFF, 0xD8]) {
2099        // Walk the segments to the first start-of-frame marker.
2100        let mut at = 2;
2101        while at + 4 <= bytes.len() {
2102            if bytes[at] != 0xFF {
2103                return None;
2104            }
2105            let marker = bytes[at + 1];
2106            let length = be16(at + 2)? as usize;
2107            if matches!(marker, 0xC0..=0xCF) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
2108                return Some((be16(at + 7)?, be16(at + 5)?));
2109            }
2110            at += 2 + length;
2111        }
2112    }
2113    None
2114}
2115
2116/// The viewer of an image nothing has answered for yet: the picture alone, with the answers
2117/// list empty, so a person opening a held call's source image sees it before the call runs.
2118pub(crate) fn unanswered(
2119    session: &str,
2120    image: &str,
2121    digest: &str,
2122    bytes: &crate::evidence::EvidenceBytes,
2123    input: &ViewerInput<'_>,
2124) -> ViewerView {
2125    let (width, height) = encoded_size(&bytes.bytes).unwrap_or((0, 0));
2126    let name = (!image.starts_with("sha256:")).then(|| image.to_string());
2127    let title = name.as_deref().map_or_else(
2128        || "An image".to_string(),
2129        |n| n.rsplit_once('.').map_or(n, |(stem, _)| stem).to_string(),
2130    );
2131    let mut meta = vec![format!("{width} × {height}")];
2132    meta.extend(name);
2133    meta.push("nothing has answered for it yet".into());
2134    ViewerView {
2135        session_id: session.to_string(),
2136        image: ViewerImage {
2137            digest: digest.to_string(),
2138            digest_short: short_digest(digest),
2139            width,
2140            height,
2141            mime_type: bytes.mime_type.clone(),
2142            href: image_href(session, digest),
2143        },
2144        kind: PictureKind::Photo,
2145        title: title.clone(),
2146        meta: meta.join(" · "),
2147        agent: String::new(),
2148        agent_name: input.agent_name.clone(),
2149        answers: Vec::new(),
2150        answer: None,
2151        compare: None,
2152        caption: None,
2153        min_score: DEFAULT_MIN_SCORE,
2154        examples: ExamplesView {
2155            can_save: false,
2156            files: input.files.clone(),
2157            file: input.files.first().cloned().unwrap_or_default(),
2158            case_name: slug(&title),
2159        },
2160    }
2161}
2162
2163// ---------------------------------------------------------------------------
2164// Comparison
2165// ---------------------------------------------------------------------------
2166
2167/// The IoU two regions need to count as the same one.
2168const SAME_REGION: f64 = 0.5;
2169
2170fn reading(region: &RegionView) -> String {
2171    region.text.clone().unwrap_or_else(|| region.label.clone())
2172}
2173
2174fn reading_with_score(region: &RegionView) -> String {
2175    if region.score_text.is_empty() {
2176        reading(region)
2177    } else {
2178        format!("{} · {}", reading(region), region.score_text)
2179    }
2180}
2181
2182/// The two answers matched region by region, greedily by overlap (board choice V11).
2183pub(crate) fn compare_view(a: AnswerView, b: AnswerView) -> CompareView {
2184    let bounds = |r: &RegionView| [r.x0, r.y0, r.x1, r.y1];
2185    let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
2186    for (i, ra) in a.regions.iter().enumerate() {
2187        for (j, rb) in b.regions.iter().enumerate() {
2188            let overlap = iou(bounds(ra), bounds(rb));
2189            if overlap >= SAME_REGION {
2190                pairs.push((overlap, i, j));
2191            }
2192        }
2193    }
2194    pairs.sort_by(|x, y| y.0.total_cmp(&x.0));
2195    let (mut matched_a, mut matched_b) = (vec![None; a.regions.len()], vec![None; b.regions.len()]);
2196    let mut overlaps = Vec::new();
2197    for (overlap, i, j) in pairs {
2198        if matched_a[i].is_none() && matched_b[j].is_none() {
2199            matched_a[i] = Some(j);
2200            matched_b[j] = Some(i);
2201            overlaps.push(overlap);
2202        }
2203    }
2204    let (mut marks_a, mut marks_b) = (Vec::new(), Vec::new());
2205    let (mut agree, mut differ, mut only_one) = (0u32, 0u32, 0u32);
2206    let mut differences = Vec::new();
2207    let number = |r: &RegionView| r.order.unwrap_or(r.index + 1);
2208    for (i, ra) in a.regions.iter().enumerate() {
2209        match matched_a[i] {
2210            Some(j) => {
2211                let rb = &b.regions[j];
2212                if reading(ra) == reading(rb) {
2213                    agree += 1;
2214                    marks_a.push(CompareMark {
2215                        index: ra.index,
2216                        agreement: Agreement::Agree,
2217                        tag: None,
2218                    });
2219                } else {
2220                    differ += 1;
2221                    marks_a.push(CompareMark {
2222                        index: ra.index,
2223                        agreement: Agreement::Differ,
2224                        tag: Some(reading(ra)),
2225                    });
2226                    differences.push(Difference {
2227                        number: number(ra),
2228                        label: ra.label.clone(),
2229                        title: format!("{} · read differently", ra.label),
2230                        a: reading_with_score(ra),
2231                        b: reading_with_score(rb),
2232                        a_region: Some(ra.index),
2233                        b_region: Some(rb.index),
2234                    });
2235                }
2236            }
2237            None => {
2238                only_one += 1;
2239                marks_a.push(CompareMark {
2240                    index: ra.index,
2241                    agreement: Agreement::OnlyHere,
2242                    tag: Some("only here".into()),
2243                });
2244                differences.push(Difference {
2245                    number: number(ra),
2246                    label: ra.label.clone(),
2247                    title: format!("{} · only A found it", ra.label),
2248                    a: reading_with_score(ra),
2249                    b: "—".into(),
2250                    a_region: Some(ra.index),
2251                    b_region: None,
2252                });
2253            }
2254        }
2255    }
2256    for (j, rb) in b.regions.iter().enumerate() {
2257        match matched_b[j] {
2258            Some(i) => {
2259                let ra = &a.regions[i];
2260                let same = reading(ra) == reading(rb);
2261                marks_b.push(CompareMark {
2262                    index: rb.index,
2263                    agreement: if same { Agreement::Agree } else { Agreement::Differ },
2264                    tag: (!same).then(|| reading(rb)),
2265                });
2266            }
2267            None => {
2268                only_one += 1;
2269                marks_b.push(CompareMark {
2270                    index: rb.index,
2271                    agreement: Agreement::OnlyHere,
2272                    tag: Some("only here".into()),
2273                });
2274                differences.push(Difference {
2275                    number: number(rb),
2276                    label: rb.label.clone(),
2277                    title: format!("{} · only B found it", rb.label),
2278                    a: "—".into(),
2279                    b: reading_with_score(rb),
2280                    a_region: None,
2281                    b_region: Some(rb.index),
2282                });
2283            }
2284        }
2285    }
2286    // Readings that differ first, the least sure first; then what only one answer found.
2287    let score_of = |difference: &Difference| {
2288        let region = difference.a_region.and_then(|i| a.regions.iter().find(|r| r.index == i));
2289        region.and_then(|r| r.score).unwrap_or(1.0)
2290    };
2291    differences.sort_by(|x, y| {
2292        let only = |d: &Difference| d.a_region.is_none() || d.b_region.is_none();
2293        only(x).cmp(&only(y)).then(score_of(x).total_cmp(&score_of(y)))
2294    });
2295    let mean = if overlaps.is_empty() {
2296        0.0
2297    } else {
2298        overlaps.iter().sum::<f64>() / overlaps.len() as f64
2299    };
2300    let overlap_text = if overlaps.is_empty() {
2301        "The two answers found no region in common.".to_string()
2302    } else {
2303        let closely = if mean >= 0.9 {
2304            "closely"
2305        } else if mean >= 0.7 {
2306            "well"
2307        } else {
2308            "loosely"
2309        };
2310        format!("Where both found a region, the boxes overlap {closely} (mean IoU {mean:.2}).")
2311    };
2312    let short = |name: &str| {
2313        name.split_whitespace().next().unwrap_or(name).trim_end_matches("-1.6").to_string()
2314    };
2315    CompareView {
2316        a: ComparePane { short_name: short(&a.name), answer: a, marks: marks_a },
2317        b: ComparePane { short_name: short(&b.name), answer: b, marks: marks_b },
2318        agree,
2319        differ,
2320        only_one,
2321        overlap_text,
2322        differences,
2323    }
2324}
2325
2326// ---------------------------------------------------------------------------
2327// Labelled examples
2328// ---------------------------------------------------------------------------
2329
2330/// What an example holds (board choice V13).
2331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2332#[serde(rename_all = "camelCase")]
2333pub enum ExampleScope {
2334    /// This region only.
2335    Region,
2336    /// Every region on the page, with this correction.
2337    Page,
2338    /// Nothing: the answer is that nothing is there.
2339    Nothing,
2340}
2341
2342/// A region as a person corrected or drew it.
2343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
2344#[serde(rename_all = "camelCase")]
2345pub struct RegionCorrection {
2346    /// The region it corrects, by its index in the answer; absent for a region the person
2347    /// drew.
2348    #[serde(default, skip_serializing_if = "Option::is_none")]
2349    pub index: Option<u32>,
2350    /// The label.
2351    pub label: String,
2352    /// The text, for a page's block.
2353    #[serde(default, skip_serializing_if = "Option::is_none")]
2354    pub text: Option<String>,
2355    /// The box `[x0, y0, x1, y1]` in the image's pixels.
2356    #[serde(rename = "box")]
2357    pub bbox: [f64; 4],
2358}
2359
2360/// `POST /api/surface/vision/{session}/examples`: save a labelled example (board choices V11,
2361/// V12, V13).
2362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
2363#[serde(rename_all = "camelCase")]
2364pub struct LabelledExample {
2365    /// The answer the example starts from.
2366    pub answer: String,
2367    /// The eval fixtures file, relative to the fixtures' root: `evals/vision/invoices.test.json`.
2368    pub file: String,
2369    /// The case's name: `inv-2291-p1-po-number`.
2370    pub case_name: String,
2371    /// What the example holds.
2372    pub scope: ExampleScope,
2373    /// The region, corrected, kept or drawn; absent for an example with nothing in it.
2374    #[serde(default, skip_serializing_if = "Option::is_none")]
2375    pub region: Option<RegionCorrection>,
2376}
2377
2378/// What saving an example did.
2379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2380#[serde(rename_all = "camelCase")]
2381pub struct SavedExample {
2382    /// The file, relative to the fixtures' root.
2383    pub file: String,
2384    /// The case's name.
2385    pub case_name: String,
2386    /// The image file the case points at, relative to the eval file.
2387    pub image: String,
2388    /// "Saved to evals/vision/invoices.test.json as inv-2291-p1-po-number. The run's answer
2389    /// stays as it was."
2390    pub text: String,
2391}
2392
2393/// The extension a fixture image takes for its MIME type.
2394pub(crate) fn extension_of(mime: &str) -> &'static str {
2395    match mime {
2396        "image/jpeg" => "jpg",
2397        "image/webp" => "webp",
2398        "image/gif" => "gif",
2399        _ => "png",
2400    }
2401}
2402
2403/// The image path a case names, relative to its eval file: `images/<hex>.png`.
2404pub(crate) fn fixture_image_path(digest: &str, mime: &str) -> String {
2405    let hex = digest.strip_prefix("sha256:").unwrap_or(digest);
2406    format!("images/{hex}.{}", extension_of(mime))
2407}
2408
2409/// Checks a fixtures file name a person picked: relative, inside the root, a `.test.json`.
2410///
2411/// # Errors
2412///
2413/// A sentence for the person.
2414pub(crate) fn check_file(file: &str) -> std::result::Result<(), String> {
2415    let path = std::path::Path::new(file);
2416    let inside = path.components().all(|part| matches!(part, std::path::Component::Normal(_)));
2417    if file.is_empty() || !inside {
2418        return Err(format!("“{file}” must be a path inside the eval fixtures folder"));
2419    }
2420    if !file.ends_with(".test.json") {
2421        return Err(format!("“{file}” must end in .test.json, the files `cargo adk eval` reads"));
2422    }
2423    Ok(())
2424}
2425
2426/// Checks a case name: letters, digits, `-`, `_` and `.`.
2427///
2428/// # Errors
2429///
2430/// A sentence for the person.
2431pub(crate) fn check_case_name(name: &str) -> std::result::Result<(), String> {
2432    let ok = !name.is_empty()
2433        && name.len() <= 120
2434        && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
2435    if ok {
2436        Ok(())
2437    } else {
2438        Err(format!("the case name “{name}” takes letters, digits, - _ and . only"))
2439    }
2440}
2441
2442/// The `adk-eval` case an example makes of `record` (board choices V11–V13): a turn that shows
2443/// the image by path and digest, asks what the call asked, and expects the regions or text the
2444/// person kept, in the image's pixels.
2445///
2446/// # Errors
2447///
2448/// A sentence for the person when the example does not fit the answer.
2449pub(crate) fn example_case(
2450    record: &Record,
2451    example: &LabelledExample,
2452) -> std::result::Result<Value, String> {
2453    check_case_name(&example.case_name)?;
2454    let (w, h) = (f64::from(record.image.width), f64::from(record.image.height));
2455    if let Some(region) = &example.region {
2456        let [x0, y0, x1, y1] = region.bbox;
2457        if !(x0 >= 0.0 && y0 >= 0.0 && x1 <= w && y1 <= h && x0 < x1 && y0 < y1) {
2458            return Err(format!("the box must lie inside the {w} × {h} image and cover something"));
2459        }
2460        if region.label.trim().is_empty() {
2461            return Err("a region needs a label".into());
2462        }
2463    }
2464    let round = |v: f64| (v * 10.0).round() / 10.0;
2465    let boxed = |b: [f64; 4]| json!([round(b[0]), round(b[1]), round(b[2]), round(b[3])]);
2466    let read = record.tool == "vision_read";
2467    let blocks = record.page.as_ref().map(|page| &page.blocks);
2468    let corrected_index = example.region.as_ref().and_then(|r| r.index).map(|i| i as usize);
2469
2470    let (prompt, expected) = match (example.scope, &example.region) {
2471        (ExampleScope::Nothing, _) => {
2472            let asked = asked_of(&record.args).unwrap_or_else(|| "anything".to_string());
2473            (format!("Find every {asked} in this image."), json!({ "count": 0 }))
2474        }
2475        (ExampleScope::Region, None) | (ExampleScope::Page, None) => {
2476            return Err("pick a region to keep, or save an example with nothing in it".into());
2477        }
2478        (ExampleScope::Region, Some(region)) if read => {
2479            let text = region.text.clone().unwrap_or_default();
2480            let b = region.bbox;
2481            (
2482                format!(
2483                    "Read the {} in the region [{}, {}, {}, {}] of this page.",
2484                    region.label,
2485                    round(b[0]),
2486                    round(b[1]),
2487                    round(b[2]),
2488                    round(b[3])
2489                ),
2490                json!({ "text": text }),
2491            )
2492        }
2493        (ExampleScope::Page, Some(region)) if read => {
2494            let order: Vec<usize> = record
2495                .page
2496                .as_ref()
2497                .map(|page| page.reading_order.clone())
2498                .filter(|order| !order.is_empty())
2499                .unwrap_or_else(|| (0..blocks.map_or(0, Vec::len)).collect());
2500            let mut lines: Vec<String> = Vec::new();
2501            for index in order {
2502                if Some(index) == corrected_index {
2503                    lines.extend(region.text.clone());
2504                } else if let Some(block) = blocks.and_then(|b| b.get(index)) {
2505                    lines.push(block.text.clone());
2506                }
2507            }
2508            if corrected_index.is_none() {
2509                lines.extend(region.text.clone());
2510            }
2511            ("Read this page.".to_string(), json!({ "text": lines.join("\n") }))
2512        }
2513        (ExampleScope::Region, Some(region)) => (
2514            format!("Find every {} in this image.", region.label),
2515            json!({ "regions": [{ "label": region.label, "box": boxed(region.bbox) }] }),
2516        ),
2517        (ExampleScope::Page, Some(region)) => {
2518            let mut regions = Vec::new();
2519            for (index, r) in record.region_set.regions.iter().enumerate() {
2520                if Some(index) == corrected_index {
2521                    continue;
2522                }
2523                let Some(bounds) = shape_bounds(&r.shape, record.image.width, record.image.height)
2524                else {
2525                    continue;
2526                };
2527                let label = r.label.clone().unwrap_or_else(|| "region".into());
2528                regions.push(json!({ "label": label, "box": boxed(bounds) }));
2529            }
2530            regions.push(json!({ "label": region.label, "box": boxed(region.bbox) }));
2531            let asked = asked_of(&record.args).unwrap_or_else(|| region.label.clone());
2532            (format!("Find every {asked} in this image."), json!({ "regions": regions }))
2533        }
2534    };
2535    let backend = answer_name(record);
2536    Ok(json!({
2537        "eval_id": example.case_name,
2538        "description": format!(
2539            "Kept in the annotated viewer from {} {} ({backend}) on {}",
2540            record.tool,
2541            record.call_id,
2542            short_digest(&record.image.digest)
2543        ),
2544        "conversation": [{
2545            "invocation_id": "t0",
2546            "user_content": {
2547                "role": "user",
2548                "parts": [
2549                    { "image": {
2550                        "path": fixture_image_path(&record.image.digest, &record.image.mime_type),
2551                        "digest": record.image.digest,
2552                    } },
2553                    { "text": prompt },
2554                ],
2555            },
2556            "expected_vision": expected,
2557        }],
2558        "tags": ["vision", record.tool.trim_start_matches("vision_"), "annotated-viewer"],
2559    }))
2560}
2561
2562/// `set` (an eval set file's JSON, or nothing for a new file) with `case` in it: a case of the
2563/// same name is replaced.
2564pub(crate) fn with_case(set: Option<Value>, file: &str, case: Value) -> Value {
2565    let mut set = set.unwrap_or_else(|| {
2566        let stem = file.rsplit('/').next().unwrap_or(file).trim_end_matches(".test.json");
2567        json!({
2568            "eval_set_id": stem,
2569            "name": stem,
2570            "description": "Labelled examples kept in the annotated viewer",
2571            "eval_cases": [],
2572        })
2573    });
2574    let name = case.get("eval_id").cloned();
2575    if let Some(cases) = set.get_mut("eval_cases").and_then(Value::as_array_mut) {
2576        cases.retain(|existing| existing.get("eval_id") != name.as_ref());
2577        cases.push(case);
2578    } else {
2579        set["eval_cases"] = json!([case]);
2580    }
2581    set
2582}
2583
2584#[cfg(test)]
2585mod tests {
2586    use super::*;
2587    use proptest::prelude::*;
2588
2589    /// A one-region `vision_detect` record over a `w` × `h` image, its box `b` answered in
2590    /// model-input pixels through `steps`.
2591    fn one_box(w: u32, h: u32, b: [f64; 4], steps: Value) -> Record {
2592        let origin = json!({
2593            "backend": "rf-detr-s",
2594            "frame": { "kind": "modelInput", "width": 640, "height": 640, "letterbox": "center" },
2595            "chain": { "sourceWidth": w, "sourceHeight": h, "steps": steps },
2596        });
2597        Record::parse(json!({
2598            "tool": "vision_detect",
2599            "callId": "c-1",
2600            "agent": "desk",
2601            "image": { "digest": "sha256:00", "width": w, "height": h },
2602            "regionSet": { "image": "sha256:00", "width": w, "height": h, "regions": [
2603                { "shape": { "kind": "box", "x0": b[0], "y0": b[1], "x1": b[2], "y1": b[3] }, "label": "part", "score": 0.9, "origin": origin },
2604            ] },
2605        }))
2606        .unwrap()
2607    }
2608
2609    proptest! {
2610        #![proptest_config(ProptestConfig::with_cases(128))]
2611
2612        /// A point carried into the backend's pixels and back is the same source pixel, for
2613        /// any crop, resize, padding and turn.
2614        #[test]
2615        fn the_chain_maps_back_to_source_pixels(
2616            (w, h) in (16u32..4000, 16u32..4000),
2617            crop in (0.0f64..0.4, 0.0f64..0.4, 0.5f64..1.0, 0.5f64..1.0),
2618            target in (64u32..2048, 64u32..2048),
2619            pad in (0u32..300, 0u32..300, 0u32..300, 0u32..300),
2620            turns in 0u8..4,
2621            at in (0.0f64..1.0, 0.0f64..1.0),
2622        ) {
2623            let (cx, cy) = ((crop.0 * f64::from(w)) as u32, (crop.1 * f64::from(h)) as u32);
2624            let cw = ((crop.2 * f64::from(w - cx)) as u32).max(1);
2625            let ch = ((crop.3 * f64::from(h - cy)) as u32).max(1);
2626            let chain = WireChain {
2627                source_width: w,
2628                source_height: h,
2629                steps: vec![
2630                    WireTransform::Crop { x: cx, y: cy, width: cw, height: ch },
2631                    WireTransform::Resize { width: target.0, height: target.1 },
2632                    WireTransform::Pad { left: pad.0, top: pad.1, right: pad.2, bottom: pad.3 },
2633                    WireTransform::Rotate { quarter_turns: turns },
2634                ],
2635            };
2636            let point = [f64::from(cx) + at.0 * f64::from(cw), f64::from(cy) + at.1 * f64::from(ch)];
2637            let back = to_source(&chain, to_backend(&chain, point));
2638            prop_assert!((back[0] - point[0]).abs() < 1e-6 && (back[1] - point[1]).abs() < 1e-6, "{point:?} -> {back:?}");
2639        }
2640
2641        /// The box the viewer draws and lists is the RegionSet's box in source pixels, clamped
2642        /// to the image, whatever frame and chain the backend answered through.
2643        #[test]
2644        fn shown_coordinates_are_source_pixels(
2645            (w, h) in (32u32..3000, 32u32..3000),
2646            corner in (-50.0f64..1.2, -50.0f64..1.2),
2647            size in (0.02f64..0.9, 0.02f64..0.9),
2648            letterbox in any::<bool>(),
2649        ) {
2650            let x0 = corner.0 * f64::from(w);
2651            let y0 = corner.1 * f64::from(h);
2652            let b = [x0, y0, x0 + size.0 * f64::from(w), y0 + size.1 * f64::from(h)];
2653            let steps = if letterbox {
2654                json!([{ "op": "resize", "width": 640, "height": 360 }, { "op": "pad", "left": 0, "top": 140, "right": 0, "bottom": 140 }])
2655            } else {
2656                json!([])
2657            };
2658            let record = one_box(w, h, b, steps);
2659            let input = ViewerInput {
2660                session: "s",
2661                agent_name: "Desk".into(),
2662                offset: FixedOffset::east_opt(0).unwrap(),
2663                can_save: false,
2664                files: Vec::new(),
2665            };
2666            let view = answer_view(&record, &input);
2667            let clamped = [
2668                b[0].clamp(0.0, f64::from(w)),
2669                b[1].clamp(0.0, f64::from(h)),
2670                b[2].clamp(0.0, f64::from(w)),
2671                b[3].clamp(0.0, f64::from(h)),
2672            ];
2673            if clamped[2] > clamped[0] && clamped[3] > clamped[1] {
2674                prop_assert_eq!(view.regions.len(), 1);
2675                let region = &view.regions[0];
2676                prop_assert_eq!([region.x0, region.y0, region.x1, region.y1], clamped);
2677                prop_assert_eq!(&region.box_text, &box_words(clamped));
2678            } else {
2679                // A box wholly outside the image draws nothing.
2680                prop_assert!(view.regions.is_empty());
2681            }
2682        }
2683
2684        /// A mask's bounds and area are the rectangle of pixels it sets.
2685        #[test]
2686        fn a_masks_bounds_are_the_pixels_it_sets(
2687            (w, h) in (2u32..40, 2u32..40),
2688            rect in (0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0),
2689        ) {
2690            let (x0, x1) = ((rect.0 * f64::from(w - 1)) as u32, (rect.2 * f64::from(w - 1)) as u32);
2691            let (y0, y1) = ((rect.1 * f64::from(h - 1)) as u32, (rect.3 * f64::from(h - 1)) as u32);
2692            let (x0, x1, y0, y1) = (x0.min(x1), x0.max(x1) + 1, y0.min(y1), y0.max(y1) + 1);
2693            let mut counts = Vec::new();
2694            let (mut current, mut run) = (false, 0u32);
2695            for x in 0..w {
2696                for y in 0..h {
2697                    let set = (x0..x1).contains(&x) && (y0..y1).contains(&y);
2698                    if set == current {
2699                        run += 1;
2700                    } else {
2701                        counts.push(run);
2702                        current = set;
2703                        run = 1;
2704                    }
2705                }
2706            }
2707            counts.push(run);
2708            let (bounds, area) = mask_bounds(w, h, &counts).unwrap();
2709            prop_assert_eq!(bounds, [f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)]);
2710            prop_assert_eq!(area, u64::from((x1 - x0) * (y1 - y0)));
2711        }
2712    }
2713
2714    fn chain(steps: Vec<WireTransform>) -> WireChain {
2715        WireChain { source_width: 1654, source_height: 2339, steps }
2716    }
2717
2718    #[test]
2719    fn a_letterboxed_page_maps_back_to_its_pixels() {
2720        let chain = chain(vec![
2721            WireTransform::Resize { width: 679, height: 960 },
2722            WireTransform::Pad { left: 140, top: 0, right: 141, bottom: 0 },
2723        ]);
2724        assert_eq!(chain_sizes(&chain), vec![(1654, 2339), (679, 960), (960, 960)]);
2725        let there = to_backend(&chain, [1250.0, 466.0]);
2726        let back = to_source(&chain, there);
2727        assert!((back[0] - 1250.0).abs() < 1e-6 && (back[1] - 466.0).abs() < 1e-6, "{back:?}");
2728        assert_eq!(pad_words(140, 0, 141, 0, (960, 960)), "Padded 140 left, 141 right · 960 × 960");
2729        assert_eq!(
2730            pad_words(0, 224, 0, 224, (1024, 1024)),
2731            "Padded 224 top and bottom · 1024 × 1024"
2732        );
2733    }
2734
2735    #[test]
2736    fn a_mask_is_bounded_by_the_pixels_it_sets() {
2737        // A 4 × 3 raster with (1, 1) and (2, 1) set: column-major, unset run first.
2738        assert_eq!(mask_bounds(4, 3, &[4, 1, 2, 1, 4]), Some(([1.0, 1.0, 3.0, 2.0], 2)));
2739        assert_eq!(mask_bounds(4, 3, &[12]), None);
2740    }
2741
2742    #[test]
2743    fn overlap_is_symmetric_and_whole_for_one_box() {
2744        let a = [0.0, 0.0, 10.0, 10.0];
2745        let b = [5.0, 0.0, 15.0, 10.0];
2746        assert_eq!(iou(a, a), 1.0);
2747        assert_eq!(iou(a, b), iou(b, a));
2748        assert!((iou(a, b) - 50.0 / 150.0).abs() < 1e-9);
2749    }
2750
2751    #[test]
2752    fn files_stay_inside_the_fixtures_folder() {
2753        assert!(check_file("evals/vision/invoices.test.json").is_ok());
2754        assert!(check_file("../invoices.test.json").is_err());
2755        assert!(check_file("/etc/invoices.test.json").is_err());
2756        assert!(check_file("evals/vision/invoices.json").is_err());
2757        assert!(check_case_name("inv-2291-p1-po-number").is_ok());
2758        assert!(check_case_name("a/b").is_err());
2759    }
2760
2761    #[test]
2762    fn words_read_as_the_boards() {
2763        assert_eq!(box_words([1250.0, 466.2, 1531.6, 540.0]), "1250, 466 → 1532, 540");
2764        assert_eq!(thousands(19_023), "19,023");
2765        assert_eq!(count_words(1_200), "1.2k");
2766        assert_eq!(video_time(634.1), "10:34.1");
2767        assert_eq!(video_length(1_200.0), "20:00");
2768        assert_eq!(cost_words(2_500), "$0.0025");
2769        assert_eq!(cost_words(0), "$0");
2770        assert_eq!(seconds_words(14_800), "14.8 s");
2771        assert_eq!(slug("INV-2291 · page 1 handwriting"), "inv-2291-page-1-handwriting");
2772        assert_eq!(
2773            frame_words(&WireFrame::ModelInput {
2774                width: 960,
2775                height: 960,
2776                letterbox: "center".into()
2777            }),
2778            "Model-input pixels, 960 × 960, letterboxed"
2779        );
2780    }
2781}