Skip to main content

adk_vision/sam/
mod.rs

1//! The Meta `sam-3.1` client (spec 3.7 §7.7), feature `sam`.
2//!
3//! [`SamSegmenter`] is a remote [`Segmenter`] and [`Detector`]: each concept phrase is one
4//! `POST /v1/responses` request with the released image, streamed with `stream: true`
5//! through `response.completed`, and [`SamStreamParser`] reads the special-token answer —
6//! one line per frame, each object a box in source pixels and a mask covering that box.
7//! Box and point prompts go in one request in Meta's object-prompt grammar.
8//!
9//! | Item | Behaviour |
10//! |------|-----------|
11//! | Credentials | The Meta Model API key Muse uses (`META_API_KEY`, else `MODEL_API_KEY`), and Muse's base URL |
12//! | Frame | Pixels of the image as sent ([`CoordFrame::SentPixels`]); the runtime maps them to source pixels |
13//! | Price | $2.50 per 1,000 images from the `adk-model` catalog: one image unit, 2,500 µUSD, per request; a five-concept query is five requests |
14//! | Rate limits | On 429 the client backs off exponentially with jitter, honouring `Retry-After`, then returns `RateLimited` with the hint |
15//! | Masks | Each object is its box, unless [`SamConfig::with_mask_decoder`] chooses a decoder ([`MaskDecoderChoice`]): a user-installed program ([`ExternalMaskDecoder`]) or, with feature `sam-codec` and recorded acceptance of the SAM License, the port of Meta's codec (`LicensedMaskDecoder`); a decoded mask is placed into a source-sized mask |
16//!
17//! # Example
18//!
19//! ```no_run
20//! use std::sync::Arc;
21//! use adk_vision::{SamConfig, SamSegmenter, VisionRuntime};
22//!
23//! let sam = SamSegmenter::new(SamConfig::from_env()?)?;
24//! let runtime = VisionRuntime::builder()
25//!     .remote_segmenter(Arc::new(sam))
26//!     .build()?;
27//! # Ok::<(), adk_vision::VisionError>(())
28//! ```
29
30mod decode;
31mod parse;
32mod video;
33
34use std::sync::Arc;
35use std::time::Duration;
36
37use adk_core::{AdkError, ErrorCategory, ErrorComponent, UsageUnit};
38use adk_model::pricing::PricingCatalog;
39use async_trait::async_trait;
40use base64::Engine as _;
41use futures::StreamExt;
42use serde_json::{Value, json};
43
44pub use crate::mask_decoder::MaskDecoderChoice;
45#[cfg(feature = "sam-codec")]
46pub use decode::LicensedMaskDecoder;
47pub use decode::{ExternalMaskDecoder, SamMaskDecoder};
48pub use parse::{SamMask, SamMaskEncoding, SamRecord, SamStreamParser};
49pub use video::{Propagation, SAM_VIDEO_INLINE_LIMIT, SamVideoTracker};
50
51use crate::backend::{BackendDescriptor, Locality, PriceRef};
52use crate::cx::VisionCx;
53use crate::egress::ReleasedImage;
54use crate::error::{Result, VisionError};
55use crate::geometry::{BBox, CoordFrame, Mask, RawRegion, Shape};
56use crate::manifest::AcceptanceStore;
57use crate::traits::{DetectQuery, Detector, SegmentPrompt, Segmenter};
58use parse::{SamEvent, SseBuffer, event};
59
60/// The spend-key vendor of the Meta Model API, which Muse and `sam-3.1` share.
61const VENDOR: &str = "muse";
62/// The most objects one object-prompt request may name.
63const MAX_OBJECTS: usize = 16;
64
65/// How to reach `sam-3.1`.
66///
67/// The key and base URL are Muse's (spec 3.7 Q5: one Meta Model API key authorises both,
68/// confirmed live on 2026-11-19).
69///
70/// # Example
71///
72/// ```
73/// use adk_vision::SamConfig;
74///
75/// let config = SamConfig::new("meta-key").with_confidence(true);
76/// assert_eq!(config.host().unwrap(), "api.meta.ai");
77/// assert!(!format!("{config:?}").contains("meta-key"));
78/// ```
79#[derive(Clone)]
80pub struct SamConfig {
81    api_key: String,
82    base_url: String,
83    model: String,
84    max_retries: u32,
85    include_confidence: bool,
86    one_bit: bool,
87    timeout: Duration,
88    masks: MaskDecoderChoice,
89    acceptances: Option<Arc<dyn AcceptanceStore>>,
90}
91
92impl std::fmt::Debug for SamConfig {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_struct("SamConfig")
95            .field("api_key", &"[REDACTED]")
96            .field("base_url", &self.base_url)
97            .field("model", &self.model)
98            .field("max_retries", &self.max_retries)
99            .field("include_confidence", &self.include_confidence)
100            .field("one_bit", &self.one_bit)
101            .field("timeout", &self.timeout)
102            .field("masks", &self.masks)
103            .field("acceptances", &self.acceptances.is_some())
104            .finish()
105    }
106}
107
108impl SamConfig {
109    /// `sam-3.1` at Muse's base URL with `api_key`.
110    pub fn new(api_key: impl Into<String>) -> Self {
111        Self {
112            api_key: api_key.into(),
113            base_url: adk_model::muse::MUSE_API_BASE.to_string(),
114            model: "sam-3.1".into(),
115            max_retries: 3,
116            include_confidence: false,
117            one_bit: false,
118            timeout: Duration::from_secs(300),
119            masks: MaskDecoderChoice::None,
120            acceptances: None,
121        }
122    }
123
124    /// The key and base URL of a Muse configuration.
125    pub fn from_muse(muse: &adk_model::MuseConfig) -> Self {
126        Self::new(muse.api_key.clone()).with_base_url(muse.effective_base_url())
127    }
128
129    /// The key from `META_API_KEY`, else `MODEL_API_KEY`, as Muse reads it.
130    ///
131    /// # Errors
132    ///
133    /// [`VisionError::InvalidInput`] when neither is set.
134    pub fn from_env() -> Result<Self> {
135        ["META_API_KEY", "MODEL_API_KEY"]
136            .iter()
137            .find_map(|name| std::env::var(name).ok().filter(|k| !k.is_empty()))
138            .map(Self::new)
139            .ok_or_else(|| {
140                VisionError::InvalidInput(
141                    "set META_API_KEY (or MODEL_API_KEY) to the Meta Model API key".into(),
142                )
143            })
144    }
145
146    /// Calls `base_url` (ending in `/v1`) instead of Meta's.
147    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
148        self.base_url = base_url.into().trim_end_matches('/').to_string();
149        self
150    }
151
152    /// Retries a rate-limited request up to `retries` times.
153    pub fn with_max_retries(mut self, retries: u32) -> Self {
154        self.max_retries = retries;
155        self
156    }
157
158    /// Asks for each object's confidence, returned as the region's score.
159    pub fn with_confidence(mut self, include: bool) -> Self {
160        self.include_confidence = include;
161        self
162    }
163
164    /// Asks for `one_bit` masks, several times smaller than the default `lossless` ones.
165    pub fn with_one_bit_masks(mut self, one_bit: bool) -> Self {
166        self.one_bit = one_bit;
167        self
168    }
169
170    /// Ends a request that takes longer than `timeout`.
171    pub fn with_timeout(mut self, timeout: Duration) -> Self {
172        self.timeout = timeout;
173        self
174    }
175
176    /// Chooses how masks are decoded; [`MaskDecoderChoice::None`], boxes only, by default.
177    /// [`SamSegmenter::new`] builds and checks the decoder.
178    ///
179    /// # Example
180    ///
181    /// ```
182    /// use adk_vision::{MaskDecoderChoice, SamConfig, SamSegmenter};
183    ///
184    /// // A program that is not installed is refused when the segmenter is built.
185    /// let config = SamConfig::new("meta-key")
186    ///     .with_mask_decoder(MaskDecoderChoice::external("no-such-sam-decoder", ["--json"]));
187    /// let refused = SamSegmenter::new(config).unwrap_err().to_string();
188    /// assert!(refused.contains("`no-such-sam-decoder` was not found on PATH"), "{refused}");
189    /// ```
190    pub fn with_mask_decoder(mut self, choice: MaskDecoderChoice) -> Self {
191        self.masks = choice;
192        self
193    }
194
195    /// Where [`MaskDecoderChoice::Licensed`] looks for a person's acceptance of the SAM
196    /// License, such as the project's `FileAcceptanceStore`. Without one, the licensed
197    /// decoder is refused.
198    pub fn with_licence_acceptances(mut self, store: Arc<dyn AcceptanceStore>) -> Self {
199        self.acceptances = Some(store);
200        self
201    }
202
203    /// The mask decoder this configuration chooses.
204    pub fn mask_decoder(&self) -> &MaskDecoderChoice {
205        &self.masks
206    }
207
208    /// The host requests go to.
209    ///
210    /// # Errors
211    ///
212    /// [`VisionError::InvalidInput`] for a base URL with no host.
213    pub fn host(&self) -> Result<String> {
214        let rest = self.base_url.split_once("://").map_or(self.base_url.as_str(), |(_, r)| r);
215        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
216        let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
217        let host = match host.strip_prefix('[') {
218            Some(v6) => v6.split(']').next().unwrap_or_default(),
219            None => host.split(':').next().unwrap_or_default(),
220        };
221        if host.is_empty() {
222            return Err(VisionError::InvalidInput(format!(
223                "the sam-3.1 base URL `{}` names no host",
224                self.base_url
225            )));
226        }
227        Ok(host.to_ascii_lowercase())
228    }
229}
230
231/// One `sam-3.1` request: the text part and the label its regions carry.
232struct Job {
233    text: String,
234    label: Option<String>,
235}
236
237/// What one request answered.
238struct Answer {
239    records: Vec<SamRecord>,
240}
241
242/// Meta's `sam-3.1` as a remote [`Segmenter`] and [`Detector`].
243///
244/// Regions are in pixels of the released image ([`CoordFrame::SentPixels`]). Each object
245/// is a [`Shape::Mask`] the size of the released image when a [`SamMaskDecoder`] is
246/// installed ([`with_mask_decoder`](Self::with_mask_decoder)), else a [`Shape::Box`].
247///
248/// # Example
249///
250/// ```
251/// use adk_vision::{CoordFrame, Locality, SamConfig, SamSegmenter, Segmenter, ReleasedImage};
252///
253/// let sam = SamSegmenter::new(SamConfig::new("meta-key")).unwrap();
254/// let d = Segmenter::<ReleasedImage>::descriptor(&sam);
255/// assert_eq!(d.frame, CoordFrame::SentPixels);
256/// assert_eq!(d.locality, Locality::Remote { hosts: vec!["api.meta.ai".into()] });
257/// assert_eq!(d.price.as_ref().unwrap().request_cost(1), Some(2_500));
258/// assert_eq!(d.concepts_per_request, Some(1));
259/// ```
260pub struct SamSegmenter {
261    config: SamConfig,
262    http: reqwest::Client,
263    descriptor: BackendDescriptor,
264    decoder: Option<Arc<dyn SamMaskDecoder>>,
265}
266
267impl std::fmt::Debug for SamSegmenter {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        f.debug_struct("SamSegmenter")
270            .field("config", &self.config)
271            .field("descriptor", &self.descriptor)
272            .field("mask_decoder", &self.decoder.is_some())
273            .finish()
274    }
275}
276
277impl SamSegmenter {
278    /// A client for `config`, with the mask decoder it chooses.
279    ///
280    /// # Errors
281    ///
282    /// [`VisionError::InvalidInput`] for a base URL with no host, an external mask decoder
283    /// that is not installed, or when the `adk-model` catalog has no image price for the
284    /// model; [`VisionError::LicenceAcceptanceRequired`] for the licensed decoder before a
285    /// person accepted the SAM License; [`VisionError::Unsupported`] for the licensed
286    /// decoder without feature `sam-codec`; [`VisionError::Backend`] when the HTTP client
287    /// cannot be built.
288    pub fn new(config: SamConfig) -> Result<Self> {
289        let host = config.host()?;
290        let decoder = decode::decoder_for(&config.masks, config.acceptances.as_deref())?;
291        let rate = PricingCatalog::standard()
292            .unit_price(Some(VENDOR), &config.model, UsageUnit::Images)
293            .map(|p| p.rate)
294            .ok_or_else(|| {
295                VisionError::InvalidInput(format!(
296                    "the pricing catalog has no image price for `{}`",
297                    config.model
298                ))
299            })?;
300        let descriptor = BackendDescriptor::new(
301            config.model.clone(),
302            Locality::Remote { hosts: vec![host] },
303            CoordFrame::SentPixels,
304        )
305        .with_provider(VENDOR)
306        .with_price(PriceRef::PerUnit {
307            vendor: VENDOR.into(),
308            model: config.model.clone(),
309            rate,
310            min_units_per_request: 0,
311        })
312        .with_concepts_per_request(1);
313        let http = reqwest::Client::builder().timeout(config.timeout).build().map_err(|e| {
314            VisionError::Backend { backend: config.model.clone(), message: e.to_string() }
315        })?;
316        Ok(Self { config, http, descriptor, decoder })
317    }
318
319    /// Names the hosts the egress policy checks instead of the base URL's, for a gateway
320    /// that forwards to Meta.
321    pub fn with_hosts<H: Into<String>>(mut self, hosts: impl IntoIterator<Item = H>) -> Self {
322        self.descriptor.locality =
323            Locality::Remote { hosts: hosts.into_iter().map(Into::into).collect() };
324        self
325    }
326
327    /// Answers with masks, decoded by `decoder`, in place of the one the configuration
328    /// chose.
329    pub fn with_mask_decoder(mut self, decoder: Arc<dyn SamMaskDecoder>) -> Self {
330        self.decoder = Some(decoder);
331        self
332    }
333
334    /// The request body for one text part and the released image.
335    pub(crate) fn body(&self, text: &str, image: &ReleasedImage) -> Value {
336        let data = base64::engine::general_purpose::STANDARD.encode(image.bytes());
337        let mut body = json!({
338            "model": self.config.model,
339            "stream": true,
340            "input": [{
341                "type": "message",
342                "role": "user",
343                "content": [
344                    {"type": "input_text", "text": text},
345                    {"type": "input_image", "image_url": format!("data:{};base64,{data}", image.mime_type())}
346                ]
347            }]
348        });
349        let mut metadata = serde_json::Map::new();
350        if self.config.include_confidence {
351            metadata.insert("include_confidence".into(), json!("true"));
352        }
353        if self.config.one_bit {
354            metadata.insert("mask_encoding".into(), json!("one_bit"));
355        }
356        if !metadata.is_empty() {
357            body["metadata"] = Value::Object(metadata);
358        }
359        body
360    }
361
362    async fn segment_jobs(
363        &self,
364        cx: &VisionCx,
365        image: &ReleasedImage,
366        jobs: Vec<Job>,
367    ) -> Result<Vec<RawRegion>> {
368        if !image.is_for(&self.descriptor.id) {
369            return Err(VisionError::NotReleased { backend: self.descriptor.id.to_string() });
370        }
371        let mut regions = Vec::new();
372        for job in jobs {
373            cx.check()?;
374            let answer = self.request(cx, &job.text, image).await?;
375            regions.extend(self.regions(image, answer, job.label).await?);
376        }
377        Ok(regions)
378    }
379
380    async fn regions(
381        &self,
382        image: &ReleasedImage,
383        answer: Answer,
384        label: Option<String>,
385    ) -> Result<Vec<RawRegion>> {
386        let sent = image.image().size();
387        let parse = |message: String| VisionError::Parse {
388            backend: self.descriptor.id.to_string(),
389            message,
390        };
391        for r in &answer.records {
392            if r.source != sent {
393                return Err(parse(format!(
394                    "a record is in a {}x{} frame, but the image sent is {}x{}",
395                    r.source.0, r.source.1, sent.0, sent.1
396                )));
397            }
398        }
399        let rasters = match &self.decoder {
400            Some(decoder) => {
401                let masks: Vec<SamMask> = answer.records.iter().map(|r| r.mask.clone()).collect();
402                let rasters = decoder.decode(&masks).await?;
403                if rasters.len() != masks.len() {
404                    return Err(parse(format!(
405                        "{} rasters for {} masks",
406                        rasters.len(),
407                        masks.len()
408                    )));
409                }
410                Some(rasters)
411            }
412            None => None,
413        };
414        let mut out = Vec::with_capacity(answer.records.len());
415        for (i, record) in answer.records.iter().enumerate() {
416            let [x0, y0, x1, y1] = record.bounds;
417            let shape = match rasters.as_ref().map(|r| &r[i]) {
418                Some(bits) => Shape::Mask(place(bits, record, sent).map_err(parse)?),
419                None => Shape::Box(BBox::new(x0 as f32, y0 as f32, x1 as f32, y1 as f32)),
420            };
421            out.push(RawRegion {
422                shape,
423                label: label.clone().or_else(|| Some(format!("object {}", record.object))),
424                score: record.confidence,
425                track: None,
426            });
427        }
428        Ok(out)
429    }
430
431    /// Sends one request, retrying rate limits, and reads its stream to the end.
432    async fn request(&self, cx: &VisionCx, text: &str, image: &ReleasedImage) -> Result<Answer> {
433        self.send(cx, &self.body(text, image)).await
434    }
435
436    /// Posts `body` to `/responses`, retrying rate limits, and reads its stream to the end.
437    async fn send(&self, cx: &VisionCx, body: &Value) -> Result<Answer> {
438        let backend = self.descriptor.id.to_string();
439        let url = format!("{}/responses", self.config.base_url);
440        let mut attempt = 0u32;
441        loop {
442            cx.check()?;
443            let sent = self
444                .http
445                .post(&url)
446                .bearer_auth(&self.config.api_key)
447                .header("accept", "text/event-stream")
448                .json(body)
449                .send()
450                .await;
451            let response = match sent {
452                Ok(response) => response,
453                Err(err) if err.is_timeout() => return Err(VisionError::Timeout { backend }),
454                Err(err) => {
455                    return Err(VisionError::Unavailable {
456                        backend,
457                        message: redact(&err.to_string()),
458                    });
459                }
460            };
461            let status = response.status();
462            if status.as_u16() == 429 {
463                let retry_after = response
464                    .headers()
465                    .get("retry-after")
466                    .and_then(|v| v.to_str().ok())
467                    .and_then(|v| v.trim().parse::<f64>().ok())
468                    .filter(|s| s.is_finite() && *s >= 0.0)
469                    .map(Duration::from_secs_f64);
470                if attempt >= self.config.max_retries {
471                    return Err(VisionError::RateLimited { backend, retry_after });
472                }
473                let wait = retry_after.unwrap_or_else(|| backoff(attempt));
474                attempt += 1;
475                tracing::debug!(vision.backend = %backend, retry.attempt = attempt, retry.wait_ms = wait.as_millis() as u64, "sam-3.1 rate limited; backing off");
476                tokio::select! {
477                    () = cx.cancellation().cancelled() => return Err(VisionError::Cancelled),
478                    () = tokio::time::sleep(wait) => continue,
479                }
480            }
481            if !status.is_success() {
482                let text = response.text().await.unwrap_or_default();
483                return Err(status_error(&backend, status.as_u16(), &text));
484            }
485            return self.read_stream(&backend, response).await;
486        }
487    }
488
489    async fn read_stream(&self, backend: &str, response: reqwest::Response) -> Result<Answer> {
490        let parse = |message: String| VisionError::Parse { backend: backend.to_string(), message };
491        let mut sse = SseBuffer::default();
492        let mut parser = SamStreamParser::new();
493        let mut records = Vec::new();
494        let mut done_text: Option<String> = None;
495        let mut completed = false;
496        let mut bytes = response.bytes_stream();
497        let mut pending: Vec<u8> = Vec::new();
498        let mut handle = |data: String,
499                          records: &mut Vec<SamRecord>,
500                          parser: &mut SamStreamParser|
501         -> Result<()> {
502            match event(&data).map_err(parse)? {
503                SamEvent::Delta(delta) => records.extend(parser.push(&delta).map_err(parse)?),
504                SamEvent::Done(text) => done_text = Some(text),
505                SamEvent::Completed { .. } => completed = true,
506                SamEvent::Failed(message) => {
507                    return Err(VisionError::Backend { backend: backend.to_string(), message });
508                }
509                SamEvent::Other => {}
510            }
511            Ok(())
512        };
513        while let Some(chunk) = bytes.next().await {
514            let chunk = chunk.map_err(|e| VisionError::Unavailable {
515                backend: backend.to_string(),
516                message: redact(&e.to_string()),
517            })?;
518            pending.extend_from_slice(&chunk);
519            // Keep an incomplete UTF-8 sequence for the next chunk.
520            let valid = match std::str::from_utf8(&pending) {
521                Ok(_) => pending.len(),
522                Err(e) => e.valid_up_to(),
523            };
524            let text = String::from_utf8_lossy(&pending[..valid]).into_owned();
525            pending.drain(..valid);
526            for data in sse.push(&text) {
527                handle(data, &mut records, &mut parser)?;
528            }
529        }
530        for data in sse.finish() {
531            handle(data, &mut records, &mut parser)?;
532        }
533        records.extend(parser.finish().map_err(parse)?);
534        match done_text {
535            // No deltas: the final text is the whole lane.
536            Some(text) if parser.text().is_empty() => {
537                records.extend(parser.push(&text).map_err(parse)?);
538                records.extend(parser.finish().map_err(parse)?);
539            }
540            Some(text) if text != parser.text() => {
541                return Err(parse("the final text differs from the streamed deltas".into()));
542            }
543            _ => {}
544        }
545        if !completed {
546            return Err(VisionError::Unavailable {
547                backend: backend.to_string(),
548                message: "the stream ended before `response.completed`".into(),
549            });
550        }
551        Ok(Answer { records })
552    }
553}
554
555/// Stretches a `height × width` raster over its box inside a source-sized mask: each source
556/// pixel in the box takes the raster cell under its centre.
557fn place(bits: &[bool], record: &SamRecord, sent: (u32, u32)) -> std::result::Result<Mask, String> {
558    let (w, h) = (record.mask.width as usize, record.mask.height as usize);
559    if bits.len() != w * h {
560        return Err(format!("a raster of {} bits for a {w}x{h} mask", bits.len()));
561    }
562    let (sw, sh) = (sent.0 as usize, sent.1 as usize);
563    let [x0, y0, x1, y1] = record.bounds.map(|v| v as usize);
564    if x1 > sw || y1 > sh {
565        return Err(format!("box ({x0}, {y0})-({x1}, {y1}) lies outside {sw}x{sh}"));
566    }
567    let (bw, bh) = (x1 - x0, y1 - y0);
568    let mut full = vec![false; sw * sh];
569    for y in y0..y1 {
570        let ry = (((y - y0) as f64 + 0.5) * h as f64 / bh as f64) as usize;
571        let row = &bits[ry.min(h - 1) * w..(ry.min(h - 1) + 1) * w];
572        for x in x0..x1 {
573            let rx = (((x - x0) as f64 + 0.5) * w as f64 / bw as f64) as usize;
574            full[y * sw + x] = row[rx.min(w - 1)];
575        }
576    }
577    Ok(Mask::encode(sent.0, sent.1, &full))
578}
579
580/// Exponential backoff with jitter: 0.5 s, 1 s, 2 s, ... plus up to half again.
581fn backoff(attempt: u32) -> Duration {
582    let base = 500u64.saturating_mul(1 << attempt.min(6));
583    let nanos = std::time::SystemTime::now()
584        .duration_since(std::time::UNIX_EPOCH)
585        .map(|d| u64::from(d.subsec_nanos()))
586        .unwrap_or(0);
587    Duration::from_millis(base + nanos % (base / 2 + 1))
588}
589
590fn status_error(backend: &str, status: u16, body: &str) -> VisionError {
591    let message = serde_json::from_str::<Value>(body)
592        .ok()
593        .and_then(|v| v.pointer("/error/message").and_then(Value::as_str).map(str::to_string))
594        .unwrap_or_else(|| body.chars().take(300).collect());
595    let message = redact(&message);
596    match status {
597        400 | 413 | 422 => {
598            VisionError::InvalidInput(format!("{backend} refused the request: {message}"))
599        }
600        401 | 403 => VisionError::Core(AdkError::new(
601            ErrorComponent::Tool,
602            ErrorCategory::Unauthorized,
603            "vision.sam.unauthorized",
604            format!(
605                "{backend} refused the key ({status}): {message}; check META_API_KEY and that \
606                 the Meta Model API account has sam-3.1"
607            ),
608        )),
609        404 => VisionError::BackendNotFound(format!("{backend} at this base URL: {message}")),
610        500..=599 => VisionError::Unavailable {
611            backend: backend.to_string(),
612            message: format!("{status}: {message}"),
613        },
614        _ => VisionError::Backend {
615            backend: backend.to_string(),
616            message: format!("{status}: {message}"),
617        },
618    }
619}
620
621/// Removes anything that looks like a bearer token from an error message.
622fn redact(message: &str) -> String {
623    message
624        .split_whitespace()
625        .map(|w| {
626            if w.len() > 32 && w.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) {
627                "[REDACTED]"
628            } else {
629                w
630            }
631        })
632        .collect::<Vec<_>>()
633        .join(" ")
634}
635
636/// The object-prompt text for box and point prompts, in pixels of an image of `size`.
637fn object_prompt(prompts: &[&SegmentPrompt], (w, h): (u32, u32)) -> Result<String> {
638    let clamp_x = |v: f32| (v.floor().max(0.0) as u32).min(w.saturating_sub(1));
639    let clamp_y = |v: f32| (v.floor().max(0.0) as u32).min(h.saturating_sub(1));
640    let mut objects: Vec<String> = Vec::new();
641    for prompt in prompts {
642        match prompt {
643            SegmentPrompt::Box { bbox } => {
644                let x1 = clamp_x(bbox.x0);
645                let y1 = clamp_y(bbox.y0);
646                let x2 = clamp_x(bbox.x1.ceil() - 1.0).max(x1);
647                let y2 = clamp_y(bbox.y1.ceil() - 1.0).max(y1);
648                objects.push(format!(
649                    "{}<|box;x1={x1};y1={y1};x2={x2};y2={y2};w={w};h={h}|>",
650                    objects.len() + 1
651                ));
652            }
653            SegmentPrompt::Point { at, positive } => {
654                let token =
655                    format!("<|point;x={};y={};w={w};h={h}|>", clamp_x(at[0]), clamp_y(at[1]));
656                let token = if *positive { token } else { format!("-{token}") };
657                match objects.last_mut() {
658                    Some(object) => object.push_str(&token),
659                    None if *positive => objects.push(format!("{}{token}", objects.len() + 1)),
660                    None => {
661                        return Err(VisionError::InvalidInput(
662                            "a negative point needs a box or positive point before it, naming the \
663                             object it is not part of"
664                                .into(),
665                        ));
666                    }
667                }
668            }
669            SegmentPrompt::Mask { .. } => {
670                return Err(VisionError::Unsupported(
671                    "sam-3.1 takes no mask prompts; give a box or points".into(),
672                ));
673            }
674            SegmentPrompt::Concept { .. } => {}
675        }
676    }
677    if objects.len() > MAX_OBJECTS {
678        return Err(VisionError::InvalidInput(format!(
679            "sam-3.1 takes at most {MAX_OBJECTS} objects per request; {} were given",
680            objects.len()
681        )));
682    }
683    Ok(format!("<0f>{}", objects.join(",")))
684}
685
686#[async_trait]
687impl Segmenter<ReleasedImage> for SamSegmenter {
688    fn descriptor(&self) -> &BackendDescriptor {
689        &self.descriptor
690    }
691
692    async fn segment(
693        &self,
694        cx: &VisionCx,
695        image: &ReleasedImage,
696        prompts: &[SegmentPrompt],
697    ) -> Result<Vec<RawRegion>> {
698        let mut jobs = Vec::new();
699        let mut objects = Vec::new();
700        for prompt in prompts {
701            match prompt {
702                SegmentPrompt::Concept { text } => {
703                    jobs.push(Job { text: text.clone(), label: Some(text.clone()) });
704                }
705                other => objects.push(other),
706            }
707        }
708        if !objects.is_empty() {
709            jobs.push(Job { text: object_prompt(&objects, image.image().size())?, label: None });
710        }
711        if jobs.is_empty() {
712            return Err(VisionError::InvalidInput("segment needs at least one prompt".into()));
713        }
714        self.segment_jobs(cx, image, jobs).await
715    }
716}
717
718#[async_trait]
719impl Detector<ReleasedImage> for SamSegmenter {
720    fn descriptor(&self) -> &BackendDescriptor {
721        &self.descriptor
722    }
723
724    async fn detect(
725        &self,
726        cx: &VisionCx,
727        image: &ReleasedImage,
728        query: &DetectQuery,
729    ) -> Result<Vec<RawRegion>> {
730        let concepts = match query {
731            DetectQuery::Concepts(c) | DetectQuery::Classes(c) => c,
732        };
733        if concepts.is_empty() {
734            return Err(VisionError::InvalidInput("detect needs at least one concept".into()));
735        }
736        let jobs =
737            concepts.iter().map(|c| Job { text: c.clone(), label: Some(c.clone()) }).collect();
738        self.segment_jobs(cx, image, jobs).await
739    }
740}
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745
746    #[test]
747    fn object_prompts_follow_the_grammar() {
748        let prompts = [
749            SegmentPrompt::Box { bbox: BBox::new(10.0, 20.0, 40.0, 60.0) },
750            SegmentPrompt::Point { at: [25.5, 30.2], positive: false },
751            SegmentPrompt::Point { at: [5.0, 5.0], positive: true },
752        ];
753        let refs: Vec<&SegmentPrompt> = prompts.iter().collect();
754        assert_eq!(
755            object_prompt(&refs, (640, 480)).unwrap(),
756            "<0f>1<|box;x1=10;y1=20;x2=39;y2=59;w=640;h=480|>-<|point;x=25;y=30;w=640;h=480|><|point;x=5;y=5;w=640;h=480|>"
757        );
758        let lonely = [SegmentPrompt::Point { at: [1.0, 1.0], positive: false }];
759        assert!(object_prompt(&lonely.iter().collect::<Vec<_>>(), (10, 10)).is_err());
760        let mask = [SegmentPrompt::Mask { mask: Mask::empty(2, 2) }];
761        assert!(matches!(
762            object_prompt(&mask.iter().collect::<Vec<_>>(), (10, 10)),
763            Err(VisionError::Unsupported(_))
764        ));
765    }
766
767    #[test]
768    fn downscaled_rasters_are_stretched_over_their_box() {
769        // A 2x1 raster over a 4x2 box: the left half set.
770        let record = parse::parse_line(
771            "<0f>0<|box;x1=1;y1=0;x2=4;y2=1;w=6;h=3|><|mask;x=0;y=0;data=1,2,~!|>",
772        )
773        .unwrap()
774        .remove(0);
775        let mask = place(&[true, false], &record, (6, 3)).unwrap();
776        let bits = mask.decode();
777        let set: Vec<usize> =
778            bits.iter().enumerate().filter(|(_, b)| **b).map(|(i, _)| i).collect();
779        assert_eq!(set, vec![1, 2, 7, 8]);
780    }
781
782    #[test]
783    fn rasters_are_placed_at_their_box() {
784        let record = parse::parse_line(
785            "<0f>0<|box;x1=2;y1=1;x2=3;y2=2;w=5;h=4|><|mask;x=0;y=0;data=2,2,~!|>",
786        )
787        .unwrap()
788        .remove(0);
789        let mask = place(&[true, false, true, true], &record, (5, 4)).unwrap();
790        let bits = mask.decode();
791        let set: Vec<usize> =
792            bits.iter().enumerate().filter(|(_, b)| **b).map(|(i, _)| i).collect();
793        // (2,1), (2,2) and (3,2) in a 5-wide raster.
794        assert_eq!(set, vec![7, 12, 13]);
795    }
796
797    #[test]
798    fn statuses_map_to_categories() {
799        let category = |status| AdkError::from(status_error("sam-3.1", status, "{}")).category;
800        assert_eq!(category(400), ErrorCategory::InvalidInput);
801        assert_eq!(category(401), ErrorCategory::Unauthorized);
802        assert_eq!(category(503), ErrorCategory::Unavailable);
803        let body = r#"{"error": {"message": "metadata[\"mask_encoding\"] must be one of ['lossless', 'one_bit']"}}"#;
804        assert!(status_error("sam-3.1", 400, body).to_string().contains("one_bit"));
805    }
806
807    #[test]
808    fn backoff_grows_and_keys_never_reach_messages() {
809        assert!(
810            backoff(0) >= Duration::from_millis(500) && backoff(0) <= Duration::from_millis(750)
811        );
812        assert!(backoff(3) >= Duration::from_millis(4_000));
813        assert!(
814            !redact("bad key sk-0123456789abcdef0123456789abcdef01")
815                .contains("0123456789abcdef0123")
816        );
817    }
818}