Skip to main content

adk_vision/
redact.rs

1//! On-device redactors for the egress gate's third step (spec 3.7 §7.8).
2//!
3//! A [`Redactor`] answers in the pixels of the minimised image the gate is about to release;
4//! the gate fills each box solid black. The redactors here run any on-device backend:
5//!
6//! | Redactor | Class | Finds |
7//! |----------|-------|-------|
8//! | [`FaceRedactor`] | `faces` | Each face a face detector finds, and the whole box of each person a person detector finds no face for (spec 3.7 Q3) |
9//! | [`PersonRedactor`] | `faces` | The whole box of every person a [`Detector`] finds |
10//! | `PersonalTextRedactor` (feature `guardrail`) | `personal_text` | Words a [`DocumentReader`](crate::DocumentReader) reads that `PiiRedactor` patterns or labelled fields match |
11//!
12//! A redactor refuses a remote backend: what it is shown has not been redacted yet.
13//!
14//! Each redactor takes any on-device backend, or builds the default one from the built-in
15//! manifest: `FaceRedactor::on_device` (feature `onnx`) over YuNet with RF-DETR Nano as its
16//! person fallback, `PersonRedactor::rf_detr` (feature `onnx`) over RF-DETR Nano, and
17//! `PersonalTextRedactor::pp_ocr` (features `guardrail` and `ocr`) over PP-OCRv6. A default
18//! backend loads on the redactor's first use, its weights verified against the manifest; a
19//! load that fails — weights missing offline, a digest mismatch — fails that call, so the
20//! egress gate refuses the release rather than send the image unredacted. The one exception
21//! errs toward covering: a `FaceRedactor` whose face detector cannot load covers every person
22//! its person detector finds as the whole person.
23
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27
28use async_trait::async_trait;
29
30use crate::backend::{BackendDescriptor, Oversize};
31use crate::cx::VisionCx;
32use crate::edit::ops;
33use crate::egress::{RedactionClass, Redactor};
34use crate::error::{Result, VisionError};
35use crate::geometry::{BBox, RawRegion, RegionNormalizer, Transform};
36use crate::sent::SentImage;
37use crate::traits::{DetectQuery, Detector};
38
39/// Pixels added around each box a redactor finds, so anti-aliased edges are covered too.
40pub const REDACTION_MARGIN: f32 = 2.0;
41
42/// The built-in manifest of the person detector `PersonRedactor::rf_detr` and
43/// `FaceRedactor::on_device` load: RF-DETR Nano, full precision.
44pub const DEFAULT_PERSON_DETECTOR: &str = "rf-detr-n";
45
46/// The built-in manifest of the face detector `FaceRedactor::on_device` loads: YuNet 2023mar
47/// (MIT, OpenCV Zoo), 232 KB.
48pub const DEFAULT_FACE_DETECTOR: &str = "yunet-2023mar";
49
50/// What [`FaceRedactor`] adds on each side of a face box, as a share of the box's longer
51/// side: YuNet boxes a face from brow to chin, and the cover takes in the hair, ears and jaw.
52pub const FACE_MARGIN: f32 = 0.15;
53
54/// One load of an on-device backend.
55pub(crate) type Loading<T> = Pin<Box<dyn Future<Output = Result<Arc<T>>> + Send>>;
56
57/// Loads an on-device backend.
58pub(crate) type Load<T> = Box<dyn Fn() -> Loading<T> + Send + Sync>;
59
60/// The backend a redactor runs: given, or loaded on first use and kept.
61///
62/// A failed load is not kept, so the next call tries again: weights fetched since, or a
63/// network that came back, then serve.
64pub(crate) struct OnDevice<T: ?Sized> {
65    name: String,
66    cell: tokio::sync::OnceCell<Arc<T>>,
67    load: Load<T>,
68}
69
70impl<T: ?Sized + Send + Sync + 'static> OnDevice<T> {
71    pub(crate) fn ready(name: impl Into<String>, backend: Arc<T>) -> Self {
72        let name = name.into();
73        let missing = name.clone();
74        Self {
75            cell: tokio::sync::OnceCell::new_with(Some(backend)),
76            load: Box::new(move || {
77                let missing = missing.clone();
78                Box::pin(async move {
79                    Err(VisionError::BackendNotFound(format!("redactor backend `{missing}`")))
80                }) as Loading<T>
81            }),
82            name,
83        }
84    }
85
86    #[cfg(any(
87        test,
88        feature = "onnx",
89        feature = "onnx-dynamic",
90        all(feature = "ocr", feature = "guardrail")
91    ))]
92    pub(crate) fn lazy(name: impl Into<String>, load: Load<T>) -> Self {
93        Self { name: name.into(), cell: tokio::sync::OnceCell::new(), load }
94    }
95
96    /// The backend's id, or the manifest it loads from.
97    pub(crate) fn name(&self) -> &str {
98        &self.name
99    }
100
101    pub(crate) async fn get(&self) -> Result<Arc<T>> {
102        self.cell.get_or_try_init(|| (self.load)()).await.cloned()
103    }
104}
105
106/// Redacts faces as the whole box of every detected person.
107///
108/// `faces` redaction with a `PersonRedactor` covers each person a [`Detector`] finds —
109/// RF-DETR's COCO `person` class, or any detector given the same labels — from head to
110/// foot, for a deployment with no face detector. [`FaceRedactor`] covers faces and keeps
111/// this as its fallback. The detector runs on the device; regions it returns without a label
112/// are covered too, since a privacy step errs toward covering. On an approval card its boxes
113/// are drawn as [`RedactionClass::people`].
114///
115/// `PersonRedactor::rf_detr` (feature `onnx`) loads RF-DETR Nano from the built-in manifest
116/// ([`DEFAULT_PERSON_DETECTOR`]) on first use.
117///
118/// # Example
119///
120/// ```
121/// use std::sync::Arc;
122/// use adk_vision::{
123///     BBox, BackendDescriptor, CoordFrame, DetectQuery, Detector, Locality, PersonRedactor,
124///     RawRegion, RedactionClass, Redactor, SentImage, VisionCx,
125/// };
126///
127/// /// Finds one person at a fixed place, in the pixels it is sent.
128/// struct OnePerson(BackendDescriptor);
129///
130/// #[async_trait::async_trait]
131/// impl Detector for OnePerson {
132///     fn descriptor(&self) -> &BackendDescriptor {
133///         &self.0
134///     }
135///     async fn detect(&self, _: &VisionCx, _: &SentImage, _: &DetectQuery) -> adk_vision::Result<Vec<RawRegion>> {
136///         Ok(vec![RawRegion::boxed(BBox::new(10.0, 10.0, 30.0, 60.0), "person", 0.9)])
137///     }
138/// }
139///
140/// let detector = OnePerson(BackendDescriptor::new("people", Locality::InProcess, CoordFrame::SentPixels));
141/// let redactor = PersonRedactor::new(Arc::new(detector));
142/// assert_eq!(redactor.class(), RedactionClass::faces());
143/// ```
144pub struct PersonRedactor {
145    detector: OnDevice<dyn Detector>,
146    labels: Vec<String>,
147    min_score: f32,
148}
149
150impl std::fmt::Debug for PersonRedactor {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        f.debug_struct("PersonRedactor")
153            .field("detector", &self.detector.name())
154            .field("labels", &self.labels)
155            .field("min_score", &self.min_score)
156            .finish()
157    }
158}
159
160impl PersonRedactor {
161    /// Covers every `person` the on-device `detector` finds with a score of 0.25 or more.
162    pub fn new(detector: Arc<dyn Detector>) -> Self {
163        let name = detector.descriptor().id.to_string();
164        Self {
165            detector: OnDevice::ready(name, detector),
166            labels: vec!["person".to_string()],
167            min_score: 0.25,
168        }
169    }
170
171    /// Covers every `person` RF-DETR Nano finds with a score of 0.25 or more: the built-in
172    /// [`DEFAULT_PERSON_DETECTOR`] manifest, fetched through `fetcher` and verified against
173    /// its SHA-256 on the redactor's first use (feature `onnx`).
174    ///
175    /// Nothing loads here. When the weights cannot be had — `HF_HUB_OFFLINE` with an empty
176    /// cache, a digest mismatch — `find` fails, and the egress gate refuses the release.
177    ///
178    /// # Example
179    ///
180    /// ```
181    /// use std::sync::Arc;
182    /// use adk_vision::{
183    ///     FetchConfig, InMemoryAcceptanceStore, ModelFetcher, PersonRedactor, RedactionClass,
184    ///     Redactor,
185    /// };
186    ///
187    /// let fetcher =
188    ///     ModelFetcher::new(FetchConfig::from_env(), Arc::new(InMemoryAcceptanceStore::new()));
189    /// let redactor = PersonRedactor::rf_detr(fetcher);
190    /// assert_eq!(redactor.class(), RedactionClass::faces());
191    /// ```
192    #[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
193    pub fn rf_detr(fetcher: crate::ModelFetcher) -> Self {
194        Self {
195            detector: builtin_rf_detr(fetcher),
196            labels: vec!["person".to_string()],
197            min_score: 0.25,
198        }
199    }
200
201    /// Covers these labels instead.
202    pub fn with_labels(mut self, labels: impl IntoIterator<Item = impl Into<String>>) -> Self {
203        self.labels = labels.into_iter().map(Into::into).collect();
204        self
205    }
206
207    /// Covers detections scoring at least `min_score`.
208    pub fn with_min_score(mut self, min_score: f32) -> Self {
209        self.min_score = min_score;
210        self
211    }
212}
213
214#[async_trait]
215impl Redactor for PersonRedactor {
216    fn class(&self) -> RedactionClass {
217        RedactionClass::faces()
218    }
219
220    async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>> {
221        let detector = self.detector.get().await?;
222        detect_boxes(cx, detector.as_ref(), image, &self.labels, self.min_score).await
223    }
224
225    /// Every box as `people`: each covers a face as the whole person.
226    async fn find_classified(
227        &self,
228        cx: &VisionCx,
229        image: &SentImage,
230    ) -> Result<Vec<(RedactionClass, BBox)>> {
231        let boxes = self.find(cx, image).await?;
232        Ok(boxes.into_iter().map(|bbox| (RedactionClass::people(), bbox)).collect())
233    }
234}
235
236/// Covers faces: each face a face [`Detector`] finds, widened by [`FACE_MARGIN`], and — with
237/// a person fallback — the whole box of each person it finds no face for (spec 3.7 Q3).
238///
239/// A person seen from behind, a face turned away or too large or small for the face
240/// detector is still covered, as the whole person; a person whose face is found keeps the
241/// rest of the picture, so a close desk frame is not blanked by one person's box. A face
242/// counts as a person's when its centre lies inside the person's box.
243///
244/// Both detectors run on the device. A face detector that cannot load (its weights missing
245/// offline, a digest mismatch) makes the redactor cover every detected person whole, with a
246/// warning; with no person fallback, or a fallback that cannot load either, the call fails
247/// and the egress gate refuses the release. On an approval card faces are drawn as `faces`
248/// and whole persons as [`RedactionClass::people`].
249///
250/// `FaceRedactor::on_device` (feature `onnx`) is the default: YuNet
251/// ([`DEFAULT_FACE_DETECTOR`]) with RF-DETR Nano ([`DEFAULT_PERSON_DETECTOR`]) as the person
252/// fallback, each loaded on first use.
253///
254/// # Example
255///
256/// ```
257/// use std::sync::Arc;
258/// use adk_vision::{
259///     BBox, BackendDescriptor, CoordFrame, DetectQuery, Detector, FaceRedactor, Locality,
260///     RawRegion, RedactionClass, Redactor, SentImage, VisionCx,
261/// };
262///
263/// /// Finds one region of a fixed label, in the pixels it is sent.
264/// struct Fixed(BackendDescriptor, &'static str, BBox);
265///
266/// #[async_trait::async_trait]
267/// impl Detector for Fixed {
268///     fn descriptor(&self) -> &BackendDescriptor {
269///         &self.0
270///     }
271///     async fn detect(&self, _: &VisionCx, _: &SentImage, _: &DetectQuery) -> adk_vision::Result<Vec<RawRegion>> {
272///         Ok(vec![RawRegion::boxed(self.2, self.1, 0.9)])
273///     }
274/// }
275///
276/// let local = |id| BackendDescriptor::new(id, Locality::InProcess, CoordFrame::SentPixels);
277/// let faces = Fixed(local("faces"), "face", BBox::new(40.0, 20.0, 60.0, 44.0));
278/// let people = Fixed(local("people"), "person", BBox::new(20.0, 10.0, 80.0, 120.0));
279/// let redactor = FaceRedactor::new(Arc::new(faces)).with_person_fallback(Arc::new(people));
280/// assert_eq!(redactor.class(), RedactionClass::faces());
281/// ```
282pub struct FaceRedactor {
283    faces: OnDevice<dyn Detector>,
284    face_labels: Vec<String>,
285    face_min_score: f32,
286    people: Option<OnDevice<dyn Detector>>,
287    person_labels: Vec<String>,
288    person_min_score: f32,
289    margin: f32,
290}
291
292impl std::fmt::Debug for FaceRedactor {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        f.debug_struct("FaceRedactor")
295            .field("faces", &self.faces.name())
296            .field("face_min_score", &self.face_min_score)
297            .field("people", &self.people.as_ref().map(OnDevice::name))
298            .field("person_min_score", &self.person_min_score)
299            .field("margin", &self.margin)
300            .finish()
301    }
302}
303
304impl FaceRedactor {
305    /// Covers every `face` the on-device `faces` detector finds with a score of 0.5 or more,
306    /// and nothing else: add [`with_person_fallback`](Self::with_person_fallback) to cover
307    /// people whose faces it misses.
308    pub fn new(faces: Arc<dyn Detector>) -> Self {
309        let name = faces.descriptor().id.to_string();
310        Self {
311            faces: OnDevice::ready(name, faces),
312            face_labels: vec!["face".to_string()],
313            face_min_score: 0.5,
314            people: None,
315            person_labels: vec!["person".to_string()],
316            person_min_score: 0.25,
317            margin: FACE_MARGIN,
318        }
319    }
320
321    /// Covers, as the whole person, each `person` the on-device `people` detector finds with
322    /// a score of 0.25 or more and no face inside.
323    pub fn with_person_fallback(mut self, people: Arc<dyn Detector>) -> Self {
324        let name = people.descriptor().id.to_string();
325        self.people = Some(OnDevice::ready(name, people));
326        self
327    }
328
329    /// YuNet for faces and RF-DETR Nano for the person fallback, from the built-in
330    /// [`DEFAULT_FACE_DETECTOR`] and [`DEFAULT_PERSON_DETECTOR`] manifests, fetched through
331    /// `fetcher` and verified against their SHA-256 on the redactor's first use (feature
332    /// `onnx`).
333    ///
334    /// Nothing loads here. When YuNet cannot be had the redactor covers whole persons; when
335    /// RF-DETR cannot be had `find` fails, and the egress gate refuses the release.
336    ///
337    /// # Example
338    ///
339    /// ```
340    /// use std::sync::Arc;
341    /// use adk_vision::{
342    ///     FaceRedactor, FetchConfig, InMemoryAcceptanceStore, ModelFetcher, RedactionClass,
343    ///     Redactor,
344    /// };
345    ///
346    /// let fetcher =
347    ///     ModelFetcher::new(FetchConfig::from_env(), Arc::new(InMemoryAcceptanceStore::new()));
348    /// let redactor = FaceRedactor::on_device(fetcher);
349    /// assert_eq!(redactor.class(), RedactionClass::faces());
350    /// ```
351    #[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
352    pub fn on_device(fetcher: crate::ModelFetcher) -> Self {
353        let load_faces = fetcher.clone();
354        let load: Load<dyn Detector> = Box::new(move || {
355            let fetcher = load_faces.clone();
356            Box::pin(async move {
357                let model = fetch_builtin(&fetcher, DEFAULT_FACE_DETECTOR).await?;
358                let detector = load_blocking(DEFAULT_FACE_DETECTOR, move || {
359                    crate::onnx::YuNet::new(&model, &crate::onnx::OnnxOptions::default())
360                })
361                .await?
362                // The redactor's own score filter decides; the detector reports more.
363                .with_threshold(0.3);
364                tracing::info!(vision.backend = DEFAULT_FACE_DETECTOR, "face redactor loaded");
365                Ok(Arc::new(detector) as Arc<dyn Detector>)
366            }) as Loading<dyn Detector>
367        });
368        Self {
369            faces: OnDevice::lazy(DEFAULT_FACE_DETECTOR, load),
370            face_labels: vec!["face".to_string()],
371            face_min_score: 0.5,
372            people: Some(builtin_rf_detr(fetcher)),
373            person_labels: vec!["person".to_string()],
374            person_min_score: 0.25,
375            margin: FACE_MARGIN,
376        }
377    }
378
379    /// Covers faces scoring at least `min_score` (0.5 by default).
380    pub fn with_face_min_score(mut self, min_score: f32) -> Self {
381        self.face_min_score = min_score;
382        self
383    }
384
385    /// Falls back to people scoring at least `min_score` (0.25 by default).
386    pub fn with_person_min_score(mut self, min_score: f32) -> Self {
387        self.person_min_score = min_score;
388        self
389    }
390
391    /// Widens each face box by `margin` of its longer side on each side ([`FACE_MARGIN`] by
392    /// default).
393    pub fn with_margin(mut self, margin: f32) -> Self {
394        self.margin = margin.max(0.0);
395        self
396    }
397}
398
399#[async_trait]
400impl Redactor for FaceRedactor {
401    fn class(&self) -> RedactionClass {
402        RedactionClass::faces()
403    }
404
405    async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>> {
406        Ok(self.find_classified(cx, image).await?.into_iter().map(|(_, bbox)| bbox).collect())
407    }
408
409    /// Faces as `faces`, the whole persons it falls back to as `people`.
410    async fn find_classified(
411        &self,
412        cx: &VisionCx,
413        image: &SentImage,
414    ) -> Result<Vec<(RedactionClass, BBox)>> {
415        let faces = match self.faces.get().await {
416            Ok(detector) => Some(
417                detect_boxes(cx, detector.as_ref(), image, &self.face_labels, self.face_min_score)
418                    .await?,
419            ),
420            Err(err) if self.people.is_some() => {
421                tracing::warn!(
422                    vision.backend = self.faces.name(),
423                    error = %err,
424                    "face detector unavailable, covering every detected person whole"
425                );
426                None
427            }
428            Err(err) => return Err(err),
429        };
430        let people = match &self.people {
431            Some(people) => {
432                let detector = people.get().await?;
433                detect_boxes(
434                    cx,
435                    detector.as_ref(),
436                    image,
437                    &self.person_labels,
438                    self.person_min_score,
439                )
440                .await?
441            }
442            None => Vec::new(),
443        };
444        let (width, height) = image.size();
445        let mut found = Vec::new();
446        for face in faces.iter().flatten() {
447            let margin = self.margin * face.width().max(face.height());
448            found.push((RedactionClass::faces(), face.expanded(margin).clamped(width, height)));
449        }
450        for person in people {
451            let has_face = faces.iter().flatten().any(|face| person.contains(face.center()));
452            if !has_face {
453                found.push((RedactionClass::people(), person));
454            }
455        }
456        Ok(found)
457    }
458}
459
460/// The boxes of `labels` scoring at least `min_score` that an on-device `detector` finds in
461/// `image`, in its pixels, widened by [`REDACTION_MARGIN`]. A region without a label or a
462/// score is kept, since a privacy step errs toward covering.
463async fn detect_boxes(
464    cx: &VisionCx,
465    detector: &dyn Detector,
466    image: &SentImage,
467    labels: &[String],
468    min_score: f32,
469) -> Result<Vec<BBox>> {
470    let descriptor = detector.descriptor();
471    let fitted = fit_on_device(descriptor, image)?;
472    let raw = detector.detect(cx, &fitted, &DetectQuery::Classes(labels.to_vec())).await?;
473    let wanted = |region: &RawRegion| {
474        let labelled = region
475            .label
476            .as_ref()
477            .is_none_or(|label| labels.iter().any(|wanted| wanted.eq_ignore_ascii_case(label)));
478        labelled && region.score.is_none_or(|score| score >= min_score)
479    };
480    let raw: Vec<RawRegion> = raw.into_iter().filter(wanted).collect();
481    to_image_boxes(descriptor, &fitted, image, raw)
482}
483
484/// RF-DETR Nano from the built-in manifest, loaded on first use with a threshold low enough
485/// for the redactor's own score filter to decide.
486#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
487fn builtin_rf_detr(fetcher: crate::ModelFetcher) -> OnDevice<dyn Detector> {
488    let load: Load<dyn Detector> = Box::new(move || {
489        let fetcher = fetcher.clone();
490        Box::pin(async move {
491            let model = fetch_builtin(&fetcher, DEFAULT_PERSON_DETECTOR).await?;
492            let detector = load_blocking(DEFAULT_PERSON_DETECTOR, move || {
493                crate::onnx::RfDetr::new(&model, &crate::onnx::OnnxOptions::default())
494            })
495            .await?
496            .with_threshold(0.05);
497            tracing::info!(vision.backend = DEFAULT_PERSON_DETECTOR, "person redactor loaded");
498            Ok(Arc::new(detector) as Arc<dyn Detector>)
499        }) as Loading<dyn Detector>
500    });
501    OnDevice::lazy(DEFAULT_PERSON_DETECTOR, load)
502}
503
504/// Fetches and verifies the built-in manifest `id`.
505#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
506async fn fetch_builtin(fetcher: &crate::ModelFetcher, id: &str) -> Result<crate::VerifiedModel> {
507    let manifest = crate::ManifestSet::builtin()?.get(id).cloned().ok_or_else(|| {
508        VisionError::Manifest { id: id.into(), reason: "not in the built-in manifest".into() }
509    })?;
510    fetcher.fetch(&manifest).await
511}
512
513/// Builds a backend on a blocking thread, since onnxruntime's session load blocks.
514#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
515async fn load_blocking<T: Send + 'static>(
516    id: &str,
517    build: impl FnOnce() -> Result<T> + Send + 'static,
518) -> Result<T> {
519    tokio::task::spawn_blocking(build).await.map_err(|e| VisionError::Backend {
520        backend: id.into(),
521        message: format!("the load task failed: {e}"),
522    })?
523}
524
525/// `image` fitted to an on-device backend's input limits, keeping the transform chain from
526/// the source, so the backend's answer maps back.
527pub(crate) fn fit_on_device(
528    descriptor: &BackendDescriptor,
529    image: &SentImage,
530) -> Result<SentImage> {
531    if descriptor.locality.is_remote() {
532        return Err(VisionError::InvalidInput(format!(
533            "backend `{}` is remote; a redactor runs on the device, before anything is released",
534            descriptor.id
535        )));
536    }
537    let Some((width, height)) = descriptor.limits.fit(image.size()) else {
538        return Ok(image.clone());
539    };
540    if descriptor.limits.oversize == Oversize::Refuse {
541        let (w, h) = image.size();
542        return Err(VisionError::InputTooLarge {
543            backend: descriptor.id.to_string(),
544            limit: descriptor.limits.describe(),
545            actual: format!("{w}x{h}"),
546        });
547    }
548    let mut chain = image.chain().clone();
549    chain.push(Transform::Resize { width, height })?;
550    let pixels = ops::resize(image.pixels(), width, height);
551    Ok(SentImage::new(image.source(), Arc::new(pixels), chain))
552}
553
554/// Maps a backend's raw regions on `fitted` to boxes in `image`'s pixels, widened by
555/// [`REDACTION_MARGIN`].
556pub(crate) fn to_image_boxes(
557    descriptor: &BackendDescriptor,
558    fitted: &SentImage,
559    image: &SentImage,
560    raw: Vec<RawRegion>,
561) -> Result<Vec<BBox>> {
562    let normalizer = RegionNormalizer::new(
563        fitted.source(),
564        fitted.chain().clone(),
565        descriptor.frame,
566        descriptor.id.clone(),
567    );
568    let (width, height) = image.size();
569    let mut boxes = Vec::new();
570    for region in normalizer.regions(raw)? {
571        if let Some(bbox) = region.shape.bbox() {
572            let target = image.chain().bbox_to_target(&bbox);
573            boxes.push(target.expanded(REDACTION_MARGIN).clamped(width, height));
574        }
575    }
576    Ok(boxes)
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use crate::backend::{BackendDescriptor, Locality};
583    use crate::digest::Digest;
584    use crate::geometry::{CoordFrame, TransformChain};
585    use crate::media::DecodedImage;
586
587    /// Finds one region of a fixed label wherever it is asked.
588    struct Fixed(BackendDescriptor, &'static str, BBox);
589
590    #[async_trait]
591    impl Detector for Fixed {
592        fn descriptor(&self) -> &BackendDescriptor {
593            &self.0
594        }
595
596        async fn detect(
597            &self,
598            _: &VisionCx,
599            _: &SentImage,
600            _: &DetectQuery,
601        ) -> Result<Vec<RawRegion>> {
602            Ok(vec![RawRegion::boxed(self.2, self.1, 0.9)])
603        }
604    }
605
606    fn local(id: &str) -> BackendDescriptor {
607        BackendDescriptor::new(id, Locality::InProcess, CoordFrame::SentPixels)
608    }
609
610    fn missing(id: &'static str) -> OnDevice<dyn Detector> {
611        OnDevice::lazy(
612            id,
613            Box::new(move || {
614                Box::pin(async move {
615                    Err(VisionError::Offline { model: id.into(), file: "model.onnx".into() })
616                }) as Loading<dyn Detector>
617            }),
618        )
619    }
620
621    fn redactor(
622        faces: OnDevice<dyn Detector>,
623        people: Option<OnDevice<dyn Detector>>,
624    ) -> FaceRedactor {
625        FaceRedactor {
626            faces,
627            face_labels: vec!["face".into()],
628            face_min_score: 0.5,
629            people,
630            person_labels: vec!["person".into()],
631            person_min_score: 0.25,
632            margin: FACE_MARGIN,
633        }
634    }
635
636    fn image() -> SentImage {
637        SentImage::new(
638            Digest::of(b"frame"),
639            Arc::new(DecodedImage::filled(200, 200, [120, 120, 120, 255])),
640            TransformChain::new(200, 200),
641        )
642    }
643
644    #[tokio::test]
645    async fn a_face_detector_that_cannot_load_covers_every_person_whole() {
646        let person = BBox::new(20.0, 10.0, 120.0, 190.0);
647        let people: Arc<dyn Detector> = Arc::new(Fixed(local("people"), "person", person));
648        let redactor = redactor(missing("yunet-2023mar"), Some(OnDevice::ready("people", people)));
649
650        let found = redactor.find_classified(&VisionCx::new(), &image()).await.unwrap();
651
652        assert_eq!(found, vec![(RedactionClass::people(), person.expanded(REDACTION_MARGIN))]);
653    }
654
655    #[tokio::test]
656    async fn without_a_person_fallback_a_missing_face_detector_refuses() {
657        let err = redactor(missing("yunet-2023mar"), None)
658            .find_classified(&VisionCx::new(), &image())
659            .await
660            .unwrap_err();
661        assert!(
662            matches!(&err, VisionError::Offline { model, .. } if model == "yunet-2023mar"),
663            "{err}"
664        );
665
666        let faces: Arc<dyn Detector> =
667            Arc::new(Fixed(local("faces"), "face", BBox::new(40.0, 40.0, 60.0, 64.0)));
668        let err = redactor(OnDevice::ready("faces", faces), Some(missing("rf-detr-n")))
669            .find_classified(&VisionCx::new(), &image())
670            .await
671            .unwrap_err();
672        assert!(
673            matches!(&err, VisionError::Offline { model, .. } if model == "rf-detr-n"),
674            "{err}"
675        );
676    }
677}