Skip to main content

adk_eval/
vision.rs

1//! Vision scoring (spec 3.7 §7.16): regions, masks, OCR text, document fields, detections
2//! and click targets, compared in the source image's pixels.
3//!
4//! A turn states what it expects in [`Turn::expected_vision`](crate::Turn::expected_vision)
5//! ([`VisionExpected`]); the agent's perception answer ([`VisionAnswer`]) is read from the
6//! responses of the `adk-vision` tools it called — `vision_detect`, `vision_segment`,
7//! `vision_read` and `vision_describe` — in the wire form those tools return. The scorers
8//! depend on no vision crate: boxes are `[x0, y0, x1, y1]` in source pixels with `x1` and `y1`
9//! exclusive, and masks are COCO run-length encodings, as `adk-vision` publishes them.
10//!
11//! | Score | Range | Compares |
12//! |-------|-------|----------|
13//! | `region_iou` | 0–1 | mean box IoU of each expected region with its matched answer region |
14//! | `box_hit_rate` | 0–1 | share of expected regions whose matched box has every edge within `box_tolerance_px` |
15//! | `mask_iou` | 0–1 | mean mask IoU of each expected mask with its matched answer mask |
16//! | `ocr_char_accuracy` | 0–1 | `1 − CER`: character edit distance over the expected text's length |
17//! | `ocr_word_accuracy` | 0–1 | `1 − WER`: word edit distance over the expected word count |
18//! | `field_exact_match` | 0–1 | share of expected fields whose value is identical |
19//! | `field_normalized_match` | 0–1 | the same, ignoring case, spacing and punctuation, and numbers by value |
20//! | `detection_precision`, `detection_recall` | 0–1 | greedy matching by score at `iou_threshold`, labels compared |
21//! | `detection_ap` | 0–1 | COCO 101-point average precision at `iou_threshold`, averaged over labels |
22//! | `detection_map` | 0–1 | the same averaged over IoU thresholds 0.50, 0.55, …, 0.95 |
23//! | `grounding_hit_rate` | 0–1 | share of targets whose matched answer's centre falls inside the target |
24//! | `count_accuracy` | 0–1 | `1 − |found − expected| / expected` |
25//!
26//! Every score is higher-is-better, so [`BaselineStore`](crate::BaselineStore) gates it.
27//! Labels match when they are equal ignoring case and punctuation, or one contains the
28//! other; an expected region without a label matches any answer region.
29//!
30//! # Example
31//!
32//! ```
33//! use adk_eval::vision::{VisionAnswer, VisionCriteria, VisionExpected, score};
34//! use serde_json::json;
35//!
36//! let expected: VisionExpected = serde_json::from_value(json!({
37//!     "regions": [{"label": "seal", "box": [10, 10, 50, 30]}],
38//!     "text": "Seal torn"
39//! }))
40//! .unwrap();
41//! let detected = VisionAnswer::from_tool_response(
42//!     "vision_detect",
43//!     &json!({"regions": [{"box": [10, 10, 50, 34], "label": "seal", "score": 0.9}]}),
44//! )
45//! .unwrap();
46//! let read = VisionAnswer::from_tool_response(
47//!     "vision_read",
48//!     &json!({"blocks": [{"kind": "text", "text": "Seal torm", "box": [10, 40, 90, 50]}]}),
49//! )
50//! .unwrap();
51//! let answer = detected.merged(read);
52//!
53//! let scores = score(&expected, &answer, &VisionCriteria::default());
54//! assert_eq!(scores.get("region_iou"), Some(800.0 / 960.0));
55//! assert_eq!(scores.get("ocr_char_accuracy"), Some(1.0 - 1.0 / 9.0));
56//! assert_eq!(scores.get("ocr_word_accuracy"), Some(0.5));
57//! ```
58
59use std::collections::{BTreeMap, HashSet};
60
61use serde::{Deserialize, Serialize};
62use serde_json::Value;
63
64/// The `adk-vision` tools whose responses carry a perception answer.
65pub const VISION_TOOLS: [&str; 4] =
66    ["vision_detect", "vision_segment", "vision_read", "vision_describe"];
67
68/// A box as `[x0, y0, x1, y1]` in source pixels, `x1` and `y1` exclusive.
69pub type BoxPx = [f64; 4];
70
71/// A binary mask, run-length encoded in COCO's column-major order: `counts` alternates runs
72/// of unset and set pixels, starting with unset, scanning each column top to bottom. The
73/// wire form of `adk_vision::Mask`.
74///
75/// # Example
76///
77/// ```
78/// use adk_eval::vision::RleMask;
79///
80/// // A 4×3 raster with pixels (1, 1) and (2, 1) set.
81/// let mask = RleMask { width: 4, height: 3, counts: vec![4, 1, 2, 1, 4] };
82/// assert_eq!(mask.area(), 2);
83/// assert_eq!(mask.bbox(), Some([1.0, 1.0, 3.0, 2.0]));
84/// ```
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct RleMask {
87    /// Width of the raster.
88    pub width: u32,
89    /// Height of the raster.
90    pub height: u32,
91    /// Alternating run lengths, unset first.
92    pub counts: Vec<u32>,
93}
94
95impl RleMask {
96    /// The `[start, end)` linear (column-major) ranges of set pixels.
97    fn set_runs(&self) -> Vec<(u64, u64)> {
98        let mut runs = Vec::with_capacity(self.counts.len() / 2);
99        let mut at = 0u64;
100        for (index, &count) in self.counts.iter().enumerate() {
101            let next = at + u64::from(count);
102            if index % 2 == 1 && count > 0 {
103                runs.push((at, next));
104            }
105            at = next;
106        }
107        runs
108    }
109
110    /// The number of set pixels.
111    pub fn area(&self) -> u64 {
112        self.counts.iter().skip(1).step_by(2).map(|&c| u64::from(c)).sum()
113    }
114
115    /// `true` when the runs sum to `width × height`.
116    pub fn is_valid(&self) -> bool {
117        let total: u64 = self.counts.iter().map(|&c| u64::from(c)).sum();
118        total == u64::from(self.width) * u64::from(self.height)
119    }
120
121    /// The smallest box covering every set pixel, or `None` for an empty mask.
122    pub fn bbox(&self) -> Option<BoxPx> {
123        let height = u64::from(self.height.max(1));
124        let mut bounds: Option<(u64, u64, u64, u64)> = None;
125        for (start, end) in self.set_runs() {
126            // A run can wrap from the bottom of one column to the top of the next.
127            let (first_col, last_col) = (start / height, (end - 1) / height);
128            let (y_top, y_bottom) = if first_col == last_col {
129                (start % height, (end - 1) % height)
130            } else {
131                (0, height - 1)
132            };
133            bounds = Some(match bounds {
134                None => (first_col, y_top, last_col, y_bottom),
135                Some((x0, y0, x1, y1)) => {
136                    (x0.min(first_col), y0.min(y_top), x1.max(last_col), y1.max(y_bottom))
137                }
138            });
139        }
140        bounds.map(|(x0, y0, x1, y1)| [x0 as f64, y0 as f64, (x1 + 1) as f64, (y1 + 1) as f64])
141    }
142}
143
144/// Intersection over union of two masks, or `None` when their rasters differ in size.
145///
146/// # Example
147///
148/// ```
149/// use adk_eval::vision::{RleMask, mask_iou};
150///
151/// let a = RleMask { width: 2, height: 2, counts: vec![0, 2, 2] }; // left column
152/// let b = RleMask { width: 2, height: 2, counts: vec![1, 2, 1] }; // (0, 1) and (1, 0)
153/// assert_eq!(mask_iou(&a, &b), Some(1.0 / 3.0));
154/// ```
155pub fn mask_iou(a: &RleMask, b: &RleMask) -> Option<f64> {
156    if (a.width, a.height) != (b.width, b.height) {
157        return None;
158    }
159    let (runs_a, runs_b) = (a.set_runs(), b.set_runs());
160    let (mut i, mut j, mut inter) = (0, 0, 0u64);
161    while i < runs_a.len() && j < runs_b.len() {
162        let (start, end) = (runs_a[i].0.max(runs_b[j].0), runs_a[i].1.min(runs_b[j].1));
163        if start < end {
164            inter += end - start;
165        }
166        if runs_a[i].1 < runs_b[j].1 {
167            i += 1;
168        } else {
169            j += 1;
170        }
171    }
172    let union = a.area() + b.area() - inter;
173    Some(if union == 0 { 1.0 } else { inter as f64 / union as f64 })
174}
175
176/// Intersection over union of two boxes, `0.0` for disjoint or empty boxes.
177///
178/// # Example
179///
180/// ```
181/// use adk_eval::vision::box_iou;
182///
183/// assert_eq!(box_iou(&[0.0, 0.0, 10.0, 10.0], &[5.0, 0.0, 15.0, 10.0]), 50.0 / 150.0);
184/// ```
185pub fn box_iou(a: &BoxPx, b: &BoxPx) -> f64 {
186    let area = |b: &BoxPx| (b[2] - b[0]).max(0.0) * (b[3] - b[1]).max(0.0);
187    let inter =
188        (a[2].min(b[2]) - a[0].max(b[0])).max(0.0) * (a[3].min(b[3]) - a[1].max(b[1])).max(0.0);
189    let union = area(a) + area(b) - inter;
190    if union <= 0.0 { 0.0 } else { inter / union }
191}
192
193/// The largest difference between corresponding edges of two boxes, in pixels.
194///
195/// # Example
196///
197/// ```
198/// use adk_eval::vision::box_edge_error;
199///
200/// assert_eq!(box_edge_error(&[10.0, 10.0, 50.0, 30.0], &[11.0, 8.5, 50.0, 30.0]), 1.5);
201/// ```
202pub fn box_edge_error(a: &BoxPx, b: &BoxPx) -> f64 {
203    (0..4).map(|i| (a[i] - b[i]).abs()).fold(0.0, f64::max)
204}
205
206/// Edit distance between two sequences: insertions, deletions and substitutions, each 1.
207///
208/// # Example
209///
210/// ```
211/// use adk_eval::vision::edit_distance;
212///
213/// let a: Vec<char> = "kitten".chars().collect();
214/// let b: Vec<char> = "sitting".chars().collect();
215/// assert_eq!(edit_distance(&a, &b), 3);
216/// ```
217pub fn edit_distance<T: PartialEq>(a: &[T], b: &[T]) -> usize {
218    let mut previous: Vec<usize> = (0..=b.len()).collect();
219    let mut current = vec![0; b.len() + 1];
220    for (i, item) in a.iter().enumerate() {
221        current[0] = i + 1;
222        for (j, other) in b.iter().enumerate() {
223            let substitution = previous[j] + usize::from(item != other);
224            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
225        }
226        std::mem::swap(&mut previous, &mut current);
227    }
228    previous[b.len()]
229}
230
231/// Collapses every run of whitespace, line breaks included, to one space and trims.
232fn collapse_whitespace(text: &str) -> String {
233    text.split_whitespace().collect::<Vec<_>>().join(" ")
234}
235
236/// Character error rate: edit distance between the texts' characters over the expected
237/// text's length, after collapsing whitespace. `0.0` for two empty texts; `1.0` (or more)
238/// when nothing matches.
239///
240/// # Example
241///
242/// ```
243/// use adk_eval::vision::character_error_rate;
244///
245/// assert_eq!(character_error_rate("INVOICE 4721", "INV0ICE  4721"), 1.0 / 12.0);
246/// ```
247pub fn character_error_rate(expected: &str, actual: &str) -> f64 {
248    let expected: Vec<char> = collapse_whitespace(expected).chars().collect();
249    let actual: Vec<char> = collapse_whitespace(actual).chars().collect();
250    rate(edit_distance(&expected, &actual), expected.len(), actual.len())
251}
252
253/// Word error rate: edit distance between the texts' whitespace-separated words over the
254/// expected word count.
255///
256/// # Example
257///
258/// ```
259/// use adk_eval::vision::word_error_rate;
260///
261/// assert_eq!(word_error_rate("total due 58.20", "total due 58.2O"), 1.0 / 3.0);
262/// ```
263pub fn word_error_rate(expected: &str, actual: &str) -> f64 {
264    let expected: Vec<&str> = expected.split_whitespace().collect();
265    let actual: Vec<&str> = actual.split_whitespace().collect();
266    rate(edit_distance(&expected, &actual), expected.len(), actual.len())
267}
268
269fn rate(distance: usize, expected: usize, actual: usize) -> f64 {
270    match (expected, actual) {
271        (0, 0) => 0.0,
272        (0, _) => 1.0,
273        _ => distance as f64 / expected as f64,
274    }
275}
276
277/// A value reduced for the normalised comparison: lowercase letters and digits only.
278fn normalize_field(value: &str) -> String {
279    value.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
280}
281
282/// A field value read as a number, ignoring currency signs and thousands separators.
283fn field_number(value: &str) -> Option<f64> {
284    let kept: String =
285        value.chars().filter(|c| c.is_ascii_digit() || matches!(c, '.' | '-')).collect();
286    let has_digit = kept.chars().any(|c| c.is_ascii_digit());
287    let only_number_chars = value.chars().all(|c| {
288        c.is_ascii_digit()
289            || c.is_whitespace()
290            || matches!(c, '.' | ',' | '-' | '+' | '$' | '€' | '£')
291    });
292    (has_digit && only_number_chars).then(|| kept.parse().ok()).flatten()
293}
294
295/// Whether two field values match ignoring case, spacing and punctuation, or as numbers.
296///
297/// # Example
298///
299/// ```
300/// use adk_eval::vision::fields_match_normalized;
301///
302/// assert!(fields_match_normalized("+1 415 555 0142", "+14155550142"));
303/// assert!(fields_match_normalized("$1,234.50", "1234.5"));
304/// assert!(!fields_match_normalized("1234.5", "1234.6"));
305/// ```
306pub fn fields_match_normalized(expected: &str, actual: &str) -> bool {
307    if let (Some(a), Some(b)) = (field_number(expected), field_number(actual)) {
308        return (a - b).abs() < 1e-9;
309    }
310    let expected = normalize_field(expected);
311    !expected.is_empty() && expected == normalize_field(actual)
312}
313
314/// A labelled region an answer must find, in source pixels.
315#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
316pub struct ExpectedRegion {
317    /// The class, concept or target name; an unlabelled region matches any answer label.
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub label: Option<String>,
320    /// The box; derived from `mask` when absent.
321    #[serde(rename = "box", default, skip_serializing_if = "Option::is_none")]
322    pub bbox: Option<BoxPx>,
323    /// The exact mask, for mask IoU.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub mask: Option<RleMask>,
326}
327
328impl ExpectedRegion {
329    /// A labelled box.
330    pub fn boxed(label: impl Into<String>, bbox: BoxPx) -> Self {
331        Self { label: Some(label.into()), bbox: Some(bbox), mask: None }
332    }
333
334    /// The box, or the mask's covering box.
335    pub fn bbox(&self) -> Option<BoxPx> {
336        self.bbox.or_else(|| self.mask.as_ref().and_then(RleMask::bbox))
337    }
338}
339
340/// What a turn expects the agent to perceive. Each part present is scored by the
341/// [`VisionCriteria`] thresholds that apply to it; parts left out are not scored.
342///
343/// # Example
344///
345/// ```
346/// use adk_eval::vision::VisionExpected;
347///
348/// let expected: VisionExpected = serde_json::from_str(r#"{
349///     "regions": [{"label": "bear", "box": [1.4, 68.8, 586.0, 632.8]}],
350///     "fields": {"invoice_number": "INV-4721"},
351///     "count": 1
352/// }"#).unwrap();
353/// assert_eq!(expected.regions[0].bbox(), Some([1.4, 68.8, 586.0, 632.8]));
354/// ```
355#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
356pub struct VisionExpected {
357    /// Objects to find: region IoU, box error, mask IoU and detection scores.
358    #[serde(default, skip_serializing_if = "Vec::is_empty")]
359    pub regions: Vec<ExpectedRegion>,
360    /// The page's text in reading order: OCR character and word accuracy.
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub text: Option<String>,
363    /// Field values a document answer extracts: exact and normalised field match.
364    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
365    pub fields: BTreeMap<String, String>,
366    /// Click targets: each matched answer region's centre must fall inside its target.
367    #[serde(default, skip_serializing_if = "Vec::is_empty")]
368    pub targets: Vec<ExpectedRegion>,
369    /// How many regions the answer should hold.
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub count: Option<usize>,
372}
373
374/// One region of an answer.
375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub struct AnswerRegion {
377    /// The label the backend gave.
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub label: Option<String>,
380    /// The box in source pixels.
381    #[serde(rename = "box", default, skip_serializing_if = "Option::is_none")]
382    pub bbox: Option<BoxPx>,
383    /// The mask, for segmentation answers.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub mask: Option<RleMask>,
386    /// The backend's confidence.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub score: Option<f64>,
389}
390
391impl AnswerRegion {
392    fn bbox(&self) -> Option<BoxPx> {
393        self.bbox.or_else(|| self.mask.as_ref().and_then(RleMask::bbox))
394    }
395
396    /// Reads one region in the vision tools' compact form (`box` as an array, optional
397    /// `mask`) or the region-set form (`shape` with a `kind`).
398    fn from_json(value: &Value) -> Option<Self> {
399        let label = value.get("label").and_then(Value::as_str).map(str::to_string);
400        let score = value.get("score").and_then(Value::as_f64);
401        let mut bbox = value.get("box").and_then(box_from_json);
402        let mut mask: Option<RleMask> =
403            value.get("mask").and_then(|m| serde_json::from_value(m.clone()).ok());
404        if let Some(shape) = value.get("shape") {
405            match shape.get("kind").and_then(Value::as_str) {
406                Some("box") => {
407                    bbox = bbox.or_else(|| {
408                        let edge = |k: &str| shape.get(k).and_then(Value::as_f64);
409                        Some([edge("x0")?, edge("y0")?, edge("x1")?, edge("y1")?])
410                    });
411                }
412                Some("mask") => {
413                    mask = mask.or_else(|| serde_json::from_value(shape.clone()).ok());
414                }
415                Some("point") => {
416                    let (x, y) = (shape.get("x")?.as_f64()?, shape.get("y")?.as_f64()?);
417                    bbox = bbox.or(Some([x, y, x, y]));
418                }
419                Some("polygon") => {
420                    let points = shape.get("points")?.as_array()?;
421                    let xy: Vec<(f64, f64)> = points
422                        .iter()
423                        .filter_map(|p| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?)))
424                        .collect();
425                    bbox = bbox.or_else(|| covering(&xy));
426                }
427                _ => {}
428            }
429        }
430        let mask = mask.filter(RleMask::is_valid);
431        (bbox.is_some() || mask.is_some()).then_some(Self { label, bbox, mask, score })
432    }
433}
434
435fn box_from_json(value: &Value) -> Option<BoxPx> {
436    let edges = value.as_array()?;
437    if edges.len() != 4 {
438        return None;
439    }
440    Some([edges[0].as_f64()?, edges[1].as_f64()?, edges[2].as_f64()?, edges[3].as_f64()?])
441}
442
443fn covering(points: &[(f64, f64)]) -> Option<BoxPx> {
444    let first = points.first()?;
445    Some(points.iter().fold([first.0, first.1, first.0, first.1], |b, &(x, y)| {
446        [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]
447    }))
448}
449
450/// What an agent perceived in one turn, read from its vision tool responses.
451///
452/// # Example
453///
454/// ```
455/// use adk_eval::vision::VisionAnswer;
456/// use serde_json::json;
457///
458/// let answer = VisionAnswer::from_tool_response(
459///     "vision_describe",
460///     &json!({"text": "An invoice.", "value": {"total": 58.2, "currency": "USD"}}),
461/// )
462/// .unwrap();
463/// assert_eq!(answer.fields["total"], "58.2");
464/// assert_eq!(answer.text.as_deref(), Some("An invoice."));
465/// ```
466#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
467pub struct VisionAnswer {
468    /// Regions found, in source pixels.
469    #[serde(default, skip_serializing_if = "Vec::is_empty")]
470    pub regions: Vec<AnswerRegion>,
471    /// Text read or answered.
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub text: Option<String>,
474    /// Field values, from a describer's structured value or a reader's fields.
475    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
476    pub fields: BTreeMap<String, String>,
477}
478
479impl VisionAnswer {
480    /// Reads the response of one of the [`VISION_TOOLS`]; `None` for any other tool or a
481    /// response that holds no regions, text or fields.
482    ///
483    /// | Key | Becomes |
484    /// |-----|---------|
485    /// | `regions` | regions (`box` arrays, optional `mask`, or region-set `shape`s) |
486    /// | `blocks` | text: the blocks' text in the order given, one line each |
487    /// | `text` | text (preferred over `blocks`) |
488    /// | `value`, `fields` | fields: each top-level scalar, as a string |
489    pub fn from_tool_response(tool: &str, response: &Value) -> Option<Self> {
490        if !VISION_TOOLS.contains(&tool) {
491            return None;
492        }
493        Self::from_json(response)
494    }
495
496    /// Reads an answer from any JSON object with the keys
497    /// [`from_tool_response`](Self::from_tool_response) lists.
498    pub fn from_json(value: &Value) -> Option<Self> {
499        let object = value.as_object()?;
500        let regions: Vec<AnswerRegion> = object
501            .get("regions")
502            .and_then(Value::as_array)
503            .map(|list| list.iter().filter_map(AnswerRegion::from_json).collect())
504            .unwrap_or_default();
505        let blocks = object.get("blocks").and_then(Value::as_array).map(|blocks| {
506            blocks
507                .iter()
508                .filter_map(|b| b.get("text").and_then(Value::as_str))
509                .collect::<Vec<_>>()
510                .join("\n")
511        });
512        let text = object.get("text").and_then(Value::as_str).map(str::to_string).or(blocks);
513        let mut fields = BTreeMap::new();
514        for key in ["value", "fields"] {
515            if let Some(map) = object.get(key).and_then(Value::as_object) {
516                fields.extend(scalar_fields(map));
517            }
518        }
519        let answer = Self { regions, text, fields };
520        (answer != Self::default()).then_some(answer)
521    }
522
523    /// This answer with `later`'s parts in place of its own, part by part.
524    pub fn merged(mut self, later: Self) -> Self {
525        if !later.regions.is_empty() {
526            self.regions = later.regions;
527        }
528        if later.text.is_some() {
529            self.text = later.text;
530        }
531        if !later.fields.is_empty() {
532            self.fields = later.fields;
533        }
534        self
535    }
536}
537
538fn scalar_fields(map: &serde_json::Map<String, Value>) -> impl Iterator<Item = (String, String)> {
539    map.iter().filter_map(|(key, value)| {
540        let text = match value {
541            Value::String(s) => s.clone(),
542            Value::Number(n) => n.to_string(),
543            Value::Bool(b) => b.to_string(),
544            Value::Null | Value::Array(_) | Value::Object(_) => return None,
545        };
546        Some((key.clone(), text))
547    })
548}
549
550/// Thresholds for the vision scores, and the settings they are computed with. A score with
551/// no threshold is not computed; a threshold whose part the turn does not expect is not
552/// applied to that turn.
553///
554/// # Example
555///
556/// ```
557/// use adk_eval::vision::VisionCriteria;
558///
559/// let criteria: VisionCriteria = serde_json::from_str(
560///     r#"{"region_iou": 0.75, "ocr_char_accuracy": 0.98, "iou_threshold": 0.5}"#,
561/// )
562/// .unwrap();
563/// assert!(criteria.has_thresholds());
564/// assert_eq!(criteria.box_tolerance_px, 2.0);
565/// ```
566#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
567pub struct VisionCriteria {
568    /// IoU at which a detection matches an expected region (default 0.5).
569    #[serde(default = "default_iou_threshold")]
570    pub iou_threshold: f64,
571    /// Largest edge error, in source pixels, a box may have and count as a hit (default 2).
572    #[serde(default = "default_box_tolerance")]
573    pub box_tolerance_px: f64,
574    /// Minimum `region_iou`.
575    #[serde(default, skip_serializing_if = "Option::is_none")]
576    pub region_iou: Option<f64>,
577    /// Minimum `box_hit_rate`.
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    pub box_hit_rate: Option<f64>,
580    /// Minimum `mask_iou`.
581    #[serde(default, skip_serializing_if = "Option::is_none")]
582    pub mask_iou: Option<f64>,
583    /// Minimum `ocr_char_accuracy`.
584    #[serde(default, skip_serializing_if = "Option::is_none")]
585    pub ocr_char_accuracy: Option<f64>,
586    /// Minimum `ocr_word_accuracy`.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub ocr_word_accuracy: Option<f64>,
589    /// Minimum `field_exact_match`.
590    #[serde(default, skip_serializing_if = "Option::is_none")]
591    pub field_exact_match: Option<f64>,
592    /// Minimum `field_normalized_match`.
593    #[serde(default, skip_serializing_if = "Option::is_none")]
594    pub field_normalized_match: Option<f64>,
595    /// Minimum `detection_precision`.
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    pub detection_precision: Option<f64>,
598    /// Minimum `detection_recall`.
599    #[serde(default, skip_serializing_if = "Option::is_none")]
600    pub detection_recall: Option<f64>,
601    /// Minimum `detection_ap`.
602    #[serde(default, skip_serializing_if = "Option::is_none")]
603    pub detection_ap: Option<f64>,
604    /// Minimum `detection_map`.
605    #[serde(default, skip_serializing_if = "Option::is_none")]
606    pub detection_map: Option<f64>,
607    /// Minimum `grounding_hit_rate`.
608    #[serde(default, skip_serializing_if = "Option::is_none")]
609    pub grounding_hit_rate: Option<f64>,
610    /// Minimum `count_accuracy`.
611    #[serde(default, skip_serializing_if = "Option::is_none")]
612    pub count_accuracy: Option<f64>,
613}
614
615fn default_iou_threshold() -> f64 {
616    0.5
617}
618
619fn default_box_tolerance() -> f64 {
620    2.0
621}
622
623impl Default for VisionCriteria {
624    fn default() -> Self {
625        Self {
626            iou_threshold: default_iou_threshold(),
627            box_tolerance_px: default_box_tolerance(),
628            region_iou: None,
629            box_hit_rate: None,
630            mask_iou: None,
631            ocr_char_accuracy: None,
632            ocr_word_accuracy: None,
633            field_exact_match: None,
634            field_normalized_match: None,
635            detection_precision: None,
636            detection_recall: None,
637            detection_ap: None,
638            detection_map: None,
639            grounding_hit_rate: None,
640            count_accuracy: None,
641        }
642    }
643}
644
645impl VisionCriteria {
646    /// Every score name with its threshold, in a fixed order.
647    pub fn thresholds(&self) -> [(&'static str, Option<f64>); 13] {
648        [
649            ("region_iou", self.region_iou),
650            ("box_hit_rate", self.box_hit_rate),
651            ("mask_iou", self.mask_iou),
652            ("ocr_char_accuracy", self.ocr_char_accuracy),
653            ("ocr_word_accuracy", self.ocr_word_accuracy),
654            ("field_exact_match", self.field_exact_match),
655            ("field_normalized_match", self.field_normalized_match),
656            ("detection_precision", self.detection_precision),
657            ("detection_recall", self.detection_recall),
658            ("detection_ap", self.detection_ap),
659            ("detection_map", self.detection_map),
660            ("grounding_hit_rate", self.grounding_hit_rate),
661            ("count_accuracy", self.count_accuracy),
662        ]
663    }
664
665    /// Whether any score has a threshold.
666    pub fn has_thresholds(&self) -> bool {
667        self.thresholds().iter().any(|(_, threshold)| threshold.is_some())
668    }
669
670    /// Checks every threshold lies in `[0, 1]`, the IoU threshold in `(0, 1]` and the box
671    /// tolerance is a non-negative number of pixels.
672    ///
673    /// # Errors
674    ///
675    /// Returns a message naming the first value out of range.
676    pub fn validate(&self) -> Result<(), String> {
677        for (name, threshold) in self.thresholds() {
678            if let Some(t) = threshold
679                && !(0.0..=1.0).contains(&t)
680            {
681                return Err(format!("vision threshold {name} is {t}; use a value from 0.0 to 1.0"));
682            }
683        }
684        if !(self.iou_threshold > 0.0 && self.iou_threshold <= 1.0) {
685            return Err(format!(
686                "vision iou_threshold is {}; use a value above 0.0 and at most 1.0",
687                self.iou_threshold
688            ));
689        }
690        if !(self.box_tolerance_px.is_finite() && self.box_tolerance_px >= 0.0) {
691            return Err(format!(
692                "vision box_tolerance_px is {}; use a non-negative number of pixels",
693                self.box_tolerance_px
694            ));
695        }
696        Ok(())
697    }
698}
699
700/// Every vision score one turn produced, with notes on what missed.
701#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
702pub struct VisionScores {
703    /// Score name to value, for the parts the turn expects.
704    pub scores: BTreeMap<String, f64>,
705    /// Largest box edge error among matched regions, in source pixels.
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub max_box_error_px: Option<f64>,
708    /// What missed, one note per expected item.
709    #[serde(default, skip_serializing_if = "Vec::is_empty")]
710    pub notes: Vec<String>,
711}
712
713impl VisionScores {
714    /// One score by name.
715    pub fn get(&self, name: &str) -> Option<f64> {
716        self.scores.get(name).copied()
717    }
718}
719
720/// Whether an answer label names an expected label: equal ignoring case and punctuation,
721/// or one containing the other.
722fn labels_match(expected: Option<&str>, actual: Option<&str>) -> bool {
723    match (expected, actual) {
724        (None, _) => true,
725        (Some(_), None) => false,
726        (Some(e), Some(a)) => {
727            let (e, a) = (normalize_field(e), normalize_field(a));
728            !e.is_empty() && !a.is_empty() && (e == a || e.contains(&a) || a.contains(&e))
729        }
730    }
731}
732
733/// Pairs each expected region with one answer region of a matching label, best IoU first;
734/// returns `(expected index, answer index, IoU)` for every pair with a positive IoU.
735fn match_by_iou(
736    expected: &[ExpectedRegion],
737    answer: &[AnswerRegion],
738    iou: impl Fn(&ExpectedRegion, &AnswerRegion) -> Option<f64>,
739) -> Vec<(usize, usize, f64)> {
740    let mut candidates: Vec<(usize, usize, f64)> = Vec::new();
741    for (e, truth) in expected.iter().enumerate() {
742        for (a, found) in answer.iter().enumerate() {
743            if labels_match(truth.label.as_deref(), found.label.as_deref())
744                && let Some(value) = iou(truth, found)
745                && value > 0.0
746            {
747                candidates.push((e, a, value));
748            }
749        }
750    }
751    candidates.sort_by(|x, y| y.2.total_cmp(&x.2).then(x.0.cmp(&y.0)).then(x.1.cmp(&y.1)));
752    let (mut used_e, mut used_a) = (HashSet::new(), HashSet::new());
753    candidates
754        .into_iter()
755        .filter(|(e, a, _)| {
756            let free = !used_e.contains(e) && !used_a.contains(a);
757            if free {
758                used_e.insert(*e);
759                used_a.insert(*a);
760            }
761            free
762        })
763        .collect()
764}
765
766/// Answer indexes, highest score first; an answer without a score ranks as 1.0.
767fn by_score(answer: &[AnswerRegion]) -> Vec<usize> {
768    let mut order: Vec<usize> = (0..answer.len()).collect();
769    order.sort_by(|&x, &y| {
770        answer[y].score.unwrap_or(1.0).total_cmp(&answer[x].score.unwrap_or(1.0))
771    });
772    order
773}
774
775/// The best still-unmatched expected region for an answer box at `threshold`.
776fn best_match(
777    expected: &[ExpectedRegion],
778    matched: &[bool],
779    found: &AnswerRegion,
780    threshold: f64,
781) -> Option<usize> {
782    let bbox = found.bbox()?;
783    expected
784        .iter()
785        .enumerate()
786        .filter(|(e, truth)| {
787            !matched[*e] && labels_match(truth.label.as_deref(), found.label.as_deref())
788        })
789        .filter_map(|(e, truth)| truth.bbox().map(|b| (e, box_iou(&b, &bbox))))
790        .filter(|(_, iou)| *iou >= threshold)
791        .max_by(|x, y| x.1.total_cmp(&y.1))
792        .map(|(e, _)| e)
793}
794
795/// Detection matching at an IoU threshold, highest-scoring answers first (COCO's greedy
796/// rule): `(true positives, answers, expected)`.
797fn detection_counts(
798    expected: &[ExpectedRegion],
799    answer: &[AnswerRegion],
800    threshold: f64,
801) -> (usize, usize, usize) {
802    let mut matched = vec![false; expected.len()];
803    let mut hits = 0;
804    for a in by_score(answer) {
805        if let Some(e) = best_match(expected, &matched, &answer[a], threshold) {
806            matched[e] = true;
807            hits += 1;
808        }
809    }
810    (hits, answer.len(), expected.len())
811}
812
813/// COCO's 101-point interpolated average precision at one IoU threshold, averaged over the
814/// expected labels (unlabelled regions form one class matched by every answer).
815///
816/// # Example
817///
818/// ```
819/// use adk_eval::vision::{AnswerRegion, ExpectedRegion, average_precision};
820///
821/// let truth = vec![ExpectedRegion::boxed("cat", [0.0, 0.0, 10.0, 10.0])];
822/// let found = vec![AnswerRegion {
823///     label: Some("cat".into()),
824///     bbox: Some([0.0, 0.0, 10.0, 9.0]),
825///     mask: None,
826///     score: Some(0.9),
827/// }];
828/// assert_eq!(average_precision(&truth, &found, 0.5), 1.0);
829/// assert_eq!(average_precision(&truth, &found, 0.95), 0.0);
830/// ```
831pub fn average_precision(expected: &[ExpectedRegion], answer: &[AnswerRegion], iou: f64) -> f64 {
832    let mut labels: Vec<Option<String>> =
833        expected.iter().map(|r| r.label.as_deref().map(normalize_field)).collect();
834    labels.sort();
835    labels.dedup();
836    if labels.is_empty() {
837        return if answer.is_empty() { 1.0 } else { 0.0 };
838    }
839    let per_label: Vec<f64> = labels
840        .iter()
841        .map(|label| {
842            let truth: Vec<ExpectedRegion> = expected
843                .iter()
844                .filter(|r| r.label.as_deref().map(normalize_field) == *label)
845                .cloned()
846                .collect();
847            let found: Vec<AnswerRegion> = answer
848                .iter()
849                .filter(|r| labels_match(label.as_deref(), r.label.as_deref()))
850                .cloned()
851                .collect();
852            class_ap(&truth, &found, iou)
853        })
854        .collect();
855    per_label.iter().sum::<f64>() / per_label.len() as f64
856}
857
858fn class_ap(truth: &[ExpectedRegion], answer: &[AnswerRegion], threshold: f64) -> f64 {
859    let mut matched = vec![false; truth.len()];
860    let (mut tp, mut fp) = (0usize, 0usize);
861    let mut curve: Vec<(f64, f64)> = Vec::with_capacity(answer.len());
862    for a in by_score(answer) {
863        match best_match(truth, &matched, &answer[a], threshold) {
864            Some(e) => {
865                matched[e] = true;
866                tp += 1;
867            }
868            None => fp += 1,
869        }
870        curve.push((tp as f64 / truth.len().max(1) as f64, tp as f64 / (tp + fp) as f64));
871    }
872    // Precision envelope from the right, then sampled at recall 0, 0.01, …, 1.
873    for i in (0..curve.len().saturating_sub(1)).rev() {
874        curve[i].1 = curve[i].1.max(curve[i + 1].1);
875    }
876    let total: f64 = (0..=100)
877        .map(|step| {
878            let recall = f64::from(step) / 100.0;
879            curve.iter().find(|(r, _)| *r >= recall - 1e-12).map_or(0.0, |(_, p)| *p)
880        })
881        .sum();
882    total / 101.0
883}
884
885fn put(scores: &mut BTreeMap<String, f64>, name: &str, value: f64) {
886    scores.insert(name.to_string(), value.clamp(0.0, 1.0));
887}
888
889/// Scores an answer against what a turn expects, for every part the turn expects.
890///
891/// | Expected part | Scores |
892/// |---------------|--------|
893/// | `regions` | `region_iou`, `box_hit_rate`, `detection_precision`, `detection_recall`, `detection_ap`, `detection_map`, and `mask_iou` when a region has a mask |
894/// | `text` | `ocr_char_accuracy`, `ocr_word_accuracy` |
895/// | `fields` | `field_exact_match`, `field_normalized_match` |
896/// | `targets` | `grounding_hit_rate` |
897/// | `count` | `count_accuracy` |
898///
899/// A missing answer part scores 0; detection precision with no answer region is 1, and
900/// recall carries the miss. `criteria` supplies the IoU threshold and box tolerance; its
901/// score thresholds are not applied here.
902pub fn score(
903    expected: &VisionExpected,
904    answer: &VisionAnswer,
905    criteria: &VisionCriteria,
906) -> VisionScores {
907    let mut out = VisionScores::default();
908
909    if !expected.regions.is_empty() {
910        let pairs = match_by_iou(&expected.regions, &answer.regions, |t, a| {
911            Some(box_iou(&t.bbox()?, &a.bbox()?))
912        });
913        let n = expected.regions.len() as f64;
914        put(&mut out.scores, "region_iou", pairs.iter().map(|p| p.2).sum::<f64>() / n);
915        let mut hits = 0u32;
916        let mut worst: Option<f64> = None;
917        for (e, a, _) in &pairs {
918            if let (Some(t), Some(f)) = (expected.regions[*e].bbox(), answer.regions[*a].bbox()) {
919                let error = box_edge_error(&t, &f);
920                worst = Some(worst.map_or(error, |w| w.max(error)));
921                if error <= criteria.box_tolerance_px {
922                    hits += 1;
923                }
924            }
925        }
926        put(&mut out.scores, "box_hit_rate", f64::from(hits) / n);
927        let matched: HashSet<usize> = pairs.iter().map(|p| p.0).collect();
928        for (e, region) in expected.regions.iter().enumerate() {
929            if !matched.contains(&e) {
930                out.notes.push(format!(
931                    "no answer region matches {}",
932                    region.label.as_deref().unwrap_or("an unlabelled region")
933                ));
934            }
935        }
936        out.max_box_error_px = worst;
937
938        let (tp, found, truth) =
939            detection_counts(&expected.regions, &answer.regions, criteria.iou_threshold);
940        let precision = if found == 0 { 1.0 } else { tp as f64 / found as f64 };
941        put(&mut out.scores, "detection_precision", precision);
942        put(&mut out.scores, "detection_recall", tp as f64 / truth as f64);
943        let ap = average_precision(&expected.regions, &answer.regions, criteria.iou_threshold);
944        put(&mut out.scores, "detection_ap", ap);
945        let coco: f64 = (0..10)
946            .map(|step| {
947                let iou = 0.5 + 0.05 * f64::from(step);
948                average_precision(&expected.regions, &answer.regions, iou)
949            })
950            .sum();
951        put(&mut out.scores, "detection_map", coco / 10.0);
952
953        let masked: Vec<ExpectedRegion> =
954            expected.regions.iter().filter(|r| r.mask.is_some()).cloned().collect();
955        if !masked.is_empty() {
956            let pairs = match_by_iou(&masked, &answer.regions, |t, a| {
957                mask_iou(t.mask.as_ref()?, a.mask.as_ref()?)
958            });
959            let mean = pairs.iter().map(|p| p.2).sum::<f64>() / masked.len() as f64;
960            put(&mut out.scores, "mask_iou", mean);
961        }
962    }
963
964    if let Some(text) = &expected.text {
965        let actual = answer.text.as_deref().unwrap_or_default();
966        put(&mut out.scores, "ocr_char_accuracy", 1.0 - character_error_rate(text, actual));
967        put(&mut out.scores, "ocr_word_accuracy", 1.0 - word_error_rate(text, actual));
968    }
969
970    if !expected.fields.is_empty() {
971        // Field names compare like values, so `Invoice Number` finds `invoice_number`.
972        let actual: BTreeMap<String, &str> =
973            answer.fields.iter().map(|(k, v)| (normalize_field(k), v.as_str())).collect();
974        let (mut exact, mut normalized) = (0u32, 0u32);
975        for (key, want) in &expected.fields {
976            match actual.get(&normalize_field(key)) {
977                Some(got) => {
978                    if got.trim() == want.trim() {
979                        exact += 1;
980                    }
981                    if fields_match_normalized(want, got) {
982                        normalized += 1;
983                    } else {
984                        out.notes.push(format!("field {key}: expected {want:?}, got {got:?}"));
985                    }
986                }
987                None => out.notes.push(format!("field {key}: missing")),
988            }
989        }
990        let n = expected.fields.len() as f64;
991        put(&mut out.scores, "field_exact_match", f64::from(exact) / n);
992        put(&mut out.scores, "field_normalized_match", f64::from(normalized) / n);
993    }
994
995    if !expected.targets.is_empty() {
996        let mut hits = 0u32;
997        for target in &expected.targets {
998            let Some(area) = target.bbox() else { continue };
999            let name = target.label.as_deref().unwrap_or("?");
1000            let point = answer
1001                .regions
1002                .iter()
1003                .find(|r| labels_match(target.label.as_deref(), r.label.as_deref()))
1004                .and_then(AnswerRegion::bbox)
1005                .map(|b| ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0));
1006            match point {
1007                Some((x, y)) if x >= area[0] && x < area[2] && y >= area[1] && y < area[3] => {
1008                    hits += 1;
1009                }
1010                Some((x, y)) => out
1011                    .notes
1012                    .push(format!("target {name}: click at ({x:.1}, {y:.1}) falls outside")),
1013                None => out.notes.push(format!("target {name}: not found")),
1014            }
1015        }
1016        let rate = f64::from(hits) / expected.targets.len() as f64;
1017        put(&mut out.scores, "grounding_hit_rate", rate);
1018    }
1019
1020    if let Some(count) = expected.count {
1021        let found = answer.regions.len() as f64;
1022        let want = count as f64;
1023        put(&mut out.scores, "count_accuracy", 1.0 - (found - want).abs() / want.max(1.0));
1024    }
1025    out
1026}
1027
1028/// The perception answer in one turn's events: the [`VISION_TOOLS`] responses, later ones
1029/// replacing earlier parts, and, when no tool gave fields, a final response that is a JSON
1030/// object.
1031pub(crate) fn answer_from_events(
1032    events: &[adk_core::Event],
1033    final_text: Option<&str>,
1034) -> Option<VisionAnswer> {
1035    let mut answer: Option<VisionAnswer> = None;
1036    for event in events {
1037        let Some(content) = event.content() else { continue };
1038        for part in &content.parts {
1039            if let adk_core::Part::FunctionResponse { function_response, .. } = part
1040                && let Some(found) = VisionAnswer::from_tool_response(
1041                    &function_response.name,
1042                    &function_response.response,
1043                )
1044            {
1045                answer = Some(match answer {
1046                    Some(earlier) => earlier.merged(found),
1047                    None => found,
1048                });
1049            }
1050        }
1051    }
1052    let structured = final_text
1053        .and_then(|text| serde_json::from_str::<Value>(text.trim()).ok())
1054        .and_then(|value| {
1055            value.as_object().map(|map| scalar_fields(map).collect::<BTreeMap<_, _>>())
1056        })
1057        .filter(|fields| !fields.is_empty());
1058    match (answer, structured) {
1059        (Some(answer), Some(fields)) if answer.fields.is_empty() => {
1060            Some(VisionAnswer { fields, ..answer })
1061        }
1062        (None, Some(fields)) => Some(VisionAnswer { fields, ..VisionAnswer::default() }),
1063        (answer, _) => answer,
1064    }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use super::*;
1070    use serde_json::json;
1071
1072    fn found(label: &str, bbox: BoxPx, score: f64) -> AnswerRegion {
1073        AnswerRegion { label: Some(label.into()), bbox: Some(bbox), mask: None, score: Some(score) }
1074    }
1075
1076    fn mask_from_bits(width: u32, height: u32, set: impl Fn(u32, u32) -> bool) -> RleMask {
1077        let mut counts = Vec::new();
1078        let (mut current, mut run) = (false, 0u32);
1079        for x in 0..width {
1080            for y in 0..height {
1081                let bit = set(x, y);
1082                if bit != current {
1083                    counts.push(run);
1084                    current = bit;
1085                    run = 0;
1086                }
1087                run += 1;
1088            }
1089        }
1090        counts.push(run);
1091        RleMask { width, height, counts }
1092    }
1093
1094    #[test]
1095    fn box_iou_by_hand() {
1096        // Overlap 5×10 = 50; union 100 + 100 − 50 = 150.
1097        assert_eq!(box_iou(&[0.0, 0.0, 10.0, 10.0], &[5.0, 0.0, 15.0, 10.0]), 50.0 / 150.0);
1098        // Contained: 4×4 inside 8×8 → 16 / 64.
1099        assert_eq!(box_iou(&[0.0, 0.0, 8.0, 8.0], &[2.0, 2.0, 6.0, 6.0]), 0.25);
1100        assert_eq!(box_iou(&[0.0, 0.0, 1.0, 1.0], &[2.0, 2.0, 3.0, 3.0]), 0.0);
1101        assert_eq!(box_iou(&[0.0, 0.0, 0.0, 0.0], &[0.0, 0.0, 0.0, 0.0]), 0.0);
1102    }
1103
1104    #[test]
1105    fn box_edge_error_is_the_worst_edge() {
1106        assert_eq!(box_edge_error(&[80.0, 60.0, 320.0, 220.0], &[81.0, 57.5, 320.0, 222.0]), 2.5);
1107    }
1108
1109    #[test]
1110    fn mask_runs_decode_by_hand() {
1111        // 3×2 raster, column-major: (0,0),(0,1),(1,0),(1,1),(2,0),(2,1).
1112        // Set (1,0), (1,1), (2,0): runs unset 2, set 3, unset 1.
1113        let mask = RleMask { width: 3, height: 2, counts: vec![2, 3, 1] };
1114        assert!(mask.is_valid());
1115        assert_eq!(mask.area(), 3);
1116        // The set run wraps from column 1 into column 2.
1117        assert_eq!(mask.bbox(), Some([1.0, 0.0, 3.0, 2.0]));
1118        assert_eq!(mask_from_bits(3, 2, |x, y| x == 1 || (x == 2 && y == 0)), mask);
1119        assert!(!RleMask { width: 3, height: 2, counts: vec![2, 3] }.is_valid());
1120        assert_eq!(RleMask { width: 3, height: 2, counts: vec![6] }.bbox(), None);
1121    }
1122
1123    #[test]
1124    fn mask_iou_by_hand() {
1125        // A: columns 0–1 of a 4×4 raster (8 px). B: rows 0–1 (8 px). Overlap 2×2 = 4.
1126        let a = mask_from_bits(4, 4, |x, _| x < 2);
1127        let b = mask_from_bits(4, 4, |_, y| y < 2);
1128        assert_eq!(mask_iou(&a, &b), Some(4.0 / 12.0));
1129        assert_eq!(mask_iou(&a, &a), Some(1.0));
1130        let empty = RleMask { width: 4, height: 4, counts: vec![16] };
1131        assert_eq!(mask_iou(&empty, &empty), Some(1.0));
1132        assert_eq!(mask_iou(&a, &empty), Some(0.0));
1133        assert_eq!(mask_iou(&a, &RleMask { width: 2, height: 8, counts: vec![16] }), None);
1134    }
1135
1136    #[test]
1137    fn error_rates_by_hand() {
1138        assert_eq!(character_error_rate("abc", "abc"), 0.0);
1139        // One substitution in 12 characters, the doubled space collapsed.
1140        assert_eq!(character_error_rate("INVOICE 4721", "INV0ICE  4721"), 1.0 / 12.0);
1141        // "Seal torn" (9 characters) against "Seal torm": one substitution.
1142        assert_eq!(character_error_rate("Seal torn", "Seal\ntorm"), 1.0 / 9.0);
1143        assert_eq!(character_error_rate("ab", ""), 1.0);
1144        assert_eq!(character_error_rate("", ""), 0.0);
1145        assert_eq!(character_error_rate("", "x"), 1.0);
1146        // Two insertions over a 1-character reference: CER 2, so accuracy clamps at 0.
1147        assert_eq!(character_error_rate("a", "abc"), 2.0);
1148        // Words: one of three substituted; then one deleted and one inserted of four.
1149        assert_eq!(word_error_rate("total due 58.20", "total due 58.2O"), 1.0 / 3.0);
1150        assert_eq!(word_error_rate("a b c d", "a c d e"), 2.0 / 4.0);
1151    }
1152
1153    #[test]
1154    fn fields_match_by_hand() {
1155        assert!(fields_match_normalized("Amara Okafor", "amara  okafor"));
1156        assert!(fields_match_normalized("amara.okafor@example.com", "Amara.Okafor@Example.com"));
1157        assert!(fields_match_normalized("2026-11-19", "2026/11/19"));
1158        assert!(fields_match_normalized("58.20", "$58.2"));
1159        assert!(!fields_match_normalized("58.20", "58.21"));
1160        assert!(!fields_match_normalized("", ""));
1161        assert!(!fields_match_normalized("INV-4721", "INV-4712"));
1162    }
1163
1164    #[test]
1165    fn region_scores_by_hand() {
1166        let expected: VisionExpected = serde_json::from_value(json!({
1167            "regions": [
1168                {"label": "red rectangle", "box": [80, 60, 320, 220]},
1169                {"label": "blue circle", "box": [550, 60, 730, 240]},
1170                {"label": "green triangle", "box": [140, 330, 301, 481]}
1171            ]
1172        }))
1173        .unwrap();
1174        let answer = VisionAnswer {
1175            regions: vec![
1176                // Exact.
1177                found("red rectangle", [80.0, 60.0, 320.0, 220.0], 0.9),
1178                // 3 px right: overlap 177×180 over union 183×180 → 177/183.
1179                found("blue circle", [553.0, 60.0, 733.0, 240.0], 0.8),
1180                // A wrong label is never matched.
1181                found("yellow star", [140.0, 330.0, 301.0, 481.0], 0.7),
1182            ],
1183            ..VisionAnswer::default()
1184        };
1185        let scores = score(&expected, &answer, &VisionCriteria::default());
1186        assert_eq!(scores.get("region_iou"), Some((1.0 + 177.0 / 183.0) / 3.0));
1187        // Only the exact rectangle is within 2 px; the circle is 3 px off.
1188        assert_eq!(scores.get("box_hit_rate"), Some(1.0 / 3.0));
1189        assert_eq!(scores.max_box_error_px, Some(3.0));
1190        assert_eq!(scores.get("detection_precision"), Some(2.0 / 3.0));
1191        assert_eq!(scores.get("detection_recall"), Some(2.0 / 3.0));
1192        // Per label AP at 0.5: rectangle 1, circle 1, triangle 0 → 2/3.
1193        assert_eq!(scores.get("detection_ap"), Some(2.0 / 3.0));
1194        // The circle's IoU 0.967 clears every threshold to 0.95, so each of the ten APs is
1195        // again (1 + 1 + 0) / 3.
1196        let map = scores.get("detection_map").unwrap();
1197        assert!((map - 2.0 / 3.0).abs() < 1e-12, "{map}");
1198        assert_eq!(scores.notes, vec!["no answer region matches green triangle".to_string()]);
1199        assert!(scores.get("mask_iou").is_none());
1200    }
1201
1202    #[test]
1203    fn detection_counts_take_the_highest_score_first() {
1204        let expected = vec![ExpectedRegion::boxed("sheep", [0.0, 0.0, 10.0, 10.0])];
1205        let answer = vec![
1206            found("sheep", [0.0, 0.0, 10.0, 10.0], 0.4),
1207            // The higher score claims the only sheep, at IoU 0.81 ≥ 0.5.
1208            found("sheep", [0.0, 0.0, 9.0, 9.0], 0.9),
1209        ];
1210        assert_eq!(detection_counts(&expected, &answer, 0.5), (1, 2, 1));
1211        // AP at 0.5: the first answer is a hit at recall 1, precision 1 → 1.
1212        assert_eq!(average_precision(&expected, &answer, 0.5), 1.0);
1213        // At 0.85 the first answer (IoU 0.81) misses, then the second hits at precision 0.5.
1214        assert_eq!(average_precision(&expected, &answer, 0.85), 0.5);
1215    }
1216
1217    #[test]
1218    fn average_precision_by_hand() {
1219        // Two cats; answers by score: hit, miss, hit. Curve (r, p): (0.5, 1), (0.5, 0.5),
1220        // (1, 2/3). Envelope: 1 for r ≤ 0.5 (51 points), 2/3 above (50 points).
1221        let expected = vec![
1222            ExpectedRegion::boxed("cat", [0.0, 0.0, 10.0, 10.0]),
1223            ExpectedRegion::boxed("cat", [20.0, 0.0, 30.0, 10.0]),
1224        ];
1225        let answer = vec![
1226            found("cat", [0.0, 0.0, 10.0, 10.0], 0.9),
1227            found("cat", [50.0, 50.0, 60.0, 60.0], 0.8),
1228            found("cat", [20.0, 0.0, 30.0, 10.0], 0.7),
1229        ];
1230        let ap = average_precision(&expected, &answer, 0.5);
1231        assert!((ap - (51.0 + 50.0 * 2.0 / 3.0) / 101.0).abs() < 1e-12, "{ap}");
1232        assert_eq!(average_precision(&[], &[], 0.5), 1.0);
1233        assert_eq!(average_precision(&[], &answer, 0.5), 0.0);
1234    }
1235
1236    #[test]
1237    fn mask_scores_by_hand() {
1238        let truth = mask_from_bits(4, 4, |x, _| x < 2);
1239        let half = mask_from_bits(4, 4, |x, y| x < 2 && y < 2);
1240        let expected = VisionExpected {
1241            regions: vec![ExpectedRegion {
1242                label: Some("seal".into()),
1243                bbox: None,
1244                mask: Some(truth),
1245            }],
1246            ..VisionExpected::default()
1247        };
1248        let answer = VisionAnswer::from_tool_response(
1249            "vision_segment",
1250            &json!({"regions": [{"label": "seal", "mask": half}]}),
1251        )
1252        .unwrap();
1253        let scores = score(&expected, &answer, &VisionCriteria::default());
1254        assert_eq!(scores.get("mask_iou"), Some(0.5));
1255        // Boxes from the masks: [0, 0, 2, 4] and [0, 0, 2, 2] → IoU 4/8.
1256        assert_eq!(scores.get("region_iou"), Some(0.5));
1257    }
1258
1259    #[test]
1260    fn text_fields_targets_and_counts_by_hand() {
1261        let expected: VisionExpected = serde_json::from_value(json!({
1262            "text": "INVOICE INV-4721\nTotal 58.20",
1263            "fields": {"invoice_number": "INV-4721", "total": "58.20", "phone": "+1 415 555 0142"},
1264            "targets": [
1265                {"label": "save", "box": [1920, 1180, 2100, 1260]},
1266                {"label": "cancel", "box": [1660, 1180, 1880, 1260]}
1267            ],
1268            "count": 4
1269        }))
1270        .unwrap();
1271        let answer = VisionAnswer {
1272            regions: vec![
1273                found("Save button", [1930.0, 1190.0, 2090.0, 1250.0], 1.0),
1274                found("cancel", [1500.0, 1180.0, 1600.0, 1260.0], 1.0),
1275            ],
1276            text: Some("INVOICE INV-4721 Total 58.2O".into()),
1277            fields: BTreeMap::from([
1278                ("Invoice Number".to_string(), "INV-4721".to_string()),
1279                ("total".to_string(), "$58.2".to_string()),
1280            ]),
1281        };
1282        let scores = score(&expected, &answer, &VisionCriteria::default());
1283        // 28 characters after collapsing; one substitution.
1284        assert_eq!(scores.get("ocr_char_accuracy"), Some(1.0 - 1.0 / 28.0));
1285        assert_eq!(scores.get("ocr_word_accuracy"), Some(1.0 - 1.0 / 4.0));
1286        assert_eq!(scores.get("field_exact_match"), Some(1.0 / 3.0));
1287        assert_eq!(scores.get("field_normalized_match"), Some(2.0 / 3.0));
1288        // "Save button" contains "save" and its centre (2010, 1220) is inside; cancel's
1289        // centre (1550, 1220) is left of its target.
1290        assert_eq!(scores.get("grounding_hit_rate"), Some(0.5));
1291        // Two regions of an expected four.
1292        assert_eq!(scores.get("count_accuracy"), Some(0.5));
1293        assert!(scores.notes.contains(&"field phone: missing".to_string()));
1294    }
1295
1296    #[test]
1297    fn missing_answer_parts_score_zero() {
1298        let expected: VisionExpected = serde_json::from_value(json!({
1299            "regions": [{"label": "bear", "box": [0, 0, 10, 10]}],
1300            "text": "hello",
1301            "fields": {"a": "1"}
1302        }))
1303        .unwrap();
1304        let scores = score(&expected, &VisionAnswer::default(), &VisionCriteria::default());
1305        for name in [
1306            "region_iou",
1307            "box_hit_rate",
1308            "detection_recall",
1309            "detection_ap",
1310            "ocr_char_accuracy",
1311            "ocr_word_accuracy",
1312            "field_exact_match",
1313        ] {
1314            assert_eq!(scores.get(name), Some(0.0), "{name}");
1315        }
1316        // Nothing found is vacuously precise; recall carries the miss.
1317        assert_eq!(scores.get("detection_precision"), Some(1.0));
1318    }
1319
1320    #[test]
1321    fn tool_responses_parse_in_every_form() {
1322        let detect = json!({
1323            "image": "sha256:00",
1324            "regions": [
1325                {"box": [1.0, 2.0, 3.0, 4.0], "label": "a", "score": 0.5},
1326                {"shape": {"kind": "box", "x0": 5, "y0": 6, "x1": 7, "y1": 8}, "label": "b"},
1327                {"shape": {"kind": "polygon", "points": [[1, 1], [4, 2], [2, 5]]}},
1328                {"shape": {"kind": "point", "x": 9, "y": 9}},
1329                {"label": "no geometry"}
1330            ],
1331            "calls": []
1332        });
1333        let answer = VisionAnswer::from_tool_response("vision_detect", &detect).unwrap();
1334        let boxes: Vec<Option<BoxPx>> = answer.regions.iter().map(|r| r.bbox).collect();
1335        assert_eq!(
1336            boxes,
1337            vec![
1338                Some([1.0, 2.0, 3.0, 4.0]),
1339                Some([5.0, 6.0, 7.0, 8.0]),
1340                Some([1.0, 1.0, 4.0, 5.0]),
1341                Some([9.0, 9.0, 9.0, 9.0]),
1342            ]
1343        );
1344        let read = json!({"blocks": [{"text": "Title"}, {"text": "Body line"}], "markdown": null});
1345        assert_eq!(
1346            VisionAnswer::from_tool_response("vision_read", &read).unwrap().text.as_deref(),
1347            Some("Title\nBody line")
1348        );
1349        assert!(VisionAnswer::from_tool_response("get_weather", &read).is_none());
1350        assert!(VisionAnswer::from_tool_response("vision_detect", &json!({"calls": []})).is_none());
1351        let bad_mask = json!({"regions": [{"mask": {"width": 2, "height": 2, "counts": [1]}}]});
1352        assert!(VisionAnswer::from_tool_response("vision_segment", &bad_mask).is_none());
1353    }
1354
1355    #[test]
1356    fn later_answers_replace_earlier_parts() {
1357        let first = VisionAnswer {
1358            regions: vec![found("a", [0.0, 0.0, 1.0, 1.0], 1.0)],
1359            text: Some("first".into()),
1360            fields: BTreeMap::new(),
1361        };
1362        let second = VisionAnswer { text: Some("second".into()), ..VisionAnswer::default() };
1363        let merged = first.clone().merged(second);
1364        assert_eq!(merged, VisionAnswer { text: Some("second".into()), ..first });
1365    }
1366
1367    #[test]
1368    fn answers_come_from_vision_tool_responses_and_json_final_text() {
1369        use adk_core::{Content, Event, FunctionResponseData, Part};
1370
1371        let mut event = Event::new("inv");
1372        event.llm_response.content = Some(Content {
1373            role: "function".into(),
1374            parts: vec![
1375                Part::FunctionResponse {
1376                    function_response: FunctionResponseData::new(
1377                        "vision_detect",
1378                        json!({"regions": [{"box": [0, 0, 2, 2], "label": "x"}]}),
1379                    ),
1380                    id: None,
1381                    annotations: None,
1382                },
1383                Part::FunctionResponse {
1384                    function_response: FunctionResponseData::new(
1385                        "lookup",
1386                        json!({"regions": [{"box": [5, 5, 6, 6]}]}),
1387                    ),
1388                    id: None,
1389                    annotations: None,
1390                },
1391            ],
1392        });
1393        let answer = answer_from_events(&[event], Some(r#"{"total": "58.20"}"#)).unwrap();
1394        assert_eq!(answer.regions.len(), 1);
1395        assert_eq!(answer.fields["total"], "58.20");
1396        assert!(answer_from_events(&[], Some("plain text")).is_none());
1397    }
1398
1399    #[test]
1400    fn criteria_validate_their_ranges() {
1401        assert!(VisionCriteria::default().validate().is_ok());
1402        assert!(!VisionCriteria::default().has_thresholds());
1403        let bad = VisionCriteria { mask_iou: Some(1.5), ..VisionCriteria::default() };
1404        assert!(bad.validate().unwrap_err().contains("mask_iou"));
1405        let bad = VisionCriteria { iou_threshold: 0.0, ..VisionCriteria::default() };
1406        assert!(bad.validate().unwrap_err().contains("iou_threshold"));
1407    }
1408}