apple_vision/animals/
mod.rs1use core::ffi::c_char;
6use core::ptr;
7use std::ffi::CString;
8use std::path::Path;
9
10use crate::error::{from_swift, VisionError};
11use crate::ffi;
12use crate::recognize_text::BoundingBox;
13use crate::sdk;
14
15pub type AnimalIdentifier = sdk::AnimalIdentifier;
17
18#[derive(Debug, Clone, PartialEq)]
20pub struct RecognizedAnimal {
21 pub identifier: String,
23 pub confidence: f32,
24 pub bounding_box: BoundingBox,
25}
26
27impl RecognizedAnimal {
28 #[must_use]
29 pub fn identifier_kind(&self) -> Option<AnimalIdentifier> {
30 AnimalIdentifier::from_str(&self.identifier)
31 }
32}
33
34pub fn recognize_animals_in_path(
40 path: impl AsRef<Path>,
41) -> Result<Vec<RecognizedAnimal>, VisionError> {
42 let path_str = path
43 .as_ref()
44 .to_str()
45 .ok_or_else(|| VisionError::InvalidArgument("non-UTF-8 path".into()))?;
46 let path_c = CString::new(path_str)
47 .map_err(|e| VisionError::InvalidArgument(format!("path NUL byte: {e}")))?;
48
49 let mut out_array: *mut core::ffi::c_void = ptr::null_mut();
50 let mut out_count: usize = 0;
51 let mut err_msg: *mut c_char = ptr::null_mut();
52 let status = unsafe {
54 ffi::vn_recognize_animals_in_path(
55 path_c.as_ptr(),
56 &mut out_array,
57 &mut out_count,
58 &mut err_msg,
59 )
60 };
61 if status != ffi::status::OK {
62 return Err(unsafe { from_swift(status, err_msg) });
64 }
65 if out_array.is_null() || out_count == 0 {
66 return Ok(Vec::new());
67 }
68 let typed = out_array.cast::<ffi::RecognizedAnimalRaw>();
69 let mut v = Vec::with_capacity(out_count);
70 for i in 0..out_count {
71 let raw = unsafe { &*typed.add(i) };
73 let identifier = if raw.identifier.is_null() {
74 String::new()
75 } else {
76 unsafe { core::ffi::CStr::from_ptr(raw.identifier) }
78 .to_string_lossy()
79 .into_owned()
80 };
81 v.push(RecognizedAnimal {
82 identifier,
83 confidence: raw.confidence,
84 bounding_box: BoundingBox {
85 x: raw.bbox_x,
86 y: raw.bbox_y,
87 width: raw.bbox_w,
88 height: raw.bbox_h,
89 },
90 });
91 }
92 unsafe { ffi::vn_recognized_animals_free(out_array, out_count) };
94 Ok(v)
95}