Skip to main content

adk_vision/cloud/
gemini.rs

1//! [`GeminiBox2d`]: Gemini's `box_2d`, `[ymin, xmin, ymax, xmax]` on 0–1000, and its masks.
2
3use base64::Engine as _;
4use serde_json::{Value, json};
5
6use super::adapter::{RegionAdapter, image_index, label, quad};
7use crate::budget::ImageTokens;
8use crate::geometry::{AxisOrder, BBox, CoordFrame, Mask, Polygon, RawRegion, Shape};
9use crate::traits::ImageRegion;
10
11/// The two forms Gemini documents for segmentation masks, chosen per model ID.
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum GeminiMaskForm {
15    /// A base64 PNG probability map of the region inside its `box_2d`, thresholded at 127.
16    Png,
17    /// A polygon of `[y, x]` points on 0–1000.
18    Polygon,
19}
20
21/// Gemini's frame: `box_2d` as `[ymin, xmin, ymax, xmax]` on 0–1000 of the image as sent,
22/// whatever its aspect ratio ([`CoordFrame::Normalized`] with [`AxisOrder::Yx`]).
23///
24/// Masks are read in both documented forms whenever an answer carries one: a `mask` PNG
25/// probability map inside the box, or a `polygon` of `[y, x]` points. Either becomes a mask
26/// on the 1000 × 1000 grid of the frame, which the runtime maps to source pixels. Which
27/// form a model returns is decided per model ID ([`with_masks`](Self::with_masks)); none
28/// is requested by default.
29///
30/// # Example
31///
32/// ```
33/// use adk_vision::cloud::{GeminiBox2d, RegionAdapter};
34///
35/// let gemini = GeminiBox2d::for_model("gemini-3.8-flash");
36/// // One 258-token image up to 384 px a side, otherwise 258 per 768 px tile.
37/// assert_eq!(gemini.image_tokens().tokens((384, 300)), 258);
38/// assert_eq!(gemini.image_tokens().tokens((1920, 1080)), 6 * 258);
39/// ```
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct GeminiBox2d {
42    masks: Option<GeminiMaskForm>,
43}
44
45const FRAME: CoordFrame = CoordFrame::Normalized { scale: 1000, order: AxisOrder::Yx };
46
47impl GeminiBox2d {
48    /// The adapter for a Gemini model ID.
49    pub fn for_model(_model: &str) -> Self {
50        Self { masks: None }
51    }
52
53    /// Asks for masks in `form` as well as boxes.
54    pub fn with_masks(mut self, form: GeminiMaskForm) -> Self {
55        self.masks = Some(form);
56        self
57    }
58}
59
60impl RegionAdapter for GeminiBox2d {
61    fn name(&self) -> &str {
62        "gemini-box2d"
63    }
64
65    fn frame(&self) -> CoordFrame {
66        FRAME
67    }
68
69    fn image_tokens(&self) -> ImageTokens {
70        ImageTokens::GeminiTiles
71    }
72
73    fn region_schema(&self) -> Value {
74        let mut properties = json!({
75            "label": {"type": "string"},
76            "box_2d": {
77                "type": "array",
78                "items": {"type": "integer"},
79                "description": "[ymin, xmin, ymax, xmax] normalized to 0-1000."
80            }
81        });
82        let mut required = vec!["label", "box_2d"];
83        match self.masks {
84            Some(GeminiMaskForm::Png) => {
85                properties["mask"] = json!({
86                    "type": "string",
87                    "description": "A base64 PNG probability map of the region inside its box."
88                });
89                required.push("mask");
90            }
91            Some(GeminiMaskForm::Polygon) => {
92                properties["polygon"] = json!({
93                    "type": "array",
94                    "items": {"type": "array", "items": {"type": "integer"}},
95                    "description": "The region's outline as [y, x] points normalized to 0-1000."
96                });
97                required.push("polygon");
98            }
99            None => {}
100        }
101        json!({"type": "object", "properties": properties, "required": required})
102    }
103
104    fn instructions(&self, sizes: &[(u32, u32)]) -> String {
105        let mut text = String::from(
106            "Give each region's `box_2d` as [ymin, xmin, ymax, xmax] normalized to 0-1000.",
107        );
108        if sizes.len() > 1 {
109            text.push_str(" Name the image each region is in by its index, from 0.");
110        }
111        match self.masks {
112            Some(GeminiMaskForm::Png) => text.push_str(
113                " Give each region's segmentation mask in `mask` as a base64 PNG probability \
114                 map of the region inside its box.",
115            ),
116            Some(GeminiMaskForm::Polygon) => text.push_str(
117                " Give each region's outline in `polygon` as [y, x] points normalized to 0-1000.",
118            ),
119            None => {}
120        }
121        text
122    }
123
124    fn parse_region(
125        &self,
126        item: &Value,
127        sizes: &[(u32, u32)],
128    ) -> Result<Option<ImageRegion>, String> {
129        let image = image_index(item, sizes)?;
130        let Some(raw) = quad(item, &["box_2d", "box", "bbox"])? else {
131            return Ok(None);
132        };
133        let bbox = FRAME.box_from_raw(raw);
134        let shape = if let Some(mask) = item.get("mask").and_then(Value::as_str) {
135            Shape::Mask(png_mask(mask, &bbox)?)
136        } else if let Some(points) = item.get("polygon").or_else(|| item.get("points")) {
137            Shape::Polygon(polygon(points)?)
138        } else {
139            Shape::Box(bbox)
140        };
141        let mut region = RawRegion::shape(shape);
142        region.label = label(item);
143        Ok(Some(ImageRegion { image, region }))
144    }
145}
146
147/// Decodes a probability-map PNG, scales it to the box's cells of the 1000 × 1000 grid and
148/// thresholds it at 127, as Gemini's documentation does in pixels.
149fn png_mask(data: &str, bbox: &BBox) -> Result<Mask, String> {
150    let b64 = data.split_once("base64,").map_or(data, |(_, b)| b);
151    let bytes = base64::engine::general_purpose::STANDARD
152        .decode(b64.trim())
153        .map_err(|e| format!("`mask` is not base64: {e}"))?;
154    let png = image::load_from_memory_with_format(&bytes, image::ImageFormat::Png)
155        .map_err(|e| format!("`mask` is not a PNG: {e}"))?
156        .to_luma8();
157    let clamped = bbox.clamped(1000, 1000);
158    let (x0, y0, w, h) = clamped.pixel_bounds(1000, 1000);
159    if w == 0 || h == 0 {
160        return Ok(Mask::empty(1000, 1000));
161    }
162    let scaled = image::imageops::resize(&png, w, h, image::imageops::FilterType::Triangle);
163    let mut bits = vec![false; 1000 * 1000];
164    for (x, y, p) in scaled.enumerate_pixels() {
165        if p.0[0] > 127 {
166            bits[(y0 + y) as usize * 1000 + (x0 + x) as usize] = true;
167        }
168    }
169    Ok(Mask::encode(1000, 1000, &bits))
170}
171
172/// Reads `[y, x]` points on 0–1000 into a polygon with x first.
173fn polygon(points: &Value) -> Result<Polygon, String> {
174    let list = points.as_array().ok_or_else(|| format!("`polygon` is not a list: {points}"))?;
175    let mut out = Vec::with_capacity(list.len());
176    for p in list {
177        let pair = p
178            .as_array()
179            .filter(|a| a.len() == 2)
180            .and_then(|a| Some([a[0].as_f64()? as f32, a[1].as_f64()? as f32]))
181            .filter(|[a, b]| a.is_finite() && b.is_finite())
182            .ok_or_else(|| format!("`polygon` holds a point that is not [y, x]: {p}"))?;
183        out.push(FRAME.point_from_raw(pair));
184    }
185    if out.len() < 3 {
186        return Err(format!("`polygon` has {} points; a region needs three", out.len()));
187    }
188    Ok(Polygon { points: out })
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> u8) -> String {
196        let img = image::GrayImage::from_fn(w, h, |x, y| image::Luma([f(x, y)]));
197        let mut bytes = Vec::new();
198        img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
199        format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))
200    }
201
202    #[test]
203    fn boxes_are_read_y_first() {
204        let item = json!({"label": "cat", "box_2d": [100, 250, 500, 750]});
205        let found = GeminiBox2d::for_model("gemini-3.8-flash")
206            .parse_region(&item, &[(2000, 1000)])
207            .unwrap()
208            .unwrap();
209        assert_eq!(found.region.shape, Shape::Box(BBox::new(250.0, 100.0, 750.0, 500.0)));
210        assert_eq!(found.region.label.as_deref(), Some("cat"));
211    }
212
213    #[test]
214    fn png_masks_fill_their_box_on_the_grid() {
215        // The left half of the map is set.
216        let item = json!({
217            "label": "half",
218            "box_2d": [100, 200, 300, 600],
219            "mask": png(64, 32, |x, _| if x < 32 { 255 } else { 0 })
220        });
221        let found = GeminiBox2d::for_model("gemini-2.5-flash")
222            .parse_region(&item, &[(1000, 1000)])
223            .unwrap()
224            .unwrap();
225        let Shape::Mask(mask) = found.region.shape else { panic!("not a mask") };
226        assert_eq!((mask.width, mask.height), (1000, 1000));
227        let b = mask.bbox().unwrap();
228        assert_eq!((b.x0, b.y0, b.y1), (200.0, 100.0, 300.0));
229        assert!((b.x1 - 400.0).abs() <= 1.0, "{b:?}");
230    }
231
232    #[test]
233    fn polygons_are_read_y_first() {
234        let item = json!({"box_2d": [0, 0, 10, 10], "polygon": [[0, 0], [0, 10], [10, 5]]});
235        let found = GeminiBox2d::for_model("gemini-2.5-flash")
236            .parse_region(&item, &[(100, 100)])
237            .unwrap()
238            .unwrap();
239        assert_eq!(
240            found.region.shape,
241            Shape::Polygon(Polygon { points: vec![[0.0, 0.0], [10.0, 0.0], [5.0, 10.0]] })
242        );
243    }
244
245    #[test]
246    fn malformed_masks_are_refused() {
247        let gemini = GeminiBox2d::for_model("gemini-2.5-flash");
248        let item = json!({"box_2d": [0, 0, 10, 10], "mask": "not base64 !!"});
249        assert!(gemini.parse_region(&item, &[(100, 100)]).is_err());
250        let item = json!({"box_2d": [0, 0, 10, 10], "polygon": [[0, 0]]});
251        assert!(gemini.parse_region(&item, &[(100, 100)]).is_err());
252    }
253}