adk_vision/lib.rs
1//! # adk-vision
2//!
3//! Local-first perception for ADK-Rust agents (spec 3.7).
4//!
5//! The crate is contracts first: artifact-backed images ([`ImageRef`]); regions that always
6//! know their source image and the transforms between it and the model ([`Region`],
7//! [`CoordFrame`], [`TransformChain`]); model manifests that pin every weight file by
8//! revision and SHA-256 and name its licence ([`ModelManifest`]); and the perception traits
9//! — [`Detector`], [`Segmenter`], [`DocumentReader`], [`Embedder`], [`Describer`],
10//! [`Tracker`], [`VideoAnalyzer`] and [`Editor`] — each with a conformance suite.
11//!
12//! [`VisionRuntime`] routes each call to a backend, local first. An on-device backend is
13//! handed a [`SentImage`]; a remote backend only a [`ReleasedImage`], which only the
14//! [`EgressGate`] constructs after it has checked the destination, cropped, redacted the
15//! classes the rules list, decided and recorded what leaves. With no rules an image leaves
16//! as it is; `ask`, `deny`, `redact` and `on_device` each restrict once chosen. Every call is metered against the run's budget and
17//! spend ledger, local calls at zero cost, and every answer comes back in source pixels.
18//!
19//! # Features
20//!
21//! | Feature | Contents |
22//! |---------|----------|
23//! | (always) | media, geometry, manifests, the traits, `VisionRuntime`, the egress gate, the deterministic `Editor`, watch conditions ([`WatchEvaluator`]), calibration and measurement ([`Calibration`]), the verifier loop ([`VerifierLoop`]) |
24//! | `fetch` | `ModelFetcher`: Hugging Face downloads by revision, SHA-256 checked before load, `HF_HUB_OFFLINE` honoured |
25//! | `conformance` | `conformance`: the suite every backend runs, and its test macros |
26//! | `eval` | `eval`: any runtime task as an `adk-eval` agent, in process or behind `cargo adk eval --agent-cmd` |
27//! | `guardrail` | `ImagePrivacyGuardrail` on model calls, tool results and user input, and `PersonalTextRedactor` (OCR words matched by `adk-guardrail`'s PII patterns) |
28//! | `onnx` | `onnx`: RF-DETR, EfficientSAM, SAM 2.1 and SigLIP 2 on ONNX Runtime, the runtime downloaded at build time |
29//! | `onnx-dynamic` | The same backends against an onnxruntime library loaded from `ORT_DYLIB_PATH` |
30//! | `onnx-coreml`, `onnx-cuda` | The CoreML and CUDA execution providers for the `onnx` backends |
31//! | `sam3-local` | SAM 3 on ONNX Runtime from weights you supply under Meta's SAM License, after you accept it |
32//! | `cloud` | `LlmDescriber` over any `adk_core::Llm` that takes images, with the Gemini, Claude and 0–1000 region adapters; `FramesAnalyzer`, questions over sampled frames on the same models |
33//! | `nim` | NVIDIA NIM: vision-language models over the OpenAI-compatible client, and `NimDocumentReader` for NVIDIA's OCR, page, table and chart endpoints, remote (implies `cloud`) |
34//! | `sam` | The Meta `sam-3.1` client: `SamSegmenter`, its stream parser and mask placement; `SamVideoTracker`, masks with stable object identifiers over a clip |
35//! | `sam-codec` | `LicensedMaskDecoder`: `sam-3.1` masks decoded in process by `adk-vision-sam-codec`, the port of Meta's codec under the SAM License, after a person records acceptance (implies `sam`) |
36//! | `ocr` | `PpOcrReader`: PP-OCRv6 text lines and words through `oar-ocr` on ONNX Runtime |
37//! | `ocr-vl` | `PaddleOcrVlReader`: PaddleOCR-VL-1.6 with PP-DocLayoutV3 through `oar-ocr-vl` on Candle |
38//! | `ocr-vl-metal` | `ocr-vl` on Apple GPUs |
39//! | `mistralrs` | `mistralrs`: `LlmDescriber::mistralrs` loads a verified Qwen3-VL (or another mistral.rs vision model) in this process; regions in Qwen3-VL's own 0–1000 frame (implies `cloud`, `fetch`) |
40//! | `mistralrs-metal`, `mistralrs-cuda` | `mistralrs` on Apple GPUs or CUDA |
41//! | `stream` | `stream`: `FrameSource`, the sampler, the frame governor, frame retention and the stream pipeline; `StreamWatch`, which keeps each watch event's frame and wakes a `WatchSink`; `FrameSources`, the named sources `vision_watch` starts and stops watches on |
42//! | `rtsp`, `ffmpeg`, `screen`, `browser`, `surface-camera` | The frame sources: `RtspSource`, `FileSource` (and H.264/H.265 through a user-installed ffmpeg), `ScreenSource`, `BrowserSource`, `SurfaceCameraSource` |
43//! | `device` | `DeviceSource`: a camera on this machine through a user-installed ffmpeg (AVFoundation, v4l2, DirectShow), and `DeviceSource::list` (implies `ffmpeg`) |
44//! | `computer-use` | `GroundedTarget::target_evidence` as `adk-computer-use` `TargetEvidence`; with `screen`, `stream::RuntimeObserver` and `stream::screen_source`, any `ComputerUseRuntime` as a screen frame source |
45//! | `stream-fixtures` | `stream::fixtures`: the generated conveyor clip and an in-process RTSP test server |
46//! | `track` | `ByteTracker`: ByteTrack through `trackforge`, anonymous tracks with stable identifiers across frames |
47//! | `gemini-video` | `GeminiVideoAnalyzer`: Gemini native video, through the File API above 20 MB, at an explicit frame rate and media resolution (implies `cloud`) |
48//! | `memory` | `memory`: `VisualMemory`, image embeddings as `adk-rag` chunks in any vector store with one embedding space per collection, text and example-image queries, `SiglipTextEmbedding` for `adk-rag` pipelines, captions with artifact references in `adk-memory`, erasure by source; the S16 week corpus |
49//! | `analyst` | `analyst`: `VideoAnalyst`, the video chunked in fixed windows or at scene cuts, each chunk captioned through the video analyzer, indexed in any vector store with its time range, captions with keyframe and clip references in `adk-memory`, the clip in graph memory; questions answered citing chunks; cost per hour of video; erasure by clip; the S17 warehouse clip (implies `cloud`, `memory`, `stream`) |
50//! | `team` | `team`: the perceiver, reasoner and verifier roles and `VisionTeam`, which escalates a disagreement to a person on one card (implies `guardrail`) |
51//!
52//! [`VisionToolset`] — `vision_detect`, `vision_segment`, `vision_read`, `vision_describe`,
53//! `vision_crop`, `vision_redact`, `vision_annotate`, `vision_measure`, `vision_video`, and
54//! with feature `stream` `vision_watch` over registered frame sources — is always built: each tool runs on
55//! the governed path, a remote call a rule asks for is held with the exact egress image as
56//! approval evidence, and every call, release and edit writes its `vision.*` audit record
57//! ([`audit`]).
58//!
59//!
60//! # Example
61//!
62//! ```
63//! use std::sync::Arc;
64//! use adk_vision::{
65//! BBox, BackendDescriptor, CoordFrame, DetectQuery, Detector, Locality, RawRegion,
66//! SentImage, SourceImage, DecodedImage, VisionCx, VisionRuntime,
67//! };
68//!
69//! /// A detector that finds the whole image, in the pixels it was sent.
70//! struct Whole(BackendDescriptor);
71//!
72//! #[async_trait::async_trait]
73//! impl Detector for Whole {
74//! fn descriptor(&self) -> &BackendDescriptor {
75//! &self.0
76//! }
77//! async fn detect(
78//! &self,
79//! _cx: &VisionCx,
80//! image: &SentImage,
81//! _query: &DetectQuery,
82//! ) -> adk_vision::Result<Vec<RawRegion>> {
83//! let (w, h) = image.size();
84//! Ok(vec![RawRegion::boxed(BBox::new(0.0, 0.0, w as f32, h as f32), "page", 0.99)])
85//! }
86//! }
87//!
88//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
89//! // The backend takes at most 500 px on the long edge; the runtime downscales and records it.
90//! let whole = BackendDescriptor::new("whole", Locality::InProcess, CoordFrame::SentPixels)
91//! .with_limits(adk_vision::InputLimits::long_edge(500));
92//! let runtime = VisionRuntime::builder().detector(Arc::new(Whole(whole))).build().unwrap();
93//!
94//! let page = SourceImage::from_pixels(DecodedImage::filled(2000, 1000, [255; 4])).unwrap();
95//! let found = runtime
96//! .detect(&VisionCx::new(), &page, &DetectQuery::Classes(vec!["page".into()]))
97//! .await
98//! .unwrap();
99//! // Back in source pixels, with the resize on record.
100//! assert_eq!(found.value[0].shape.bbox(), Some(BBox::new(0.0, 0.0, 2000.0, 1000.0)));
101//! assert!(!found.value[0].origin.chain.is_identity());
102//! # });
103//! ```
104//!
105//! ## Stability
106//!
107//! Experimental — new in 3.0.0 (spec 3.7), and its API may change while the spec lands. See
108//! [STABILITY.md](https://github.com/zavora-ai/adk-rust/blob/main/STABILITY.md).
109
110#![warn(missing_docs)]
111
112#[cfg(feature = "analyst")]
113pub mod analyst;
114pub mod audit;
115mod backend;
116mod budget;
117#[cfg(feature = "cloud")]
118pub mod cloud;
119#[cfg(feature = "conformance")]
120pub mod conformance;
121mod cx;
122mod digest;
123mod edit;
124mod egress;
125mod error;
126#[cfg(feature = "eval")]
127pub mod eval;
128#[cfg(feature = "fetch")]
129mod fetch;
130mod geometry;
131#[cfg(feature = "guardrail")]
132mod guardrail;
133mod manifest;
134mod mask_decoder;
135mod measure;
136mod media;
137#[cfg(feature = "memory")]
138pub mod memory;
139#[cfg(feature = "mistralrs")]
140pub mod mistralrs;
141#[cfg(feature = "nim")]
142mod nim_cv;
143#[cfg(feature = "ocr")]
144mod ocr;
145#[cfg(feature = "ocr-vl")]
146mod ocr_vl;
147#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
148pub mod onnx;
149#[cfg(any(feature = "ocr", feature = "ocr-vl", feature = "nim"))]
150mod reading;
151mod redact;
152mod runtime;
153#[cfg(feature = "sam")]
154pub mod sam;
155pub mod screen;
156mod sent;
157#[cfg(feature = "stream")]
158pub mod stream;
159#[cfg(feature = "team")]
160pub mod team;
161mod toolset;
162#[cfg(feature = "track")]
163mod track;
164mod tracker;
165mod traits;
166mod verify;
167pub mod video;
168mod watch;
169
170pub use backend::{BackendDescriptor, BackendId, InputLimits, Locality, Oversize, PriceRef};
171pub use budget::{ImageTokens, TokenEstimate};
172#[cfg(feature = "cloud")]
173pub use cloud::{LlmDescriber, RegionAdapter};
174pub use cx::VisionCx;
175pub use digest::Digest;
176pub use edit::{DeterministicEditor, EditOp, Overlay, Rgba, apply_edit};
177pub use egress::{ClipReleaseRequest, ReleasedClip};
178pub use egress::{
179 DataClass, EgressAction, EgressConfig, EgressDecision, EgressEvidence, EgressGate,
180 EgressPreview, EgressReceipt, EgressRecord, EgressRecorder, EgressRefusal, EgressRuleConfig,
181 InMemoryEgressRecorder, RedactionClass, Redactor, ReleaseRequest, ReleasedImage, RuleTarget,
182 StagedEgress, VisionConfig,
183};
184pub use error::{Result, VisionError};
185#[cfg(feature = "fetch")]
186pub use fetch::{FetchConfig, ModelFetcher};
187pub use geometry::{
188 AxisOrder, BBox, CoordFrame, EscalatedFrom, EscalationReason, Keypoint, Keypoints, Letterbox,
189 LetterboxGeometry, Mask, Point2, Polygon, RawRegion, Region, RegionNormalizer, RegionOrigin,
190 RegionSet, ScreenSpace, Shape, Track, TrackId, Transform, TransformChain,
191};
192#[cfg(feature = "guardrail")]
193pub use guardrail::{
194 GateOutcome, ImagePrivacyGuardrail, MODEL_CONTEXT_CLASS, PERSONAL_FIELD_LABELS,
195 PersonalTextRedactor,
196};
197pub use manifest::{
198 AcceptanceStore, FileAcceptanceStore, InMemoryAcceptanceStore, InputSpec, IoSpec,
199 LicenceAcceptance, LicenceClass, LicenceGate, LicenceInfo, LicencePolicy, ManifestSet,
200 ModelFile, ModelManifest, ModelSource, RuntimeSpec, VerifiedFile, VerifiedModel, VisionTask,
201};
202pub use mask_decoder::{
203 DEFAULT_MASK_DECODER_TIMEOUT_SECS, MaskDecoderChoice, SAM_MASK_CODEC_MANIFEST, SamSettings,
204};
205pub use measure::{
206 Calibration, CalibrationSource, FiducialSpec, MEASUREMENT_VALIDITY, MeasuredGeometry,
207 Measurement,
208};
209pub use media::{
210 ArtifactLocator, DecodeLimits, DecodedImage, Frame, FrameMeta, FramePixels, FrameSourceId,
211 ImageRef, MediaScope, MediaStore, Provenance, SourceImage, VideoRef, artifact_uri,
212};
213#[cfg(feature = "nim")]
214pub use nim_cv::{
215 DEFAULT_MAX_INLINE_BYTES, DEFAULT_MIN_LAYOUT_CONFIDENCE, DEFAULT_REQUESTS_PER_MINUTE,
216 DEFAULT_TIMEOUT, GRAPHIC_ELEMENTS_MODEL, NIM_READER_ID, NimCvConfig, NimDocumentReader,
217 NimOcrModel, PAGE_ELEMENTS_MODEL, TABLE_STRUCTURE_MODEL,
218};
219#[cfg(feature = "ocr")]
220pub use ocr::{PpOcrReader, PpOcrV6Size};
221#[cfg(feature = "ocr-vl")]
222pub use ocr_vl::{PADDLEOCR_VL_MANIFEST, PP_DOCLAYOUT_MANIFEST, PaddleOcrVlReader, VlDevice};
223pub use redact::{
224 DEFAULT_FACE_DETECTOR, DEFAULT_PERSON_DETECTOR, FACE_MARGIN, FaceRedactor, PersonRedactor,
225 REDACTION_MARGIN,
226};
227pub use runtime::{
228 CallOptions, CallRecord, Edited, Escalation, Route, Trigger, VideoSource, VisionOutput,
229 VisionRuntime, VisionRuntimeBuilder,
230};
231#[cfg(feature = "sam")]
232pub use sam::{SamConfig, SamSegmenter, SamVideoTracker};
233pub use sent::{SentImage, VisionInput};
234#[cfg(feature = "stream")]
235pub use toolset::VISION_WATCH_TOOL;
236pub use toolset::{
237 ANSWER_ARTIFACT_PREFIX, EgressApproval, MAX_VIDEO_FRAMES, VISION_EGRESS_POLICY_REF,
238 VISION_TOOL_NAMES, VisionTool, VisionToolKind, VisionToolset, VisionToolsetBuilder,
239 answer_artifact_name,
240};
241#[cfg(feature = "track")]
242pub use track::{ByteTrackConfig, ByteTracker};
243pub use tracker::GreedyIouTracker;
244pub use traits::{
245 Block, BlockKind, DescribeRequest, DescribeSpec, Describer, Description, DetectQuery, Detector,
246 DocumentPage, DocumentReader, Editor, Embedder, EmbeddingSpace, ImageRegion, Metric,
247 ReadOptions, Sampling, SegmentPrompt, Segmenter, TableCell, Tracker, VideoAnalysis,
248 VideoAnalyzer, VideoEvent, VideoFrame, VideoInput, VideoPlan, VideoRequest, VideoUsage, Word,
249};
250pub use verify::{
251 ExpectedChange, LoopOutcome, Observation, Observer, RegionDiff, RegionExpectation,
252 VERIFICATION_TOOL, VerificationHold, VerificationReport, VerifiedAction, VerifierLoop,
253 check_change, diff_regions,
254};
255pub use video::{ClipInfo, MAX_CLIP_BYTES, SentClip, SourceClip, VideoCodec};
256#[cfg(feature = "cloud")]
257pub use video::{DEFAULT_CAPTION_INSTRUCTIONS, FramesAnalyzer, VisibilityPass};
258#[cfg(feature = "gemini-video")]
259pub use video::{GEMINI_INLINE_LIMIT, GeminiVideoAnalyzer, MediaResolution};
260pub use watch::{
261 FrameRef, TrackedObservation, VISION_WATCH_FIRED, VISION_WATCH_REGISTERED,
262 VISION_WATCH_STOPPED, WatchCondition, WatchEvaluator, WatchEvent, WatchEventKind, WatchSink,
263 Zone, ZoneAnchor, watch_registered_draft,
264};