1use 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
39pub const REDACTION_MARGIN: f32 = 2.0;
41
42pub const DEFAULT_PERSON_DETECTOR: &str = "rf-detr-n";
45
46pub const DEFAULT_FACE_DETECTOR: &str = "yunet-2023mar";
49
50pub const FACE_MARGIN: f32 = 0.15;
53
54pub(crate) type Loading<T> = Pin<Box<dyn Future<Output = Result<Arc<T>>> + Send>>;
56
57pub(crate) type Load<T> = Box<dyn Fn() -> Loading<T> + Send + Sync>;
59
60pub(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 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
106pub 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 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 #[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 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 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 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
236pub 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 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 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 #[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 .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 pub fn with_face_min_score(mut self, min_score: f32) -> Self {
381 self.face_min_score = min_score;
382 self
383 }
384
385 pub fn with_person_min_score(mut self, min_score: f32) -> Self {
387 self.person_min_score = min_score;
388 self
389 }
390
391 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 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
460async 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#[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#[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#[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
525pub(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
554pub(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 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}