use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use async_trait::async_trait;
use crate::backend::{BackendDescriptor, Oversize};
use crate::cx::VisionCx;
use crate::edit::ops;
use crate::egress::{RedactionClass, Redactor};
use crate::error::{Result, VisionError};
use crate::geometry::{BBox, RawRegion, RegionNormalizer, Transform};
use crate::sent::SentImage;
use crate::traits::{DetectQuery, Detector};
pub const REDACTION_MARGIN: f32 = 2.0;
pub const DEFAULT_PERSON_DETECTOR: &str = "rf-detr-n";
pub const DEFAULT_FACE_DETECTOR: &str = "yunet-2023mar";
pub const FACE_MARGIN: f32 = 0.15;
pub(crate) type Loading<T> = Pin<Box<dyn Future<Output = Result<Arc<T>>> + Send>>;
pub(crate) type Load<T> = Box<dyn Fn() -> Loading<T> + Send + Sync>;
pub(crate) struct OnDevice<T: ?Sized> {
name: String,
cell: tokio::sync::OnceCell<Arc<T>>,
load: Load<T>,
}
impl<T: ?Sized + Send + Sync + 'static> OnDevice<T> {
pub(crate) fn ready(name: impl Into<String>, backend: Arc<T>) -> Self {
let name = name.into();
let missing = name.clone();
Self {
cell: tokio::sync::OnceCell::new_with(Some(backend)),
load: Box::new(move || {
let missing = missing.clone();
Box::pin(async move {
Err(VisionError::BackendNotFound(format!("redactor backend `{missing}`")))
}) as Loading<T>
}),
name,
}
}
#[cfg(any(
test,
feature = "onnx",
feature = "onnx-dynamic",
all(feature = "ocr", feature = "guardrail")
))]
pub(crate) fn lazy(name: impl Into<String>, load: Load<T>) -> Self {
Self { name: name.into(), cell: tokio::sync::OnceCell::new(), load }
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) async fn get(&self) -> Result<Arc<T>> {
self.cell.get_or_try_init(|| (self.load)()).await.cloned()
}
}
pub struct PersonRedactor {
detector: OnDevice<dyn Detector>,
labels: Vec<String>,
min_score: f32,
}
impl std::fmt::Debug for PersonRedactor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PersonRedactor")
.field("detector", &self.detector.name())
.field("labels", &self.labels)
.field("min_score", &self.min_score)
.finish()
}
}
impl PersonRedactor {
pub fn new(detector: Arc<dyn Detector>) -> Self {
let name = detector.descriptor().id.to_string();
Self {
detector: OnDevice::ready(name, detector),
labels: vec!["person".to_string()],
min_score: 0.25,
}
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
pub fn rf_detr(fetcher: crate::ModelFetcher) -> Self {
Self {
detector: builtin_rf_detr(fetcher),
labels: vec!["person".to_string()],
min_score: 0.25,
}
}
pub fn with_labels(mut self, labels: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.labels = labels.into_iter().map(Into::into).collect();
self
}
pub fn with_min_score(mut self, min_score: f32) -> Self {
self.min_score = min_score;
self
}
}
#[async_trait]
impl Redactor for PersonRedactor {
fn class(&self) -> RedactionClass {
RedactionClass::faces()
}
async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>> {
let detector = self.detector.get().await?;
detect_boxes(cx, detector.as_ref(), image, &self.labels, self.min_score).await
}
async fn find_classified(
&self,
cx: &VisionCx,
image: &SentImage,
) -> Result<Vec<(RedactionClass, BBox)>> {
let boxes = self.find(cx, image).await?;
Ok(boxes.into_iter().map(|bbox| (RedactionClass::people(), bbox)).collect())
}
}
pub struct FaceRedactor {
faces: OnDevice<dyn Detector>,
face_labels: Vec<String>,
face_min_score: f32,
people: Option<OnDevice<dyn Detector>>,
person_labels: Vec<String>,
person_min_score: f32,
margin: f32,
}
impl std::fmt::Debug for FaceRedactor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FaceRedactor")
.field("faces", &self.faces.name())
.field("face_min_score", &self.face_min_score)
.field("people", &self.people.as_ref().map(OnDevice::name))
.field("person_min_score", &self.person_min_score)
.field("margin", &self.margin)
.finish()
}
}
impl FaceRedactor {
pub fn new(faces: Arc<dyn Detector>) -> Self {
let name = faces.descriptor().id.to_string();
Self {
faces: OnDevice::ready(name, faces),
face_labels: vec!["face".to_string()],
face_min_score: 0.5,
people: None,
person_labels: vec!["person".to_string()],
person_min_score: 0.25,
margin: FACE_MARGIN,
}
}
pub fn with_person_fallback(mut self, people: Arc<dyn Detector>) -> Self {
let name = people.descriptor().id.to_string();
self.people = Some(OnDevice::ready(name, people));
self
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
pub fn on_device(fetcher: crate::ModelFetcher) -> Self {
let load_faces = fetcher.clone();
let load: Load<dyn Detector> = Box::new(move || {
let fetcher = load_faces.clone();
Box::pin(async move {
let model = fetch_builtin(&fetcher, DEFAULT_FACE_DETECTOR).await?;
let detector = load_blocking(DEFAULT_FACE_DETECTOR, move || {
crate::onnx::YuNet::new(&model, &crate::onnx::OnnxOptions::default())
})
.await?
.with_threshold(0.3);
tracing::info!(vision.backend = DEFAULT_FACE_DETECTOR, "face redactor loaded");
Ok(Arc::new(detector) as Arc<dyn Detector>)
}) as Loading<dyn Detector>
});
Self {
faces: OnDevice::lazy(DEFAULT_FACE_DETECTOR, load),
face_labels: vec!["face".to_string()],
face_min_score: 0.5,
people: Some(builtin_rf_detr(fetcher)),
person_labels: vec!["person".to_string()],
person_min_score: 0.25,
margin: FACE_MARGIN,
}
}
pub fn with_face_min_score(mut self, min_score: f32) -> Self {
self.face_min_score = min_score;
self
}
pub fn with_person_min_score(mut self, min_score: f32) -> Self {
self.person_min_score = min_score;
self
}
pub fn with_margin(mut self, margin: f32) -> Self {
self.margin = margin.max(0.0);
self
}
}
#[async_trait]
impl Redactor for FaceRedactor {
fn class(&self) -> RedactionClass {
RedactionClass::faces()
}
async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>> {
Ok(self.find_classified(cx, image).await?.into_iter().map(|(_, bbox)| bbox).collect())
}
async fn find_classified(
&self,
cx: &VisionCx,
image: &SentImage,
) -> Result<Vec<(RedactionClass, BBox)>> {
let faces = match self.faces.get().await {
Ok(detector) => Some(
detect_boxes(cx, detector.as_ref(), image, &self.face_labels, self.face_min_score)
.await?,
),
Err(err) if self.people.is_some() => {
tracing::warn!(
vision.backend = self.faces.name(),
error = %err,
"face detector unavailable, covering every detected person whole"
);
None
}
Err(err) => return Err(err),
};
let people = match &self.people {
Some(people) => {
let detector = people.get().await?;
detect_boxes(
cx,
detector.as_ref(),
image,
&self.person_labels,
self.person_min_score,
)
.await?
}
None => Vec::new(),
};
let (width, height) = image.size();
let mut found = Vec::new();
for face in faces.iter().flatten() {
let margin = self.margin * face.width().max(face.height());
found.push((RedactionClass::faces(), face.expanded(margin).clamped(width, height)));
}
for person in people {
let has_face = faces.iter().flatten().any(|face| person.contains(face.center()));
if !has_face {
found.push((RedactionClass::people(), person));
}
}
Ok(found)
}
}
async fn detect_boxes(
cx: &VisionCx,
detector: &dyn Detector,
image: &SentImage,
labels: &[String],
min_score: f32,
) -> Result<Vec<BBox>> {
let descriptor = detector.descriptor();
let fitted = fit_on_device(descriptor, image)?;
let raw = detector.detect(cx, &fitted, &DetectQuery::Classes(labels.to_vec())).await?;
let wanted = |region: &RawRegion| {
let labelled = region
.label
.as_ref()
.is_none_or(|label| labels.iter().any(|wanted| wanted.eq_ignore_ascii_case(label)));
labelled && region.score.is_none_or(|score| score >= min_score)
};
let raw: Vec<RawRegion> = raw.into_iter().filter(wanted).collect();
to_image_boxes(descriptor, &fitted, image, raw)
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
fn builtin_rf_detr(fetcher: crate::ModelFetcher) -> OnDevice<dyn Detector> {
let load: Load<dyn Detector> = Box::new(move || {
let fetcher = fetcher.clone();
Box::pin(async move {
let model = fetch_builtin(&fetcher, DEFAULT_PERSON_DETECTOR).await?;
let detector = load_blocking(DEFAULT_PERSON_DETECTOR, move || {
crate::onnx::RfDetr::new(&model, &crate::onnx::OnnxOptions::default())
})
.await?
.with_threshold(0.05);
tracing::info!(vision.backend = DEFAULT_PERSON_DETECTOR, "person redactor loaded");
Ok(Arc::new(detector) as Arc<dyn Detector>)
}) as Loading<dyn Detector>
});
OnDevice::lazy(DEFAULT_PERSON_DETECTOR, load)
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
async fn fetch_builtin(fetcher: &crate::ModelFetcher, id: &str) -> Result<crate::VerifiedModel> {
let manifest = crate::ManifestSet::builtin()?.get(id).cloned().ok_or_else(|| {
VisionError::Manifest { id: id.into(), reason: "not in the built-in manifest".into() }
})?;
fetcher.fetch(&manifest).await
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
async fn load_blocking<T: Send + 'static>(
id: &str,
build: impl FnOnce() -> Result<T> + Send + 'static,
) -> Result<T> {
tokio::task::spawn_blocking(build).await.map_err(|e| VisionError::Backend {
backend: id.into(),
message: format!("the load task failed: {e}"),
})?
}
pub(crate) fn fit_on_device(
descriptor: &BackendDescriptor,
image: &SentImage,
) -> Result<SentImage> {
if descriptor.locality.is_remote() {
return Err(VisionError::InvalidInput(format!(
"backend `{}` is remote; a redactor runs on the device, before anything is released",
descriptor.id
)));
}
let Some((width, height)) = descriptor.limits.fit(image.size()) else {
return Ok(image.clone());
};
if descriptor.limits.oversize == Oversize::Refuse {
let (w, h) = image.size();
return Err(VisionError::InputTooLarge {
backend: descriptor.id.to_string(),
limit: descriptor.limits.describe(),
actual: format!("{w}x{h}"),
});
}
let mut chain = image.chain().clone();
chain.push(Transform::Resize { width, height })?;
let pixels = ops::resize(image.pixels(), width, height);
Ok(SentImage::new(image.source(), Arc::new(pixels), chain))
}
pub(crate) fn to_image_boxes(
descriptor: &BackendDescriptor,
fitted: &SentImage,
image: &SentImage,
raw: Vec<RawRegion>,
) -> Result<Vec<BBox>> {
let normalizer = RegionNormalizer::new(
fitted.source(),
fitted.chain().clone(),
descriptor.frame,
descriptor.id.clone(),
);
let (width, height) = image.size();
let mut boxes = Vec::new();
for region in normalizer.regions(raw)? {
if let Some(bbox) = region.shape.bbox() {
let target = image.chain().bbox_to_target(&bbox);
boxes.push(target.expanded(REDACTION_MARGIN).clamped(width, height));
}
}
Ok(boxes)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::{BackendDescriptor, Locality};
use crate::digest::Digest;
use crate::geometry::{CoordFrame, TransformChain};
use crate::media::DecodedImage;
struct Fixed(BackendDescriptor, &'static str, BBox);
#[async_trait]
impl Detector for Fixed {
fn descriptor(&self) -> &BackendDescriptor {
&self.0
}
async fn detect(
&self,
_: &VisionCx,
_: &SentImage,
_: &DetectQuery,
) -> Result<Vec<RawRegion>> {
Ok(vec![RawRegion::boxed(self.2, self.1, 0.9)])
}
}
fn local(id: &str) -> BackendDescriptor {
BackendDescriptor::new(id, Locality::InProcess, CoordFrame::SentPixels)
}
fn missing(id: &'static str) -> OnDevice<dyn Detector> {
OnDevice::lazy(
id,
Box::new(move || {
Box::pin(async move {
Err(VisionError::Offline { model: id.into(), file: "model.onnx".into() })
}) as Loading<dyn Detector>
}),
)
}
fn redactor(
faces: OnDevice<dyn Detector>,
people: Option<OnDevice<dyn Detector>>,
) -> FaceRedactor {
FaceRedactor {
faces,
face_labels: vec!["face".into()],
face_min_score: 0.5,
people,
person_labels: vec!["person".into()],
person_min_score: 0.25,
margin: FACE_MARGIN,
}
}
fn image() -> SentImage {
SentImage::new(
Digest::of(b"frame"),
Arc::new(DecodedImage::filled(200, 200, [120, 120, 120, 255])),
TransformChain::new(200, 200),
)
}
#[tokio::test]
async fn a_face_detector_that_cannot_load_covers_every_person_whole() {
let person = BBox::new(20.0, 10.0, 120.0, 190.0);
let people: Arc<dyn Detector> = Arc::new(Fixed(local("people"), "person", person));
let redactor = redactor(missing("yunet-2023mar"), Some(OnDevice::ready("people", people)));
let found = redactor.find_classified(&VisionCx::new(), &image()).await.unwrap();
assert_eq!(found, vec![(RedactionClass::people(), person.expanded(REDACTION_MARGIN))]);
}
#[tokio::test]
async fn without_a_person_fallback_a_missing_face_detector_refuses() {
let err = redactor(missing("yunet-2023mar"), None)
.find_classified(&VisionCx::new(), &image())
.await
.unwrap_err();
assert!(
matches!(&err, VisionError::Offline { model, .. } if model == "yunet-2023mar"),
"{err}"
);
let faces: Arc<dyn Detector> =
Arc::new(Fixed(local("faces"), "face", BBox::new(40.0, 40.0, 60.0, 64.0)));
let err = redactor(OnDevice::ready("faces", faces), Some(missing("rf-detr-n")))
.find_classified(&VisionCx::new(), &image())
.await
.unwrap_err();
assert!(
matches!(&err, VisionError::Offline { model, .. } if model == "rf-detr-n"),
"{err}"
);
}
}