1use std::collections::{BTreeMap, HashSet};
60
61use serde::{Deserialize, Serialize};
62use serde_json::Value;
63
64pub const VISION_TOOLS: [&str; 4] =
66 ["vision_detect", "vision_segment", "vision_read", "vision_describe"];
67
68pub type BoxPx = [f64; 4];
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct RleMask {
87 pub width: u32,
89 pub height: u32,
91 pub counts: Vec<u32>,
93}
94
95impl RleMask {
96 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 pub fn area(&self) -> u64 {
112 self.counts.iter().skip(1).step_by(2).map(|&c| u64::from(c)).sum()
113 }
114
115 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 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 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
144pub 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
176pub 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
193pub 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
206pub 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
231fn collapse_whitespace(text: &str) -> String {
233 text.split_whitespace().collect::<Vec<_>>().join(" ")
234}
235
236pub 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
253pub 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
277fn normalize_field(value: &str) -> String {
279 value.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
280}
281
282fn 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
295pub 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
316pub struct ExpectedRegion {
317 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub label: Option<String>,
320 #[serde(rename = "box", default, skip_serializing_if = "Option::is_none")]
322 pub bbox: Option<BoxPx>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub mask: Option<RleMask>,
326}
327
328impl ExpectedRegion {
329 pub fn boxed(label: impl Into<String>, bbox: BoxPx) -> Self {
331 Self { label: Some(label.into()), bbox: Some(bbox), mask: None }
332 }
333
334 pub fn bbox(&self) -> Option<BoxPx> {
336 self.bbox.or_else(|| self.mask.as_ref().and_then(RleMask::bbox))
337 }
338}
339
340#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
356pub struct VisionExpected {
357 #[serde(default, skip_serializing_if = "Vec::is_empty")]
359 pub regions: Vec<ExpectedRegion>,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
362 pub text: Option<String>,
363 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
365 pub fields: BTreeMap<String, String>,
366 #[serde(default, skip_serializing_if = "Vec::is_empty")]
368 pub targets: Vec<ExpectedRegion>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub count: Option<usize>,
372}
373
374#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub struct AnswerRegion {
377 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub label: Option<String>,
380 #[serde(rename = "box", default, skip_serializing_if = "Option::is_none")]
382 pub bbox: Option<BoxPx>,
383 #[serde(default, skip_serializing_if = "Option::is_none")]
385 pub mask: Option<RleMask>,
386 #[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 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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
467pub struct VisionAnswer {
468 #[serde(default, skip_serializing_if = "Vec::is_empty")]
470 pub regions: Vec<AnswerRegion>,
471 #[serde(default, skip_serializing_if = "Option::is_none")]
473 pub text: Option<String>,
474 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
476 pub fields: BTreeMap<String, String>,
477}
478
479impl VisionAnswer {
480 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
567pub struct VisionCriteria {
568 #[serde(default = "default_iou_threshold")]
570 pub iou_threshold: f64,
571 #[serde(default = "default_box_tolerance")]
573 pub box_tolerance_px: f64,
574 #[serde(default, skip_serializing_if = "Option::is_none")]
576 pub region_iou: Option<f64>,
577 #[serde(default, skip_serializing_if = "Option::is_none")]
579 pub box_hit_rate: Option<f64>,
580 #[serde(default, skip_serializing_if = "Option::is_none")]
582 pub mask_iou: Option<f64>,
583 #[serde(default, skip_serializing_if = "Option::is_none")]
585 pub ocr_char_accuracy: Option<f64>,
586 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub ocr_word_accuracy: Option<f64>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub field_exact_match: Option<f64>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
594 pub field_normalized_match: Option<f64>,
595 #[serde(default, skip_serializing_if = "Option::is_none")]
597 pub detection_precision: Option<f64>,
598 #[serde(default, skip_serializing_if = "Option::is_none")]
600 pub detection_recall: Option<f64>,
601 #[serde(default, skip_serializing_if = "Option::is_none")]
603 pub detection_ap: Option<f64>,
604 #[serde(default, skip_serializing_if = "Option::is_none")]
606 pub detection_map: Option<f64>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub grounding_hit_rate: Option<f64>,
610 #[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 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 pub fn has_thresholds(&self) -> bool {
667 self.thresholds().iter().any(|(_, threshold)| threshold.is_some())
668 }
669
670 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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
702pub struct VisionScores {
703 pub scores: BTreeMap<String, f64>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
707 pub max_box_error_px: Option<f64>,
708 #[serde(default, skip_serializing_if = "Vec::is_empty")]
710 pub notes: Vec<String>,
711}
712
713impl VisionScores {
714 pub fn get(&self, name: &str) -> Option<f64> {
716 self.scores.get(name).copied()
717 }
718}
719
720fn 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
733fn 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
766fn 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
775fn 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
795fn 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
813pub 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 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
889pub 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 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
1028pub(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 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 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 let mask = RleMask { width: 3, height: 2, counts: vec![2, 3, 1] };
1114 assert!(mask.is_valid());
1115 assert_eq!(mask.area(), 3);
1116 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 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 assert_eq!(character_error_rate("INVOICE 4721", "INV0ICE 4721"), 1.0 / 12.0);
1141 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 assert_eq!(character_error_rate("a", "abc"), 2.0);
1148 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 found("red rectangle", [80.0, 60.0, 320.0, 220.0], 0.9),
1178 found("blue circle", [553.0, 60.0, 733.0, 240.0], 0.8),
1180 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 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 assert_eq!(scores.get("detection_ap"), Some(2.0 / 3.0));
1194 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 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 assert_eq!(average_precision(&expected, &answer, 0.5), 1.0);
1213 assert_eq!(average_precision(&expected, &answer, 0.85), 0.5);
1215 }
1216
1217 #[test]
1218 fn average_precision_by_hand() {
1219 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 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 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 assert_eq!(scores.get("grounding_hit_rate"), Some(0.5));
1291 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 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}