1use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12
13use crate::backend::BackendDescriptor;
14use crate::cx::VisionCx;
15use crate::edit::EditOp;
16use crate::error::Result;
17use crate::geometry::{BBox, EscalatedFrom, Mask, RawRegion, Region, TrackId};
18use crate::media::{DecodedImage, FrameMeta};
19use crate::sent::{SentImage, VisionInput};
20
21#[non_exhaustive]
23#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase", tag = "kind", content = "values")]
25pub enum DetectQuery {
26 Classes(Vec<String>),
28 Concepts(Vec<String>),
30}
31
32#[async_trait]
66pub trait Detector<I: VisionInput = SentImage>: Send + Sync {
67 fn descriptor(&self) -> &BackendDescriptor;
69
70 async fn detect(&self, cx: &VisionCx, image: &I, query: &DetectQuery)
72 -> Result<Vec<RawRegion>>;
73}
74
75#[non_exhaustive]
78#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
79#[serde(rename_all = "camelCase", tag = "kind")]
80pub enum SegmentPrompt {
81 Concept {
83 text: String,
85 },
86 Point {
88 at: [f32; 2],
90 positive: bool,
92 },
93 Box {
95 bbox: BBox,
97 },
98 Mask {
100 mask: Mask,
102 },
103}
104
105#[async_trait]
107pub trait Segmenter<I: VisionInput = SentImage>: Send + Sync {
108 fn descriptor(&self) -> &BackendDescriptor;
110
111 async fn segment(
113 &self,
114 cx: &VisionCx,
115 image: &I,
116 prompts: &[SegmentPrompt],
117 ) -> Result<Vec<RawRegion>>;
118}
119
120#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123#[non_exhaustive]
124pub struct ReadOptions {
125 #[serde(default)]
127 pub languages: Vec<String>,
128 #[serde(default)]
130 pub markdown: bool,
131}
132
133#[non_exhaustive]
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "camelCase")]
137pub enum BlockKind {
138 Text,
140 Title,
142 Table,
144 Formula,
146 Figure,
148 Seal,
150 Checkbox,
152 Handwriting,
154}
155
156#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159pub struct Word<R = Region> {
160 pub region: R,
162 pub text: String,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub confidence: Option<f32>,
167}
168
169#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
171#[serde(rename_all = "camelCase")]
172pub struct TableCell<R = Region> {
173 pub region: R,
175 pub row: u32,
177 pub col: u32,
179 pub row_span: u32,
181 pub col_span: u32,
183 pub text: String,
185}
186
187#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct Block<R = Region> {
191 pub kind: BlockKind,
193 pub region: R,
195 pub text: String,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub confidence: Option<f32>,
200 #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
202 pub words: Vec<Word<R>>,
203 #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
205 pub cells: Vec<TableCell<R>>,
206}
207
208#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct DocumentPage<R = Region> {
212 pub blocks: Vec<Block<R>>,
214 pub reading_order: Vec<usize>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub markdown: Option<String>,
219}
220
221impl<R> Default for DocumentPage<R> {
222 fn default() -> Self {
223 Self { blocks: Vec::new(), reading_order: Vec::new(), markdown: None }
224 }
225}
226
227#[async_trait]
229pub trait DocumentReader<I: VisionInput = SentImage>: Send + Sync {
230 fn descriptor(&self) -> &BackendDescriptor;
232
233 async fn read(
235 &self,
236 cx: &VisionCx,
237 page: &I,
238 options: &ReadOptions,
239 ) -> Result<DocumentPage<RawRegion>>;
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
244#[serde(rename_all = "camelCase")]
245pub enum Metric {
246 Cosine,
248 Dot,
250 L2,
252}
253
254#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
256#[serde(rename_all = "camelCase")]
257pub struct EmbeddingSpace {
258 pub model: String,
260 pub revision: String,
262 pub dimensions: usize,
264 pub metric: Metric,
266}
267
268#[async_trait]
270pub trait Embedder<I: VisionInput = SentImage>: Send + Sync {
271 fn descriptor(&self) -> &BackendDescriptor;
273
274 fn space(&self) -> &EmbeddingSpace;
276
277 async fn embed_images(&self, cx: &VisionCx, images: &[I]) -> Result<Vec<Vec<f32>>>;
279
280 async fn embed_texts(&self, cx: &VisionCx, texts: &[&str]) -> Result<Vec<Vec<f32>>>;
282}
283
284#[derive(Debug)]
286#[non_exhaustive]
287pub struct DescribeRequest<I = SentImage> {
288 pub images: Vec<I>,
290 pub prompt: String,
292 pub output_schema: Option<serde_json::Value>,
294 pub want_regions: bool,
296 pub max_output_tokens: Option<u32>,
298}
299
300impl<I> DescribeRequest<I> {
301 pub(crate) fn new(images: Vec<I>, spec: &DescribeSpec) -> Self {
302 Self {
303 images,
304 prompt: spec.prompt.clone(),
305 output_schema: spec.output_schema.clone(),
306 want_regions: spec.want_regions,
307 max_output_tokens: spec.max_output_tokens,
308 }
309 }
310}
311
312#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
323#[serde(rename_all = "camelCase")]
324#[non_exhaustive]
325pub struct DescribeSpec {
326 pub prompt: String,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub output_schema: Option<serde_json::Value>,
331 #[serde(default)]
333 pub want_regions: bool,
334 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub max_output_tokens: Option<u32>,
337}
338
339impl DescribeSpec {
340 pub fn new(prompt: impl Into<String>) -> Self {
342 Self { prompt: prompt.into(), ..Self::default() }
343 }
344
345 pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
347 self.output_schema = Some(schema);
348 self
349 }
350
351 pub fn with_regions(mut self) -> Self {
353 self.want_regions = true;
354 self
355 }
356
357 pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
359 self.max_output_tokens = Some(tokens);
360 self
361 }
362}
363
364#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase")]
367pub struct ImageRegion {
368 pub image: usize,
370 pub region: RawRegion,
372}
373
374#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
377#[serde(rename_all = "camelCase")]
378pub struct Description<R = Region> {
379 #[serde(default, skip_serializing_if = "Option::is_none")]
381 pub text: Option<String>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
384 pub value: Option<serde_json::Value>,
385 #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
387 pub regions: Vec<R>,
388 #[serde(default, skip_serializing_if = "Option::is_none")]
390 pub confidence: Option<f32>,
391 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub escalated_from: Option<EscalatedFrom>,
395}
396
397impl<R> Default for Description<R> {
398 fn default() -> Self {
399 Self {
400 text: None,
401 value: None,
402 regions: Vec::new(),
403 confidence: None,
404 escalated_from: None,
405 }
406 }
407}
408
409#[async_trait]
411pub trait Describer<I: VisionInput = SentImage>: Send + Sync {
412 fn descriptor(&self) -> &BackendDescriptor;
414
415 async fn describe(
417 &self,
418 cx: &VisionCx,
419 request: &DescribeRequest<I>,
420 ) -> Result<Description<ImageRegion>>;
421}
422
423pub trait Tracker: Send {
425 fn update(&mut self, frame: &FrameMeta, detections: Vec<Region>) -> Vec<Region>;
427
428 fn reset(&mut self);
430
431 fn live_tracks(&self) -> Vec<TrackId> {
435 Vec::new()
436 }
437}
438
439#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
451#[serde(rename_all = "camelCase")]
452pub struct Sampling {
453 pub fps: f32,
455 #[serde(default, skip_serializing_if = "Option::is_none")]
457 pub max_long_edge: Option<u32>,
458}
459
460impl Sampling {
461 pub fn at(fps: f32) -> Self {
463 Self { fps, max_long_edge: None }
464 }
465}
466
467#[non_exhaustive]
469#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
470#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
471pub enum VideoRequest {
472 Track {
474 prompts: Vec<SegmentPrompt>,
476 },
477 Caption {
482 chunk_ms: u64,
484 },
485 Ask {
487 question: String,
489 },
490}
491
492#[non_exhaustive]
497pub struct VideoInput<I: VisionInput = SentImage> {
498 pub frames: Vec<(FrameMeta, I)>,
500 pub clip: Option<I::Clip>,
502 pub sampling: Sampling,
504}
505
506impl<I: VisionInput> VideoInput<I> {
507 pub(crate) fn new(
508 frames: Vec<(FrameMeta, I)>,
509 clip: Option<I::Clip>,
510 sampling: Sampling,
511 ) -> Self {
512 Self { frames, clip, sampling }
513 }
514}
515
516impl<I: VisionInput + std::fmt::Debug> std::fmt::Debug for VideoInput<I> {
517 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518 f.debug_struct("VideoInput")
519 .field("frames", &self.frames)
520 .field("clip", &self.clip)
521 .field("sampling", &self.sampling)
522 .finish()
523 }
524}
525
526#[derive(Clone, Debug, PartialEq)]
529#[non_exhaustive]
530pub struct VideoPlan {
531 pub clip: Option<crate::video::ClipInfo>,
533 pub frame_sizes: Vec<(u32, u32)>,
535 pub duration_ms: u64,
537 pub sampling: Sampling,
539}
540
541impl VideoPlan {
542 pub fn frames(&self) -> u64 {
544 match &self.clip {
545 Some(clip) => clip.frames,
546 None => self.frame_sizes.len() as u64,
547 }
548 }
549}
550
551#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
564#[serde(rename_all = "camelCase")]
565pub struct VideoEvent {
566 pub start_ms: u64,
568 pub end_ms: u64,
570 pub text: String,
572 #[serde(default, skip_serializing_if = "Vec::is_empty")]
574 pub labels: Vec<String>,
575}
576
577impl VideoEvent {
578 pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
580 Self { start_ms, end_ms, text: text.into(), labels: Vec::new() }
581 }
582
583 pub fn with_labels<I, S>(mut self, labels: I) -> Self
585 where
586 I: IntoIterator<Item = S>,
587 S: Into<String>,
588 {
589 self.labels.extend(labels.into_iter().map(Into::into));
590 self
591 }
592}
593
594#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597pub struct VideoFrame<R = Region> {
598 pub index: u64,
600 #[serde(default, skip_serializing_if = "Option::is_none")]
602 pub pts_ms: Option<u64>,
603 pub regions: Vec<R>,
605}
606
607#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
609#[serde(rename_all = "camelCase")]
610#[non_exhaustive]
611pub struct VideoUsage {
612 pub frames: u64,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
616 pub input_tokens: Option<u64>,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
619 pub output_tokens: Option<u64>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
623 pub cost_micro_usd: Option<u64>,
624 pub requests: u64,
626}
627
628#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
630#[serde(rename_all = "camelCase")]
631#[non_exhaustive]
632pub struct VideoAnalysis<R = Region> {
633 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub answer: Option<String>,
636 #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
638 pub events: Vec<VideoEvent>,
639 #[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
641 pub frames: Vec<VideoFrame<R>>,
642 #[serde(default)]
644 pub usage: VideoUsage,
645}
646
647impl<R> Default for VideoAnalysis<R> {
648 fn default() -> Self {
649 Self { answer: None, events: Vec::new(), frames: Vec::new(), usage: VideoUsage::default() }
650 }
651}
652
653#[async_trait]
659pub trait VideoAnalyzer<I: VisionInput = SentImage>: Send + Sync {
660 fn descriptor(&self) -> &BackendDescriptor;
662
663 fn frames(&self, plan: &VideoPlan) -> u64 {
666 plan.frames()
667 }
668
669 fn max_cost_micro_usd(&self, _plan: &VideoPlan, _request: &VideoRequest) -> Option<u64> {
673 None
674 }
675
676 async fn analyze(
678 &self,
679 cx: &VisionCx,
680 video: &VideoInput<I>,
681 request: &VideoRequest,
682 ) -> Result<VideoAnalysis<RawRegion>>;
683}
684
685#[async_trait]
688pub trait Editor<I: VisionInput = SentImage>: Send + Sync {
689 fn descriptor(&self) -> &BackendDescriptor;
691
692 async fn edit(&self, cx: &VisionCx, image: &I, operation: &EditOp) -> Result<DecodedImage>;
694}