Skip to main content

sightloom_host/
config.rs

1//! Model specs and host bundle configuration.
2
3use crate::device::DevicePreference;
4use crate::preprocess::PreprocessConfig;
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8/// High-level model task in the host package.
9#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum ModelTask {
12    /// Face detector.
13    FaceDetect,
14    /// Person / body detector.
15    PersonDetect,
16    /// Face embedding (recognition).
17    FaceEmbed,
18    /// Person re-identification embedding.
19    PersonReId,
20    /// Instance / semantic segmentation (masks for host → `VisionIndex`).
21    Segmentation,
22}
23
24impl ModelTask {
25    /// Stable string id.
26    #[must_use]
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::FaceDetect => "face_detect",
30            Self::PersonDetect => "person_detect",
31            Self::FaceEmbed => "face_embed",
32            Self::PersonReId => "person_reid",
33            Self::Segmentation => "segmentation",
34        }
35    }
36}
37
38/// One model the host may load (weights **not** shipped in `SightLoom` core).
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40pub struct ModelSpec {
41    /// Stable id (`"person_yolo_v8n"`, `"osnet_x1_0"`, …).
42    pub id: String,
43    /// Task this model performs.
44    pub task: ModelTask,
45    /// Optional remote URI for download (https / s3 / …). Host fetcher only.
46    #[serde(default)]
47    pub uri: Option<String>,
48    /// Local path when already on disk.
49    #[serde(default)]
50    pub local_path: Option<PathBuf>,
51    /// Expected embedding length (`0` for detectors / segmenters).
52    #[serde(default)]
53    pub embedding_dim: usize,
54    /// Preprocess knobs.
55    #[serde(default)]
56    pub preprocess: PreprocessConfig,
57    /// Device preference.
58    #[serde(default)]
59    pub device: DevicePreference,
60    /// Optional model format hint (`"onnx"`, `"torchscript"`, `"openvino"`, …).
61    #[serde(default)]
62    pub format: Option<String>,
63    /// Optional lowercase hex SHA-256 of the weight file (integrity check).
64    #[serde(default)]
65    pub sha256: Option<String>,
66}
67
68impl ModelSpec {
69    /// Detector-oriented constructor.
70    #[must_use]
71    pub fn detector(id: impl Into<String>, task: ModelTask) -> Self {
72        Self {
73            id: id.into(),
74            task,
75            uri: None,
76            local_path: None,
77            embedding_dim: 0,
78            preprocess: PreprocessConfig::yolo_detect(640, 640),
79            device: DevicePreference::Auto,
80            format: Some("onnx".into()),
81            sha256: None,
82        }
83    }
84
85    /// Embedding-oriented constructor.
86    #[must_use]
87    pub fn embedder(id: impl Into<String>, task: ModelTask, dim: usize) -> Self {
88        Self {
89            id: id.into(),
90            task,
91            uri: None,
92            local_path: None,
93            embedding_dim: dim,
94            preprocess: PreprocessConfig::imagenet_like(256, 128),
95            device: DevicePreference::Auto,
96            format: Some("onnx".into()),
97            sha256: None,
98        }
99    }
100}
101
102/// Full host bundle: which models participate in photo search / ingest.
103#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
104pub struct HostBundleConfig {
105    /// Person detector (ingest path).
106    #[serde(default)]
107    pub person_detect: Option<ModelSpec>,
108    /// Face detector (optional crop path).
109    #[serde(default)]
110    pub face_detect: Option<ModelSpec>,
111    /// Person re-id embedder.
112    #[serde(default)]
113    pub person_reid: Option<ModelSpec>,
114    /// Face embedder.
115    #[serde(default)]
116    pub face_embed: Option<ModelSpec>,
117    /// Segmentation model (optional masks).
118    #[serde(default)]
119    pub segmentation: Option<ModelSpec>,
120    /// Root directory for downloaded / cached weights.
121    #[serde(default = "default_cache_dir")]
122    pub cache_dir: PathBuf,
123    /// When true, missing local models are an error (no silent fake).
124    #[serde(default)]
125    pub require_real_weights: bool,
126}
127
128fn default_cache_dir() -> PathBuf {
129    PathBuf::from(".sightloom-models")
130}
131
132impl Default for HostBundleConfig {
133    fn default() -> Self {
134        Self {
135            person_detect: Some(ModelSpec::detector(
136                "ref_person_detect",
137                ModelTask::PersonDetect,
138            )),
139            face_detect: Some(ModelSpec::detector(
140                "ref_face_detect",
141                ModelTask::FaceDetect,
142            )),
143            person_reid: Some(ModelSpec::embedder(
144                "ref_person_reid",
145                ModelTask::PersonReId,
146                128,
147            )),
148            face_embed: Some(ModelSpec::embedder(
149                "ref_face_embed",
150                ModelTask::FaceEmbed,
151                128,
152            )),
153            segmentation: None,
154            cache_dir: default_cache_dir(),
155            require_real_weights: false,
156        }
157    }
158}
159
160impl HostBundleConfig {
161    /// Parses JSON host config.
162    ///
163    /// # Errors
164    ///
165    /// Serde errors.
166    pub fn from_json(text: &str) -> Result<Self, serde_json::Error> {
167        serde_json::from_str(text)
168    }
169
170    /// Serializes to pretty JSON.
171    ///
172    /// # Errors
173    ///
174    /// Serde errors.
175    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
176        serde_json::to_string_pretty(self)
177    }
178
179    /// All configured specs in a stable order.
180    #[must_use]
181    pub fn all_specs(&self) -> Vec<&ModelSpec> {
182        [
183            self.person_detect.as_ref(),
184            self.face_detect.as_ref(),
185            self.person_reid.as_ref(),
186            self.face_embed.as_ref(),
187            self.segmentation.as_ref(),
188        ]
189        .into_iter()
190        .flatten()
191        .collect()
192    }
193}