use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::fit::ScreenshotScale;
use crate::digest::Digest;
use crate::edit::{EditOp, Overlay, Rgba, apply_edit};
use crate::error::{Result, VisionError};
use crate::geometry::{BBox, ScreenSpace, Shape, TransformChain};
use crate::media::DecodedImage;
use crate::traits::Word;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum CandidateSource {
BrowserElement {
selector: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
role: Option<String>,
},
OcrWord {
#[serde(default, skip_serializing_if = "Option::is_none")]
confidence: Option<f32>,
},
ModelPoint {
backend: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
pub mark: u32,
pub region: BBox,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
pub source: CandidateSource,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserElement {
pub selector: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub role: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub rect: CssRect,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CssRect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserElements {
pub device_pixel_ratio: f32,
pub elements: Vec<BrowserElement>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarkSet {
pub screenshot: Digest,
pub size: [u32; 2],
pub screen: ScreenSpace,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<String>,
pub candidates: Vec<Candidate>,
}
pub(crate) fn same_label(a: Option<&str>, b: Option<&str>) -> bool {
match (a, b) {
(Some(a), Some(b)) => a.trim().eq_ignore_ascii_case(b.trim()),
(None, None) => true,
_ => false,
}
}
impl MarkSet {
pub fn new(screenshot: Digest, size: (u32, u32), screen: ScreenSpace) -> Self {
Self { screenshot, size: [size.0, size.1], screen, window: None, candidates: Vec::new() }
}
#[must_use]
pub fn with_window(mut self, window: impl Into<String>) -> Self {
self.window = Some(window.into());
self
}
pub fn push(
&mut self,
region: BBox,
label: Option<String>,
source: CandidateSource,
) -> Option<u32> {
let region = region.clamped(self.size[0], self.size[1]);
if region.is_empty() {
return None;
}
let mark = u32::try_from(self.candidates.len() + 1).unwrap_or(u32::MAX);
self.candidates.push(Candidate { mark, region, label, source });
Some(mark)
}
pub fn add_browser_elements(&mut self, page: &BrowserElements) -> Vec<u32> {
let ratio = if page.device_pixel_ratio > 0.0 { page.device_pixel_ratio } else { 1.0 };
page.elements
.iter()
.filter_map(|element| {
let r = element.rect;
let region =
BBox::from_xywh(r.x * ratio, r.y * ratio, r.width * ratio, r.height * ratio);
self.push(
region,
element.name.clone(),
CandidateSource::BrowserElement {
selector: element.selector.clone(),
role: element.role.clone(),
},
)
})
.collect()
}
pub fn add_words(&mut self, words: &[Word]) -> Vec<u32> {
let screenshot = self.screenshot;
words
.iter()
.filter(|word| word.region.image == screenshot)
.filter_map(|word| {
let region = word.region.shape.bbox()?;
self.push(
region,
Some(word.text.clone()),
CandidateSource::OcrWord { confidence: word.confidence },
)
})
.collect()
}
pub fn add_model_point(
&mut self,
point: [f32; 2],
scale: &ScreenshotScale,
backend: &str,
) -> Option<u32> {
let at = scale.to_source(point);
let containing = self
.candidates
.iter()
.filter(|c| c.region.contains(at))
.min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
.map(|c| (c.region, c.label.clone()));
let (region, label) = containing.unwrap_or_else(|| {
let half = 4.0 * self.ratio();
(BBox::new(at[0] - half, at[1] - half, at[0] + half, at[1] + half), None)
});
self.push(region, label, CandidateSource::ModelPoint { backend: backend.to_string() })
}
fn ratio(&self) -> f32 {
if self.screen.device_pixel_ratio > 0.0 { self.screen.device_pixel_ratio } else { 1.0 }
}
pub fn candidate(&self, mark: u32) -> Option<&Candidate> {
self.candidates.iter().find(|c| c.mark == mark)
}
pub fn by_label(&self, label: &str) -> Vec<&Candidate> {
self.candidates.iter().filter(|c| same_label(c.label.as_deref(), Some(label))).collect()
}
pub fn overlays(&self) -> Vec<Overlay> {
let ratio = self.ratio();
let thickness = (2.0 * ratio).round().max(1.0) as u32;
self.candidates
.iter()
.flat_map(|c| {
[
Overlay::Box { bbox: c.region, color: Rgba::RED, thickness },
Overlay::Mark {
at: [c.region.x0, c.region.y0],
number: c.mark,
color: Rgba::RED,
scale: ratio,
},
]
})
.collect()
}
pub fn annotate_args(&self) -> Value {
let boxes: Vec<Value> = self
.candidates
.iter()
.map(|c| {
json!({
"box": [c.region.x0, c.region.y0, c.region.x1, c.region.y1],
"label": c.label,
"mark": c.mark,
})
})
.collect();
json!({ "image": self.screenshot, "boxes": boxes, "devicePixelRatio": self.ratio() })
}
pub fn annotate(&self, pixels: &DecodedImage) -> Result<DecodedImage> {
if pixels.size() != (self.size[0], self.size[1]) {
return Err(VisionError::InvalidInput(format!(
"the marks are for a {}x{} screenshot, not {}x{}",
self.size[0],
self.size[1],
pixels.width(),
pixels.height()
)));
}
let chain = TransformChain::new(self.size[0], self.size[1]);
apply_edit(pixels, &chain, &EditOp::Annotate { overlays: self.overlays() })
}
pub fn ground(&self, mark: u32) -> Result<GroundedTarget> {
let candidate = self.candidate(mark).ok_or_else(|| {
VisionError::InvalidInput(format!(
"mark {mark} is not on this screenshot; its marks are 1 to {}",
self.candidates.len()
))
})?;
Ok(self.target_of(candidate))
}
pub(crate) fn target_of(&self, candidate: &Candidate) -> GroundedTarget {
let points = self.screen.bbox_to_points(&candidate.region);
GroundedTarget {
mark: candidate.mark,
screenshot: self.screenshot,
screenshot_size: self.size,
screen: self.screen.clone(),
window: self.window.clone(),
pixels: candidate.region,
points,
click: self.screen.to_points(candidate.region.center()),
label: candidate.label.clone(),
source: candidate.source.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroundedTarget {
pub mark: u32,
pub screenshot: Digest,
pub screenshot_size: [u32; 2],
pub screen: ScreenSpace,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<String>,
pub pixels: BBox,
pub points: BBox,
pub click: [f32; 2],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
pub source: CandidateSource,
}
impl GroundedTarget {
pub fn click_pixel(&self) -> [f32; 2] {
self.screen.to_pixels(self.click)
}
pub fn browser_click_args(&self) -> Option<Value> {
match &self.source {
CandidateSource::BrowserElement { selector, .. } => {
Some(json!({ "selector": selector }))
}
CandidateSource::OcrWord { .. } | CandidateSource::ModelPoint { .. } => None,
}
}
pub fn toolset_coordinate(&self, scale: &ScreenshotScale) -> [i64; 2] {
let sent = scale.to_sent(self.click_pixel());
let clamp = |v: f32, max: u32| (v.floor() as i64).clamp(0, i64::from(max) - 1);
[clamp(sent[0], scale.sent[0]), clamp(sent[1], scale.sent[1])]
}
pub fn shape(&self) -> Shape {
Shape::Box(self.pixels)
}
#[cfg(feature = "computer-use")]
pub fn target_evidence(
&self,
platform: &str,
app_id: &str,
observation_id: &str,
captured_at: &str,
) -> adk_computer_use::TargetEvidence {
let ratio = f64::from(self.screen.device_pixel_ratio);
let p = &self.points;
adk_computer_use::TargetEvidence {
platform: platform.to_string(),
app_id: app_id.to_string(),
pid: None,
window_id: self.window.clone().map(Value::String),
window_title_digest: None,
display_id: Some(self.screen.display.clone()),
role: match &self.source {
CandidateSource::BrowserElement { role, .. } => role.clone(),
CandidateSource::OcrWord { .. } | CandidateSource::ModelPoint { .. } => None,
},
label_digest: self
.label
.as_deref()
.map(|label| Digest::of(label.as_bytes()).to_string()),
bounds: Some(adk_computer_use::Bounds::points(
f64::from(p.x0),
f64::from(p.y0),
f64::from(p.width()),
f64::from(p.height()),
ratio,
)),
observation_id: observation_id.to_string(),
screenshot_hash: Some(self.screenshot.to_string()),
device_pixel_ratio: Some(ratio),
ui_tree_revision: None,
confidence: match &self.source {
CandidateSource::OcrWord { confidence: Some(c) } => f64::from(*c),
CandidateSource::BrowserElement { .. }
| CandidateSource::OcrWord { confidence: None }
| CandidateSource::ModelPoint { .. } => 1.0,
},
captured_at: captured_at.to_string(),
}
}
}