use std::sync::Arc;
use adk_core::egress::ToolEgress;
use adk_core::{Evidence, GovernedCall, ImageEvidence, ToolEffect};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::cx::VisionCx;
use crate::digest::Digest;
use crate::error::Result;
use crate::geometry::{BBox, Region, RegionSet};
use crate::media::ImageRef;
pub const VERIFICATION_TOOL: &str = "vision_verification_failed";
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Observation {
pub regions: RegionSet,
pub frame: Option<ImageRef>,
}
impl Observation {
pub fn new(regions: RegionSet) -> Self {
Self { regions, frame: None }
}
#[must_use]
pub fn with_frame(mut self, frame: ImageRef) -> Self {
self.frame = Some(frame);
self
}
}
#[async_trait]
pub trait Observer: Send + Sync {
async fn observe(&self, cx: &VisionCx) -> Result<Observation>;
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RegionExpectation {
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub within: Option<BBox>,
}
impl RegionExpectation {
pub fn label(label: impl Into<String>) -> Self {
Self { label: label.into(), within: None }
}
#[must_use]
pub fn within(mut self, bbox: BBox) -> Self {
self.within = Some(bbox);
self
}
fn matches(&self, region: &Region) -> bool {
region.label.as_deref() == Some(self.label.as_str())
&& match (self.within, region.shape.bbox()) {
(None, _) => true,
(Some(area), Some(bbox)) => {
let [cx, cy] = bbox.center();
cx >= area.x0 && cx <= area.x1 && cy >= area.y0 && cy <= area.y1
}
(Some(_), None) => false,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ExpectedChange {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub appear: Vec<RegionExpectation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub disappear: Vec<RegionExpectation>,
#[serde(default = "default_iou")]
pub same_iou: f32,
}
fn default_iou() -> f32 {
0.5
}
impl ExpectedChange {
pub fn none() -> Self {
Self { same_iou: default_iou(), ..Self::default() }
}
#[must_use]
pub fn appears(mut self, expectation: RegionExpectation) -> Self {
self.appear.push(expectation);
self
}
#[must_use]
pub fn disappears(mut self, expectation: RegionExpectation) -> Self {
self.disappear.push(expectation);
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RegionDiff {
pub appeared: Vec<Region>,
pub disappeared: Vec<Region>,
}
pub fn diff_regions(before: &RegionSet, after: &RegionSet, same_iou: f32) -> RegionDiff {
let same = |a: &Region, b: &Region| {
a.label == b.label
&& match (a.shape.bbox(), b.shape.bbox()) {
(Some(x), Some(y)) => x.iou(&y) >= same_iou,
_ => false,
}
};
let mut matched = vec![false; after.regions.len()];
let mut disappeared = Vec::new();
for old in &before.regions {
match after.regions.iter().enumerate().position(|(i, new)| !matched[i] && same(old, new)) {
Some(index) => matched[index] = true,
None => disappeared.push(old.clone()),
}
}
let appeared = after
.regions
.iter()
.zip(matched)
.filter(|(_, matched)| !matched)
.map(|(region, _)| region.clone())
.collect();
RegionDiff { appeared, disappeared }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VerificationReport {
pub passed: bool,
pub missing: Vec<String>,
pub unexpected: Vec<Region>,
pub diff: RegionDiff,
pub before: Digest,
pub after: Digest,
}
pub fn check_change(
before: &RegionSet,
after: &RegionSet,
expected: &ExpectedChange,
) -> VerificationReport {
let diff = diff_regions(before, after, expected.same_iou);
let mut missing = Vec::new();
let mut appeared: Vec<Option<&Region>> = diff.appeared.iter().map(Some).collect();
let mut disappeared: Vec<Option<&Region>> = diff.disappeared.iter().map(Some).collect();
for (want, pool, verb) in [
(&expected.appear, &mut appeared, "appear"),
(&expected.disappear, &mut disappeared, "disappear"),
] {
for expectation in want {
match pool.iter_mut().find(|r| r.is_some_and(|r| expectation.matches(r))) {
Some(slot) => *slot = None,
None => missing.push(format!(
"`{}` did not {verb}{}",
expectation.label,
expectation
.within
.map(|b| format!(" in [{}, {}, {}, {}]", b.x0, b.y0, b.x1, b.y1))
.unwrap_or_default()
)),
}
}
}
let unexpected: Vec<Region> =
appeared.into_iter().chain(disappeared).flatten().cloned().collect();
VerificationReport {
passed: missing.is_empty() && unexpected.is_empty(),
missing,
unexpected,
diff,
before: before.image,
after: after.image,
}
}
#[async_trait]
pub trait VerifiedAction: Send + Sync {
async fn act(
&self,
cx: &VisionCx,
failed: Option<&VerificationReport>,
) -> Result<ExpectedChange>;
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LoopOutcome {
Verified {
attempts: u32,
report: VerificationReport,
},
Held(VerificationHold),
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct VerificationHold {
pub reports: Vec<VerificationReport>,
pub frames: Vec<ImageRef>,
}
impl VerificationHold {
pub fn governed_call(&self, function_call_id: &str) -> GovernedCall {
let evidence = self
.frames
.iter()
.enumerate()
.map(|(index, frame)| {
let mut image = ImageEvidence::new(
frame.digest.to_string(),
frame.artifact.clone(),
frame.mime_type.clone(),
frame.width,
frame.height,
)
.with_caption(if index == 0 {
"Before the action"
} else {
"After the action"
});
if index + 1 == self.frames.len()
&& let Some(report) = self.reports.last()
{
let regions = RegionSet::new(
frame.digest,
frame.width,
frame.height,
report.unexpected.clone(),
);
image = image.with_regions(serde_json::to_value(regions).unwrap_or_default());
}
Evidence::from(image)
})
.collect::<Vec<_>>();
let mut call = GovernedCall::new(
VERIFICATION_TOOL,
function_call_id,
json!({ "reports": self.reports }),
)
.with_effect(ToolEffect::Idempotent)
.with_egress(ToolEgress::None)
.with_evidence(evidence);
call.requires_confirmation = true;
call
}
}
pub struct VerifierLoop {
observer: Arc<dyn Observer>,
regrounds: u32,
}
impl VerifierLoop {
pub fn new(observer: Arc<dyn Observer>) -> Self {
Self { observer, regrounds: 1 }
}
pub async fn run(&self, cx: &VisionCx, action: &dyn VerifiedAction) -> Result<LoopOutcome> {
let mut before = self.observer.observe(cx).await?;
let mut reports: Vec<VerificationReport> = Vec::new();
let mut frames = Vec::new();
for attempt in 0..=self.regrounds {
let expected = action.act(cx, reports.last()).await?;
let after = self.observer.observe(cx).await?;
let report = check_change(&before.regions, &after.regions, &expected);
tracing::debug!(
vision.attempt = attempt + 1,
vision.passed = report.passed,
vision.unexpected = report.unexpected.len(),
"verification checked"
);
if report.passed {
return Ok(LoopOutcome::Verified { attempts: attempt + 1, report });
}
frames = before.frame.iter().chain(after.frame.iter()).cloned().collect();
reports.push(report);
before = after;
}
tracing::info!(vision.reports = reports.len(), "verification failed; held for a person");
Ok(LoopOutcome::Held(VerificationHold { reports, frames }))
}
}