Skip to main content

adk_vision/sam/
parse.rs

1//! The `sam-3.1` answer: server-sent events carrying special-token text, one line per frame.
2
3use std::collections::BTreeMap;
4
5/// How a mask payload is encoded, from the first character after `H,W,`.
6#[non_exhaustive]
7#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum SamMaskEncoding {
10    /// `~`: the API default, coverage bytes.
11    Lossless,
12    /// `!`: one bit per pixel.
13    OneBit,
14}
15
16impl SamMaskEncoding {
17    /// The character the payload starts with on the wire, before [`SamMask::payload`].
18    pub fn marker(self) -> char {
19        match self {
20            Self::Lossless => '~',
21            Self::OneBit => '!',
22        }
23    }
24}
25
26/// One mask token: a `height` × `width` raster stretched over the record's box, with its
27/// payload kept exactly as the API sent it. A small box's raster is the box at source
28/// resolution; a large box's is downscaled (a 1699×398 box came back as 1024×240).
29#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
30pub struct SamMask {
31    /// Raster rows.
32    pub height: u32,
33    /// Raster columns.
34    pub width: u32,
35    /// The payload's encoding.
36    pub encoding: SamMaskEncoding,
37    /// The base85 payload after the encoding marker, opaque.
38    pub payload: String,
39}
40
41/// One object on one frame: its identifier, its box and its mask.
42#[derive(Clone, Debug, PartialEq)]
43pub struct SamRecord {
44    /// The frame index; always 0 for an image.
45    pub frame: u64,
46    /// The object identifier, stable across the frames of one response.
47    pub object: String,
48    /// `[left, top, right, bottom)` in source pixels: the wire's inclusive `x2` and `y2`
49    /// plus one.
50    pub bounds: [u32; 4],
51    /// The source width and height the box is in.
52    pub source: (u32, u32),
53    /// The confidence, when the request asked for it.
54    pub confidence: Option<f32>,
55    /// The mask, stretched over `bounds`.
56    pub mask: SamMask,
57}
58
59/// Parses the `output_text` lane into records as lines arrive, so a long video yields
60/// records frame by frame.
61///
62/// Each line is `<Nf>` followed by records `id<|box;x1=..;y1=..;x2=..;y2=..;w=..;h=..|>
63/// <|mask;x=0;y=0;data=H,W,<enc><payload>|>`, optionally comma-separated, per Meta's
64/// published SAM 3 text format. A malformed line is an error: nothing is guessed.
65///
66/// # Example
67///
68/// ```
69/// use adk_vision::sam::SamStreamParser;
70///
71/// let mut parser = SamStreamParser::new();
72/// let line = "<0f>0<|box;x1=10;y1=20;x2=14;y2=24;w=100;h=80|><|mask;x=0;y=0;data=5,5,!!!!!(QO(0lu8?|>";
73/// assert!(parser.push(&line[..30]).unwrap().is_empty());
74/// let records = parser.push(&format!("{}\n", &line[30..])).unwrap();
75/// assert_eq!(records[0].bounds, [10, 20, 15, 25]);
76/// assert_eq!((records[0].mask.height, records[0].mask.width), (5, 5));
77/// ```
78#[derive(Debug, Default)]
79pub struct SamStreamParser {
80    buffer: String,
81    text: String,
82}
83
84impl SamStreamParser {
85    /// An empty parser.
86    pub fn new() -> Self {
87        Self::default()
88    }
89
90    /// Adds a text delta and returns the records of every line it completed.
91    ///
92    /// # Errors
93    ///
94    /// A message naming the malformed line.
95    pub fn push(&mut self, delta: &str) -> Result<Vec<SamRecord>, String> {
96        self.text.push_str(delta);
97        self.buffer.push_str(delta);
98        let mut records = Vec::new();
99        while let Some(end) = self.buffer.find('\n') {
100            let line: String = self.buffer.drain(..=end).collect();
101            records.extend(parse_line(line.trim_end_matches(['\n', '\r']))?);
102        }
103        Ok(records)
104    }
105
106    /// Ends the lane and returns the records of a last line with no newline.
107    ///
108    /// # Errors
109    ///
110    /// A message naming the malformed line.
111    pub fn finish(&mut self) -> Result<Vec<SamRecord>, String> {
112        let line = std::mem::take(&mut self.buffer);
113        parse_line(line.trim())
114    }
115
116    /// Every character received so far.
117    pub fn text(&self) -> &str {
118        &self.text
119    }
120}
121
122/// Parses one line; an empty line has no records.
123pub(crate) fn parse_line(line: &str) -> Result<Vec<SamRecord>, String> {
124    let line = line.trim();
125    if line.is_empty() {
126        return Ok(Vec::new());
127    }
128    let bad = |why: &str| format!("malformed sam-3.1 line ({why}): {}", preview(line));
129    // The format keeps a line that does not start with `<` as text, not a record.
130    let Some(rest) = line.strip_prefix('<') else {
131        tracing::debug!(sam.line = %preview(line), "skipping a sam-3.1 text line");
132        return Ok(Vec::new());
133    };
134    let close = rest.find('>').ok_or_else(|| bad("unclosed frame marker"))?;
135    let marker = &rest[..close];
136    let index = marker.split(';').next().unwrap_or_default();
137    let frame: u64 = index
138        .strip_suffix('f')
139        .and_then(|n| n.parse().ok())
140        .ok_or_else(|| bad("frame marker is not <Nf>"))?;
141    let mut rest = &rest[close + 1..];
142    if rest.is_empty() {
143        return Err(bad("a frame marker with no records"));
144    }
145    let mut records = Vec::new();
146    while !rest.is_empty() {
147        rest = rest.strip_prefix(',').unwrap_or(rest);
148        let digits = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
149        if digits == 0 {
150            return Err(bad("a record does not start with an object id"));
151        }
152        let object = rest[..digits].to_string();
153        rest = &rest[digits..];
154        let mut tokens: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
155        while let Some(body) = rest.strip_prefix("<|") {
156            let end = body.find("|>").ok_or_else(|| bad("unclosed token"))?;
157            let token = &body[..end];
158            rest = &body[end + 2..];
159            let (name, fields) = token.split_once(';').unwrap_or((token, ""));
160            let mut map = BTreeMap::new();
161            for field in fields.split(';') {
162                let field = field.trim();
163                if field.is_empty() {
164                    continue;
165                }
166                let (k, v) = field.split_once('=').unwrap_or((field, ""));
167                if map.insert(k.trim().to_string(), v.trim().to_string()).is_some() && k != "c" {
168                    return Err(bad("a repeated field"));
169                }
170            }
171            if matches!(name, "box" | "mask") && tokens.insert(name.to_string(), map).is_some() {
172                return Err(bad("a repeated token"));
173            }
174        }
175        if !rest.is_empty()
176            && !rest.starts_with(',')
177            && !rest.starts_with(|c: char| c.is_ascii_digit())
178        {
179            return Err(bad("text between tokens"));
180        }
181        let (Some(b), Some(m)) = (tokens.get("box"), tokens.get("mask")) else {
182            return Err(bad("a record without one box and one mask"));
183        };
184        records.push(record(frame, object, b, m).map_err(|why| bad(&why))?);
185    }
186    Ok(records)
187}
188
189fn record(
190    frame: u64,
191    object: String,
192    b: &BTreeMap<String, String>,
193    m: &BTreeMap<String, String>,
194) -> Result<SamRecord, String> {
195    let int = |k: &str| -> Result<i64, String> {
196        b.get(k)
197            .and_then(|v| v.parse().ok())
198            .ok_or_else(|| format!("box `{k}` is missing or not an integer"))
199    };
200    let (x1, y1, x2, y2, w, h) =
201        (int("x1")?, int("y1")?, int("x2")?, int("y2")?, int("w")?, int("h")?);
202    if w <= 0 || h <= 0 || x1 < 0 || y1 < 0 || x2 < x1 || y2 < y1 || x2 >= w || y2 >= h {
203        return Err(format!("box ({x1}, {y1})-({x2}, {y2}) does not lie inside {w}x{h}"));
204    }
205    let as_u32 = |v: i64| u32::try_from(v).map_err(|_| format!("{v} is out of range"));
206    let bounds = [as_u32(x1)?, as_u32(y1)?, as_u32(x2 + 1)?, as_u32(y2 + 1)?];
207    if m.get("x").map(String::as_str) != Some("0") || m.get("y").map(String::as_str) != Some("0") {
208        return Err("mask `x` and `y` are not 0".into());
209    }
210    let data = m.get("data").ok_or("mask has no `data`")?;
211    let mut parts = data.splitn(3, ',');
212    let height: u32 =
213        parts.next().and_then(|v| v.parse().ok()).ok_or("mask height is not a number")?;
214    let width: u32 =
215        parts.next().and_then(|v| v.parse().ok()).ok_or("mask width is not a number")?;
216    let payload = parts.next().ok_or("mask has no payload")?;
217    let mut chars = payload.chars();
218    let encoding = match chars.next() {
219        Some('~') => SamMaskEncoding::Lossless,
220        Some('!') => SamMaskEncoding::OneBit,
221        _ => return Err("mask payload has no encoding marker".into()),
222    };
223    if height == 0 || width == 0 {
224        return Err("mask has no pixels".into());
225    }
226    let confidence =
227        b.get("c").and_then(|c| c.parse::<f32>().ok()).filter(|c| (0.0..=1.0).contains(c));
228    Ok(SamRecord {
229        frame,
230        object,
231        bounds,
232        source: (as_u32(w)?, as_u32(h)?),
233        confidence,
234        mask: SamMask { height, width, encoding, payload: chars.as_str().to_string() },
235    })
236}
237
238fn preview(line: &str) -> String {
239    let mut end = line.len().min(120);
240    while !line.is_char_boundary(end) {
241        end -= 1;
242    }
243    if end < line.len() { format!("{}...", &line[..end]) } else { line.to_string() }
244}
245
246/// One server-sent event of a `/v1/responses` stream, reduced to what the client needs.
247#[derive(Debug, PartialEq)]
248pub(crate) enum SamEvent {
249    /// Text for the output lane.
250    Delta(String),
251    /// The lane's final text.
252    Done(String),
253    /// The response completed; the images it reports processing.
254    Completed { images: Option<u64> },
255    /// The response failed or was cut short.
256    Failed(String),
257    /// Anything else.
258    Other,
259}
260
261/// Splits a byte stream of server-sent events into their `data:` payloads.
262#[derive(Debug, Default)]
263pub(crate) struct SseBuffer {
264    buffer: String,
265}
266
267impl SseBuffer {
268    /// Adds bytes and returns every complete event's data.
269    pub(crate) fn push(&mut self, chunk: &str) -> Vec<String> {
270        self.buffer.push_str(&chunk.replace("\r\n", "\n"));
271        let mut events = Vec::new();
272        while let Some(end) = self.buffer.find("\n\n") {
273            let block: String = self.buffer.drain(..end + 2).collect();
274            let data: Vec<&str> = block
275                .lines()
276                .filter_map(|l| l.strip_prefix("data:"))
277                .map(|d| d.strip_prefix(' ').unwrap_or(d))
278                .collect();
279            if !data.is_empty() {
280                events.push(data.join("\n"));
281            }
282        }
283        events
284    }
285
286    /// The data of a last event with no blank line after it.
287    pub(crate) fn finish(&mut self) -> Vec<String> {
288        let rest = std::mem::take(&mut self.buffer);
289        let data: Vec<&str> = rest
290            .lines()
291            .filter_map(|l| l.strip_prefix("data:"))
292            .map(|d| d.strip_prefix(' ').unwrap_or(d))
293            .collect();
294        if data.is_empty() { Vec::new() } else { vec![data.join("\n")] }
295    }
296}
297
298/// Reads one event's data.
299pub(crate) fn event(data: &str) -> Result<SamEvent, String> {
300    if data.trim() == "[DONE]" {
301        return Ok(SamEvent::Other);
302    }
303    let value: serde_json::Value =
304        serde_json::from_str(data).map_err(|e| format!("an event is not JSON: {e}"))?;
305    let kind = value.get("type").and_then(|t| t.as_str()).unwrap_or_default();
306    Ok(match kind {
307        "response.output_text.delta" => {
308            SamEvent::Delta(value["delta"].as_str().unwrap_or_default().to_string())
309        }
310        "response.output_text.done" => {
311            SamEvent::Done(value["text"].as_str().unwrap_or_default().to_string())
312        }
313        "response.completed" => {
314            SamEvent::Completed { images: value["response"]["usage"]["images_processed"].as_u64() }
315        }
316        "response.failed" | "response.incomplete" | "error" => SamEvent::Failed(
317            value
318                .pointer("/response/error/message")
319                .or_else(|| value.pointer("/error/message"))
320                .or_else(|| value.pointer("/message"))
321                .or_else(|| value.pointer("/response/incomplete_details/reason"))
322                .and_then(|m| m.as_str())
323                .unwrap_or(kind)
324                .to_string(),
325        ),
326        "response.refusal.delta" | "response.refusal.done" => {
327            SamEvent::Failed("the model refused the request".into())
328        }
329        _ => SamEvent::Other,
330    })
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    const LINE: &str =
338        "<7f>0<|box;x1=10;y1=20;x2=14;y2=24;w=100;h=80|><|mask;x=0;y=0;data=5,5,!!!!!(QO(0lu8?|>";
339
340    #[test]
341    fn the_protocol_example_parses() {
342        let records = parse_line(LINE).unwrap();
343        assert_eq!(records.len(), 1);
344        let r = &records[0];
345        assert_eq!((r.frame, r.object.as_str()), (7, "0"));
346        assert_eq!(r.bounds, [10, 20, 15, 25]);
347        assert_eq!(r.source, (100, 80));
348        assert_eq!(r.mask.encoding, SamMaskEncoding::OneBit);
349        assert_eq!(r.mask.payload, "!!!!(QO(0lu8?");
350    }
351
352    #[test]
353    fn confidences_and_several_records_parse() {
354        let line = "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10;c=0.75|><|mask;x=0;y=0;c=0.75;data=2,2,~!!|>,\
355                    2<|box;x1=3;y1=3;x2=3;y2=3;w=10;h=10|><|mask;x=0;y=0;data=1,1,~!|>";
356        let records = parse_line(line).unwrap();
357        assert_eq!(records.len(), 2);
358        assert_eq!(records[0].confidence, Some(0.75));
359        assert_eq!(records[1].object, "2");
360        assert_eq!(records[1].confidence, None);
361        assert_eq!(records[1].mask.encoding, SamMaskEncoding::Lossless);
362    }
363
364    #[test]
365    fn deltas_split_anywhere_give_the_same_records() {
366        let text = format!("{LINE}\n{LINE}\n");
367        let whole = SamStreamParser::new().push(&text).unwrap();
368        for cut in [1, 17, 40, 88, text.len() - 1] {
369            let mut parser = SamStreamParser::new();
370            let mut records = parser.push(&text[..cut]).unwrap();
371            records.extend(parser.push(&text[cut..]).unwrap());
372            records.extend(parser.finish().unwrap());
373            assert_eq!(records, whole, "cut at {cut}");
374        }
375        assert_eq!(whole.len(), 2);
376    }
377
378    #[test]
379    fn malformed_lines_are_refused() {
380        for line in [
381            "<0f>",
382            "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|>",
383            "<0f>0<|box;x1=1;y1=1;x2=20;y2=2;w=10;h=10|><|mask;x=0;y=0;data=2,20,~!|>",
384            "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|><|mask;x=1;y=0;data=2,2,~!|>",
385            "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|><|mask;x=0;y=0;data=0,3,~!|>",
386            "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|><|mask;x=0;y=0;data=2,2,#!|>",
387            "<xf>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|><|mask;x=0;y=0;data=2,2,~!|>",
388            "<0f>0<|box;x1=1;y1=1;x2=2;y2=2;w=10;h=10|>junk<|mask;x=0;y=0;data=2,2,~!|>",
389        ] {
390            assert!(parse_line(line).is_err(), "{line}");
391        }
392        assert!(parse_line("").unwrap().is_empty());
393        assert!(parse_line("a note the model wrote").unwrap().is_empty());
394    }
395
396    #[test]
397    fn events_split_on_blank_lines() {
398        let mut sse = SseBuffer::default();
399        let first = sse.push(
400            "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",",
401        );
402        assert!(first.is_empty());
403        let events = sse.push("\"delta\":\"<0f>\"}\n\ndata: [DONE]\n\n");
404        assert_eq!(events.len(), 2);
405        assert_eq!(event(&events[0]).unwrap(), SamEvent::Delta("<0f>".into()));
406        assert_eq!(event(&events[1]).unwrap(), SamEvent::Other);
407        let done =
408            event(r#"{"type":"response.completed","response":{"usage":{"images_processed":1}}}"#);
409        assert_eq!(done.unwrap(), SamEvent::Completed { images: Some(1) });
410        let failed = event(r#"{"type":"response.failed","response":{"error":{"message":"boom"}}}"#);
411        assert_eq!(failed.unwrap(), SamEvent::Failed("boom".into()));
412    }
413}