Skip to main content

jams_client/
common.rs

1use serde::Deserialize;
2use std::collections::HashMap;
3
4#[derive(Deserialize, Debug)]
5pub struct GetModelsResponse {
6    /// Total number of models.
7    pub total: i32,
8    /// List of model names.
9    pub models: Vec<Metadata>,
10}
11#[derive(Deserialize, Debug)]
12pub struct Metadata {
13    pub name: String,
14    pub framework: String,
15    pub path: String,
16    pub last_updated: String,
17}
18
19#[derive(Deserialize, Clone, Debug)]
20pub struct Predictions(HashMap<String, Vec<Vec<f64>>>);
21
22impl Predictions {
23    #[allow(clippy::should_implement_trait)]
24    pub fn from_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
25        let predictions: Predictions = serde_json::from_slice(bytes)?;
26        Ok(predictions)
27    }
28
29    #[allow(clippy::wrong_self_convention)]
30    pub fn to_vec(self) -> Vec<Vec<f64>> {
31        self.0
32            .values()
33            .flat_map(|vecs| vecs.iter().cloned())
34            .collect()
35    }
36}
37
38pub fn get_url(base_url: String) -> String {
39    if base_url.starts_with("http://") || base_url.starts_with("https://") {
40        return base_url;
41    }
42    format!("http://{}", base_url)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn successfully_parses_bytes_into_predictions() {
51        // Act
52        let data= "{\"predictions\":[[0.7560540820707359],[1.152310804888906],[0.45694264204906754],[0.912618828350997],[0.08037521123549339],[0.8689713450910137],[0.4549892870109407],[0.5386298352854039],[0.471754086353748],[0.18414340024741896]]}".to_string();
53
54        // Arrange
55        let result = Predictions::from_bytes(data.as_bytes());
56
57        // Assert
58        assert!(result.is_ok())
59    }
60
61    #[test]
62    fn successfully_converts_predictions_into_2d_vector() {
63        // Act
64        let data= "{\"predictions\":[[0.7560540820707359],[1.152310804888906],[0.45694264204906754],[0.912618828350997],[0.08037521123549339],[0.8689713450910137],[0.4549892870109407],[0.5386298352854039],[0.471754086353748],[0.18414340024741896]]}".to_string();
65
66        // Arrange
67        let result = Predictions::from_bytes(data.as_bytes());
68
69        // Assert
70        assert!(result.is_ok());
71        let vec = result.unwrap().to_vec();
72        assert_eq!(vec.len(), 10);
73    }
74
75    #[test]
76    fn fails_to_parse_bytes_into_predictions() {
77        // Act
78        let data = "unsupported string value".to_string();
79
80        // Arrange
81        let result = Predictions::from_bytes(data.as_bytes());
82
83        // Assert
84        assert!(result.is_err())
85    }
86}