m.rs 1.7 KB
Newer Older
yongshk's avatar
yongshk committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use candle_wasm_example_yolo::coco_classes;
use candle_wasm_example_yolo::model::Bbox;
use candle_wasm_example_yolo::worker::Model as M;
use candle_wasm_example_yolo::worker::ModelPose as P;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Model {
    inner: M,
}

#[wasm_bindgen]
impl Model {
    #[wasm_bindgen(constructor)]
    pub fn new(data: Vec<u8>, model_size: &str) -> Result<Model, JsError> {
        let inner = M::load_(data, model_size)?;
        Ok(Self { inner })
    }

    #[wasm_bindgen]
    pub fn run(
        &self,
        image: Vec<u8>,
        conf_threshold: f32,
        iou_threshold: f32,
    ) -> Result<String, JsError> {
        let bboxes = self.inner.run(image, conf_threshold, iou_threshold)?;
        let mut detections: Vec<(String, Bbox)> = vec![];

        for (class_index, bboxes_for_class) in bboxes.into_iter().enumerate() {
            for b in bboxes_for_class.into_iter() {
                detections.push((coco_classes::NAMES[class_index].to_string(), b));
            }
        }
        let json = serde_json::to_string(&detections)?;
        Ok(json)
    }
}

#[wasm_bindgen]
pub struct ModelPose {
    inner: P,
}

#[wasm_bindgen]
impl ModelPose {
    #[wasm_bindgen(constructor)]
    pub fn new(data: Vec<u8>, model_size: &str) -> Result<ModelPose, JsError> {
        let inner = P::load_(data, model_size)?;
        Ok(Self { inner })
    }

    #[wasm_bindgen]
    pub fn run(
        &self,
        image: Vec<u8>,
        conf_threshold: f32,
        iou_threshold: f32,
    ) -> Result<String, JsError> {
        let bboxes = self.inner.run(image, conf_threshold, iou_threshold)?;
        let json = serde_json::to_string(&bboxes)?;
        Ok(json)
    }
}

fn main() {}