use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::backend::BackendDescriptor;
use crate::cx::VisionCx;
use crate::edit::EditOp;
use crate::error::Result;
use crate::geometry::{BBox, EscalatedFrom, Mask, RawRegion, Region, TrackId};
use crate::media::{DecodedImage, FrameMeta};
use crate::sent::{SentImage, VisionInput};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind", content = "values")]
pub enum DetectQuery {
Classes(Vec<String>),
Concepts(Vec<String>),
}
#[async_trait]
pub trait Detector<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
async fn detect(&self, cx: &VisionCx, image: &I, query: &DetectQuery)
-> Result<Vec<RawRegion>>;
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum SegmentPrompt {
Concept {
text: String,
},
Point {
at: [f32; 2],
positive: bool,
},
Box {
bbox: BBox,
},
Mask {
mask: Mask,
},
}
#[async_trait]
pub trait Segmenter<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
async fn segment(
&self,
cx: &VisionCx,
image: &I,
prompts: &[SegmentPrompt],
) -> Result<Vec<RawRegion>>;
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReadOptions {
#[serde(default)]
pub languages: Vec<String>,
#[serde(default)]
pub markdown: bool,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BlockKind {
Text,
Title,
Table,
Formula,
Figure,
Seal,
Checkbox,
Handwriting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Word<R = Region> {
pub region: R,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<f32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableCell<R = Region> {
pub region: R,
pub row: u32,
pub col: u32,
pub row_span: u32,
pub col_span: u32,
pub text: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Block<R = Region> {
pub kind: BlockKind,
pub region: R,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<f32>,
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub words: Vec<Word<R>>,
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub cells: Vec<TableCell<R>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentPage<R = Region> {
pub blocks: Vec<Block<R>>,
pub reading_order: Vec<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub markdown: Option<String>,
}
impl<R> Default for DocumentPage<R> {
fn default() -> Self {
Self { blocks: Vec::new(), reading_order: Vec::new(), markdown: None }
}
}
#[async_trait]
pub trait DocumentReader<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
async fn read(
&self,
cx: &VisionCx,
page: &I,
options: &ReadOptions,
) -> Result<DocumentPage<RawRegion>>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Metric {
Cosine,
Dot,
L2,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmbeddingSpace {
pub model: String,
pub revision: String,
pub dimensions: usize,
pub metric: Metric,
}
#[async_trait]
pub trait Embedder<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
fn space(&self) -> &EmbeddingSpace;
async fn embed_images(&self, cx: &VisionCx, images: &[I]) -> Result<Vec<Vec<f32>>>;
async fn embed_texts(&self, cx: &VisionCx, texts: &[&str]) -> Result<Vec<Vec<f32>>>;
}
#[derive(Debug)]
#[non_exhaustive]
pub struct DescribeRequest<I = SentImage> {
pub images: Vec<I>,
pub prompt: String,
pub output_schema: Option<serde_json::Value>,
pub want_regions: bool,
pub max_output_tokens: Option<u32>,
}
impl<I> DescribeRequest<I> {
pub(crate) fn new(images: Vec<I>, spec: &DescribeSpec) -> Self {
Self {
images,
prompt: spec.prompt.clone(),
output_schema: spec.output_schema.clone(),
want_regions: spec.want_regions,
max_output_tokens: spec.max_output_tokens,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DescribeSpec {
pub prompt: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_schema: Option<serde_json::Value>,
#[serde(default)]
pub want_regions: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u32>,
}
impl DescribeSpec {
pub fn new(prompt: impl Into<String>) -> Self {
Self { prompt: prompt.into(), ..Self::default() }
}
pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
self.output_schema = Some(schema);
self
}
pub fn with_regions(mut self) -> Self {
self.want_regions = true;
self
}
pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
self.max_output_tokens = Some(tokens);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageRegion {
pub image: usize,
pub region: RawRegion,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Description<R = Region> {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<serde_json::Value>,
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub regions: Vec<R>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalated_from: Option<EscalatedFrom>,
}
impl<R> Default for Description<R> {
fn default() -> Self {
Self {
text: None,
value: None,
regions: Vec::new(),
confidence: None,
escalated_from: None,
}
}
}
#[async_trait]
pub trait Describer<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
async fn describe(
&self,
cx: &VisionCx,
request: &DescribeRequest<I>,
) -> Result<Description<ImageRegion>>;
}
pub trait Tracker: Send {
fn update(&mut self, frame: &FrameMeta, detections: Vec<Region>) -> Vec<Region>;
fn reset(&mut self);
fn live_tracks(&self) -> Vec<TrackId> {
Vec::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Sampling {
pub fps: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_long_edge: Option<u32>,
}
impl Sampling {
pub fn at(fps: f32) -> Self {
Self { fps, max_long_edge: None }
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum VideoRequest {
Track {
prompts: Vec<SegmentPrompt>,
},
Caption {
chunk_ms: u64,
},
Ask {
question: String,
},
}
#[non_exhaustive]
pub struct VideoInput<I: VisionInput = SentImage> {
pub frames: Vec<(FrameMeta, I)>,
pub clip: Option<I::Clip>,
pub sampling: Sampling,
}
impl<I: VisionInput> VideoInput<I> {
pub(crate) fn new(
frames: Vec<(FrameMeta, I)>,
clip: Option<I::Clip>,
sampling: Sampling,
) -> Self {
Self { frames, clip, sampling }
}
}
impl<I: VisionInput + std::fmt::Debug> std::fmt::Debug for VideoInput<I> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoInput")
.field("frames", &self.frames)
.field("clip", &self.clip)
.field("sampling", &self.sampling)
.finish()
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct VideoPlan {
pub clip: Option<crate::video::ClipInfo>,
pub frame_sizes: Vec<(u32, u32)>,
pub duration_ms: u64,
pub sampling: Sampling,
}
impl VideoPlan {
pub fn frames(&self) -> u64 {
match &self.clip {
Some(clip) => clip.frames,
None => self.frame_sizes.len() as u64,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoEvent {
pub start_ms: u64,
pub end_ms: u64,
pub text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>,
}
impl VideoEvent {
pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
Self { start_ms, end_ms, text: text.into(), labels: Vec::new() }
}
pub fn with_labels<I, S>(mut self, labels: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.labels.extend(labels.into_iter().map(Into::into));
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoFrame<R = Region> {
pub index: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pts_ms: Option<u64>,
pub regions: Vec<R>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VideoUsage {
pub frames: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_micro_usd: Option<u64>,
pub requests: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VideoAnalysis<R = Region> {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub answer: Option<String>,
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub events: Vec<VideoEvent>,
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub frames: Vec<VideoFrame<R>>,
#[serde(default)]
pub usage: VideoUsage,
}
impl<R> Default for VideoAnalysis<R> {
fn default() -> Self {
Self { answer: None, events: Vec::new(), frames: Vec::new(), usage: VideoUsage::default() }
}
}
#[async_trait]
pub trait VideoAnalyzer<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
fn frames(&self, plan: &VideoPlan) -> u64 {
plan.frames()
}
fn max_cost_micro_usd(&self, _plan: &VideoPlan, _request: &VideoRequest) -> Option<u64> {
None
}
async fn analyze(
&self,
cx: &VisionCx,
video: &VideoInput<I>,
request: &VideoRequest,
) -> Result<VideoAnalysis<RawRegion>>;
}
#[async_trait]
pub trait Editor<I: VisionInput = SentImage>: Send + Sync {
fn descriptor(&self) -> &BackendDescriptor;
async fn edit(&self, cx: &VisionCx, image: &I, operation: &EditOp) -> Result<DecodedImage>;
}