adk_vision/mask_decoder.rs
1//! Which decoder turns `sam-3.1` mask payloads into rasters, as configuration that parses in
2//! every build, so `.adk/vision.toml` reads the same with or without the `sam` feature.
3
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8/// The built-in manifest entry whose licence, the SAM License, covers the ported codec
9/// ([`MaskDecoderChoice::Licensed`]). `adk-rust vision models accept sam-mask-codec`
10/// records a person's acceptance of it.
11pub const SAM_MASK_CODEC_MANIFEST: &str = "sam-mask-codec";
12
13/// How long an external decoder may take for one answer's masks, unless configured.
14pub const DEFAULT_MASK_DECODER_TIMEOUT_SECS: u64 = 60;
15
16fn default_timeout_secs() -> u64 {
17 DEFAULT_MASK_DECODER_TIMEOUT_SECS
18}
19
20/// Which decoder a `SamSegmenter` uses for `sam-3.1` masks.
21///
22/// Meta's mask payloads are base85 text around an arithmetic-coded body whose model only
23/// Meta's `@meta-sam/parser` defines, under the SAM License. The Apache-2.0 crates hold no
24/// SAM-licensed code, so masks come through one of three choices:
25///
26/// | Choice | Each object is | Needs |
27/// |--------|----------------|-------|
28/// | `None` (`boxes`, the default) | Its box in source pixels | Nothing |
29/// | `External` | Its mask, decoded by a program you installed | The program; it reads mask JSON on standard input and writes base64 rasters |
30/// | `Licensed` | Its mask, decoded in this process by the port of Meta's codec | Feature `sam-codec` and a person's recorded acceptance of the SAM License |
31///
32/// In `.adk/vision.toml` it is the `[sam.masks]` table, keyed by `decoder`.
33///
34/// # Example
35///
36/// ```
37/// use adk_vision::{MaskDecoderChoice, VisionConfig};
38///
39/// let config = VisionConfig::from_toml_str(r#"
40/// [sam.masks]
41/// decoder = "external"
42/// program = "/opt/sam/bin/sam-mask-decode"
43/// args = ["--json"]
44/// timeout_secs = 30
45/// "#).unwrap();
46/// assert_eq!(
47/// config.sam.masks,
48/// MaskDecoderChoice::External {
49/// program: "/opt/sam/bin/sam-mask-decode".into(),
50/// args: vec!["--json".into()],
51/// timeout_secs: 30,
52/// }
53/// );
54/// let licensed = VisionConfig::from_toml_str("[sam.masks]\ndecoder = \"licensed\"").unwrap();
55/// assert_eq!(licensed.sam.masks, MaskDecoderChoice::Licensed);
56/// assert_eq!(VisionConfig::default().sam.masks, MaskDecoderChoice::None);
57/// ```
58#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(tag = "decoder", rename_all = "snake_case", deny_unknown_fields)]
60pub enum MaskDecoderChoice {
61 /// No decoder: each object is its box in source pixels.
62 #[default]
63 #[serde(rename = "boxes", alias = "none")]
64 None,
65 /// A program the user installed, such as a wrapper around Meta's parser.
66 ///
67 /// It is started once per answer with `args`, reads a JSON array of
68 /// `{"encoding", "width", "height", "payload"}` on standard input and writes a JSON array
69 /// holding one base64 string per mask: `height × width` bytes, row-major, nonzero for a
70 /// set pixel. It is ended after `timeout_secs`.
71 External {
72 /// The program: a path, or a name looked up on `PATH`.
73 program: PathBuf,
74 /// Arguments passed before anything else.
75 #[serde(default)]
76 args: Vec<String>,
77 /// Seconds one answer's masks may take.
78 #[serde(default = "default_timeout_secs")]
79 timeout_secs: u64,
80 },
81 /// The Rust port of Meta's codec (`adk-vision-sam-codec`, under the SAM License), in
82 /// this process: feature `sam-codec`, and a person's recorded acceptance of the
83 /// [`SAM_MASK_CODEC_MANIFEST`] entry's licence.
84 Licensed,
85}
86
87impl MaskDecoderChoice {
88 /// An external program with arguments and the default timeout.
89 ///
90 /// # Example
91 ///
92 /// ```
93 /// use adk_vision::MaskDecoderChoice;
94 ///
95 /// let choice = MaskDecoderChoice::external("sam-mask-decode", ["--json"]);
96 /// assert_eq!(choice.name(), "external");
97 /// ```
98 pub fn external<A: Into<String>>(
99 program: impl Into<PathBuf>,
100 args: impl IntoIterator<Item = A>,
101 ) -> Self {
102 Self::External {
103 program: program.into(),
104 args: args.into_iter().map(Into::into).collect(),
105 timeout_secs: DEFAULT_MASK_DECODER_TIMEOUT_SECS,
106 }
107 }
108
109 /// The choice's configuration word: `boxes`, `external` or `licensed`.
110 pub fn name(&self) -> &'static str {
111 match self {
112 Self::None => "boxes",
113 Self::External { .. } => "external",
114 Self::Licensed => "licensed",
115 }
116 }
117}
118
119/// The `[sam]` table of `.adk/vision.toml`.
120#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct SamSettings {
123 /// The `[sam.masks]` table: which decoder turns mask payloads into rasters.
124 #[serde(default)]
125 pub masks: MaskDecoderChoice,
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131
132 #[test]
133 fn unknown_keys_and_decoders_are_refused() {
134 let parse = |text: &str| toml::from_str::<SamSettings>(text);
135 assert_eq!(parse("").unwrap().masks, MaskDecoderChoice::None);
136 assert_eq!(parse("[masks]\ndecoder = \"none\"").unwrap().masks, MaskDecoderChoice::None);
137 assert!(parse("[masks]\ndecoder = \"codec\"").is_err());
138 assert!(parse("[masks]\nprogram = \"x\"").is_err());
139 assert!(parse("decoder = \"boxes\"").is_err());
140 assert!(parse("[masks]\ndecoder = \"external\"\nprogram = \"d\"\ntimeout = 5").is_err());
141 let external = parse("[masks]\ndecoder = \"external\"\nprogram = \"d\"").unwrap();
142 assert_eq!(external.masks, MaskDecoderChoice::external("d", Vec::<String>::new()));
143 }
144}