use adk_core::ArtifactLocator;
use async_trait::async_trait;
use chrono::{DateTime, SecondsFormat, Utc};
use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::error::{KernelError, Result};
use crate::wake::{WAKE_PAYLOAD_LIMIT, WakeEvent, WakeHub, WakeSource, keys};
pub const VISION_PAYLOAD_KIND: &str = "vision";
const PAYLOAD_TEXT_CHARS: usize = 64;
const PAYLOAD_FILE_CHARS: usize = 128;
const MAX_KEY_PART: usize = 128;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VisualFrame {
pub index: u64,
pub captured_at: DateTime<Utc>,
pub digest: String,
pub width: u32,
pub height: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub artifact: Option<ArtifactLocator>,
}
impl VisualFrame {
pub fn new(
index: u64,
captured_at: DateTime<Utc>,
digest: impl Into<String>,
width: u32,
height: u32,
) -> Self {
Self { index, captured_at, digest: digest.into(), width, height, artifact: None }
}
#[must_use]
pub fn with_artifact(mut self, artifact: ArtifactLocator) -> Self {
self.artifact = Some(artifact);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VisualRegion {
#[serde(rename = "box")]
pub bbox: [f32; 4],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub track: Option<u64>,
}
impl VisualRegion {
pub fn new(bbox: [f32; 4]) -> Self {
Self { bbox, label: None, score: None, track: None }
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_score(mut self, score: f32) -> Self {
self.score = Some(score);
self
}
#[must_use]
pub fn with_track(mut self, track: u64) -> Self {
self.track = Some(track);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VisualWake {
pub session: String,
pub condition: String,
pub event: String,
pub track: u64,
pub label: String,
pub score: f32,
pub frames: u32,
pub frame: VisualFrame,
pub regions: Vec<VisualRegion>,
}
impl VisualWake {
pub fn new(
session: impl Into<String>,
condition: impl Into<String>,
event: impl Into<String>,
track: u64,
label: impl Into<String>,
score: f32,
frame: VisualFrame,
) -> Self {
Self {
session: session.into(),
condition: condition.into(),
event: event.into(),
track,
label: label.into(),
score,
frames: 1,
frame,
regions: Vec::new(),
}
}
#[must_use]
pub fn with_frames(mut self, frames: u32) -> Self {
self.frames = frames;
self
}
#[must_use]
pub fn with_regions(mut self, regions: impl IntoIterator<Item = VisualRegion>) -> Self {
self.regions = regions.into_iter().collect();
self
}
}
#[derive(Debug)]
pub struct VisionWakeSource {
name: String,
hub: WakeHub,
}
impl VisionWakeSource {
pub fn new(source: impl Into<String>) -> Result<Self> {
let name = source.into();
key_part("source name", &name)?;
if name.contains(':') {
return Err(KernelError::Config {
reason: format!(
"the visual wake source name `{name}` holds `:`; name the stream without \
one, since a key's source ends at its first `:`"
),
});
}
Ok(Self { name, hub: WakeHub::default() })
}
pub fn event(&self, wake: &VisualWake) -> Result<WakeEvent> {
key_part("session", &wake.session)?;
key_part("condition", &wake.condition)?;
key_part("event", &wake.event)?;
let key = keys::vision(&self.name, &wake.session, wake.track, &wake.condition, &wake.event);
Ok(WakeEvent::new(self.name.clone(), key, vision_payload(&self.name, wake))
.with_at(wake.frame.captured_at))
}
pub fn publish(&self, wake: &VisualWake) -> Result<WakeEvent> {
let event = self.event(wake)?;
tracing::debug!(wake.source = %self.name, wake.key = %event.key, "visual wake published");
self.hub.publish(event.clone());
Ok(event)
}
}
#[async_trait]
impl WakeSource for VisionWakeSource {
fn name(&self) -> &str {
&self.name
}
async fn subscribe(&self) -> Result<BoxStream<'static, WakeEvent>> {
Ok(self.hub.subscribe())
}
}
fn key_part(what: &str, text: &str) -> Result<()> {
let ok = !text.is_empty()
&& text.len() <= MAX_KEY_PART
&& !text.chars().any(|c| c.is_whitespace() || c.is_control() || c == '#');
if ok {
return Ok(());
}
Err(KernelError::Config {
reason: format!(
"a visual wake's {what} `{}` cannot be part of a key: use 1 to {MAX_KEY_PART} bytes \
with no whitespace, control character or `#`",
clip(text, PAYLOAD_TEXT_CHARS)
),
})
}
fn clip(text: &str, chars: usize) -> String {
text.chars().take(chars).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect()
}
fn rounded(value: f32, decimals: i32) -> Value {
let scale = 10f64.powi(decimals);
json!((f64::from(value) * scale).round() / scale)
}
fn region_json(region: &VisualRegion) -> Value {
let mut entry = json!({ "box": region.bbox.map(|edge| rounded(edge, 1)) });
if let Some(label) = ®ion.label {
entry["label"] = json!(clip(label, PAYLOAD_TEXT_CHARS));
}
if let Some(score) = region.score {
entry["score"] = rounded(score, 2);
}
if let Some(track) = region.track {
entry["track"] = json!(track);
}
entry
}
pub fn vision_payload(source: &str, wake: &VisualWake) -> Value {
let text = |value: &str| json!(clip(value, PAYLOAD_TEXT_CHARS));
let frame = &wake.frame;
let mut frame_json = json!({
"index": frame.index,
"capturedAt": frame.captured_at.to_rfc3339_opts(SecondsFormat::Millis, true),
"digest": clip(&frame.digest, 80),
"width": frame.width,
"height": frame.height,
});
if let Some(artifact) = &frame.artifact {
frame_json["artifact"] = json!({
"appName": text(&artifact.app_name),
"userId": text(&artifact.user_id),
"sessionId": text(&artifact.session_id),
"fileName": clip(&artifact.file_name, PAYLOAD_FILE_CHARS),
"version": artifact.version,
});
}
let regions: Vec<Value> = wake.regions.iter().map(region_json).collect();
let total = regions.len();
let build = |kept: usize| {
json!({
"kind": VISION_PAYLOAD_KIND,
"source": text(source),
"session": text(&wake.session),
"condition": text(&wake.condition),
"event": text(&wake.event),
"label": text(&wake.label),
"score": rounded(wake.score, 2),
"track": wake.track,
"frames": wake.frames,
"frame": frame_json,
"regions": regions[..kept],
"moreRegions": total - kept,
})
};
let fits = |kept: usize| build(kept).to_string().len() <= WAKE_PAYLOAD_LIMIT;
let (mut low, mut high) = (0, total);
while low < high {
let mid = (low + high).div_ceil(2);
if fits(mid) {
low = mid;
} else {
high = mid - 1;
}
}
build(low)
}
#[cfg(feature = "vision")]
mod bridge {
use adk_vision::{VisionError, WatchEvent, WatchSink};
use async_trait::async_trait;
use super::{VisionWakeSource, VisualFrame, VisualRegion, VisualWake};
impl From<&WatchEvent> for VisualWake {
fn from(event: &WatchEvent) -> Self {
let frame = &event.frame;
let mut visual = VisualFrame::new(
frame.index,
frame.captured_at,
frame.digest.to_string(),
frame.width,
frame.height,
);
visual.artifact = frame.artifact.clone();
let regions = event.regions.iter().filter_map(|region| {
let b = region.shape.bbox()?;
Some(VisualRegion {
bbox: [b.x0, b.y0, b.x1, b.y1],
label: region.label.clone(),
score: region.score,
track: region.track.map(|track| track.0),
})
});
VisualWake::new(
event.session.clone(),
event.condition.clone(),
event.kind.as_str(),
event.track.0,
event.label.clone(),
event.score,
visual,
)
.with_frames(event.frames)
.with_regions(regions)
}
}
#[async_trait]
impl WatchSink for VisionWakeSource {
async fn deliver(&self, event: &WatchEvent) -> adk_vision::Result<()> {
if event.source.0 != self.name {
return Err(VisionError::InvalidInput(format!(
"a watch event from stream `{}` reached the wake source of `{}`; register \
one VisionWakeSource per stream",
event.source.0, self.name
)));
}
self.publish(&VisualWake::from(event))
.map(|_| ())
.map_err(|error| VisionError::InvalidInput(error.to_string()))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn frame() -> VisualFrame {
VisualFrame::new(4, Utc::now(), "sha256:0f3a", 640, 480)
}
#[test]
fn names_and_key_parts_that_cannot_key_a_wake_are_refused() {
for name in ["", "rtsp://cam", "two words", "a#b"] {
assert!(VisionWakeSource::new(name).is_err(), "{name:?}");
}
let source = VisionWakeSource::new("cam-1").unwrap();
for (session, condition) in [("", "seal"), ("s 1", "seal"), ("s1", "se#al")] {
let wake = VisualWake::new(session, condition, "detected", 1, "seal", 0.9, frame());
assert!(source.event(&wake).is_err(), "{session:?} {condition:?}");
}
}
#[test]
fn a_published_wake_reaches_a_later_subscriber_once() {
use futures::StreamExt;
let source = VisionWakeSource::new("cam-1").unwrap();
let wake = VisualWake::new("s1", "seal", "detected", 3, "seal", 0.9, frame());
let published = source.publish(&wake).unwrap();
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let received = runtime.block_on(async {
let mut events = source.subscribe().await.unwrap();
events.next().await.unwrap()
});
assert_eq!(received, published);
assert_eq!(received.key, "queue:cam-1:s1:3:seal:detected");
}
#[test]
fn a_media_store_file_name_reaches_the_payload_whole() {
let file = format!("vision-{}.png", "0f".repeat(32));
let frame =
frame().with_artifact(ArtifactLocator::new("inspector", "line-1", "s1", &file, 0));
let wake = VisualWake::new("s1", "seal", "detected", 1, "seal", 0.9, frame);
let payload = vision_payload("cam-1", &wake);
assert_eq!(payload["frame"]["artifact"]["fileName"], json!(file));
}
#[test]
fn hostile_labels_stay_within_the_limit() {
let label = "\u{0}\"\\\u{10ffff}".repeat(400);
let region = VisualRegion::new([0.0, 0.0, 1.0, 1.0]).with_label(label.clone());
let mut frame = frame();
frame.digest = label.clone();
frame.artifact = Some(ArtifactLocator::new(&label, &label, &label, &label, 1));
let wake = VisualWake::new("s1", "seal", "detected", 1, label, 0.5, frame)
.with_regions(vec![region; 100]);
let payload = vision_payload(&"\u{1F600}".repeat(200), &wake);
assert!(payload.to_string().len() <= WAKE_PAYLOAD_LIMIT, "{}", payload.to_string().len());
assert!(payload["regions"].as_array().is_some_and(|kept| !kept.is_empty()));
}
}