moondream 0.1.0

Client for interacting with the Moondream API
Documentation
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Client for the [Moondream](https://moondream.ai/) vision API.
//!
//! Provides a simple wrapper around the Moondream HTTP endpoints. It is used to 
//! detect objects in images, generate captions and answer visual questions. Examples 
//! are available in the `examples` directory.

use derive_new::new;
use derive_setters::Setters;
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;

/// Errors returned by the [`MoonDream`] client when performing HTTP requests.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Wrapper around [`reqwest::Error`].
    #[error("MoonDream Error: {0}")]
    PointError(#[from] reqwest::Error),
}

/// Client for interacting with the [Moondream API](https://moondream.ai/).
///
/// Use [`MoonDream::remote`] when you have an API key or [`MoonDream::local`]
/// for unauthenticated local deployments. The client exposes helper methods for
/// the `/point`, `/detect`, `/caption` and `/query` endpoints.
#[derive(Debug, new, Setters, Clone)]
#[setters(prefix = "with_", into, strip_option)]
pub struct MoonDream {
    #[setters(skip)]
    token: String,

    #[new(value = "String::from(\"https://api.moondream.ai/v1\")")]
    endpoint: String,

    #[new(default)]
    headers: Vec<(String, String)>,

    #[new(value = "Duration::from_secs(5)")]
    timeout: Duration,

    #[new(value = "reqwest::Client::new()")]
    client: reqwest::Client,
}

/// Response returned by the `/point` endpoint.
///
/// Contains the request identifier, a list of centre [`Point`]s for each
/// detected object and an optional count of how many were found.
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct PointsResponse {
    /// Unique request identifier returned by the API.
    pub request_id: Option<String>,
    /// List of centre coordinates for each detected object.
    pub points: Vec<Point>,
    /// Number of points returned by the API.
    pub count: Option<usize>,
}

/// Response returned by the `/detect` endpoint.
///
/// Includes the request id and the bounding boxes for all detected objects.
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct DetectResponse {
    /// Unique request identifier returned by the API.
    pub request_id: Option<String>,
    /// Bounding boxes for each detected object.
    pub objects: Vec<DetectionObject>,
}

/// Bounding box coordinates for a detected object.
///
/// Values are normalized to the image dimensions (0-1). To convert them to
/// pixels multiply by the width and height of the source image.
#[derive(Debug, Deserialize, PartialOrd, PartialEq, Clone)]
pub struct DetectionObject {
    /// Left boundary of the box (normalized 0-1).
    pub x_min: f64,
    /// Top boundary of the box (normalized 0-1).
    pub y_min: f64,
    /// Right boundary of the box (normalized 0-1).
    pub x_max: f64,
    /// Bottom boundary of the box (normalized 0-1).
    pub y_max: f64,
}

/// Centre point coordinates returned by the `/point` endpoint.
///
/// Values are normalized to the image dimensions (0-1). To convert them to
/// pixels multiply by the width and height of the source image.
#[derive(Debug, Deserialize, PartialOrd, PartialEq, Clone)]
pub struct Point {
    /// Normalized X coordinate.
    pub x: f64,
    /// Normalized Y coordinate.
    pub y: f64,
}

/// Response from the `/query` endpoint (Visual Question Answering).
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct QueryResponse {
    /// Unique request identifier returned by the API.
    pub request_id: Option<String>,
    /// Answer returned for the asked question.
    pub answer: String,
}

impl MoonDream {
    /// Create a [`MoonDream`] instance for a local service.
    ///
    /// Use this when the API does not require authentication and you want to
    /// specify the service endpoint directly.
    pub fn local(endpoint: impl Into<String>) -> Self {
        MoonDream::new(String::new()).with_endpoint(endpoint)
    }

    /// Create a [`MoonDream`] instance for the hosted service.
    ///
    /// Provide the authentication token returned by the remote provider.
    pub fn remote(token: impl Into<String>) -> Self {
        MoonDream::new(token.into())
    }

    pub async fn points(
        &self,
        image: impl Into<String>,
        object: impl Into<String>,
    ) -> Result<PointsResponse, Error> {
        let object = object.into();
        let image = image.into();

        let result = self
            .client
            .post(format!("{}/point", self.endpoint))
            .header("X-Moondream-Auth", &self.token)
            .timeout(self.timeout.clone())
            .json(&json!({
                "image_url": image,
                "object": object,
            }))
            .send()
            .await?
            .error_for_status()?;
        Ok(result.json().await?)
    }

    pub async fn detect(
        &self,
        image: impl Into<String>,
        object: impl Into<String>,
    ) -> Result<DetectResponse, Error> {
        let object = object.into();
        let image = image.into();

        let result = self
            .client
            .post(format!("{}/detect", self.endpoint))
            .header("X-Moondream-Auth", &self.token)
            .timeout(self.timeout.clone())
            .json(&json!({
                "image_url": image,
                "object": object,
            }))
            .send()
            .await?
            .error_for_status()?;
        Ok(result.json().await?)
    }

    pub async fn caption(
        &self,
        image: impl Into<String>,
        length: Option<CaptionLength>,
    ) -> Result<CaptionResponse, Error> {
        let image = image.into();
        let length = length.unwrap_or(CaptionLength::Normal);

        let result = self
            .client
            .post(format!("{}/caption", self.endpoint))
            .header("X-Moondream-Auth", &self.token)
            .timeout(self.timeout.clone())
            .json(&json!({
                "image_url": image,
                "length": length.as_str(),
            }))
            .send()
            .await?
            .error_for_status()?;
        Ok(result.json().await?)
    }

    pub async fn query(
        &self,
        image: impl Into<String>,
        question: impl Into<String>,
    ) -> Result<QueryResponse, Error> {
        let image = image.into();
        let question = question.into();

        let result = self
            .client
            .post(format!("{}/query", self.endpoint))
            .header("X-Moondream-Auth", &self.token)
            .timeout(self.timeout.clone())
            .json(&json!({
                "image_url": image,
                "question": question,
            }))
            .send()
            .await?
            .error_for_status()?;
        Ok(result.json().await?)
    }
}

/// Controls the length of the caption returned by [`MoonDream::caption`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptionLength {
    /// A brief caption.
    Short,
    /// A normal length caption.
    Normal,
}

impl CaptionLength {
    fn as_str(&self) -> &'static str {
        match self {
            CaptionLength::Short => "short",
            CaptionLength::Normal => "normal",
        }
    }
}

/// Response from the `/caption` endpoint.
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct CaptionResponse {
    /// Unique request identifier returned by the API.
    pub request_id: Option<String>,
    /// The generated caption text.
    pub caption: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_points_response_deserialization() {
        let json = r#"{
            "request_id": "abc",
            "points": [{"x": 0.1, "y": 0.2}],
            "count": 1
        }"#;

        let resp: PointsResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.request_id, Some("abc".to_string()));
        assert_eq!(resp.points, vec![Point { x: 0.1, y: 0.2 }]);
        assert_eq!(resp.count, Some(1));
    }

    #[tokio::test]
    async fn test_points_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "abc",
            "points": [{"x": 0.5, "y": 0.5}],
            "count": 1
        });

        Mock::given(method("POST"))
            .and(path("/point"))
            .and(header("x-moondream-auth", "token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::new("token".to_string()).with_endpoint(server.uri());

        let resp = md
            .points("data:image/png;base64,AAA", "object")
            .await
            .unwrap();

        assert_eq!(
            resp,
            PointsResponse {
                request_id: Some("abc".to_string()),
                points: vec![Point { x: 0.5, y: 0.5 }],
                count: Some(1),
            }
        );
    }

    #[tokio::test]
    async fn test_detect_response_deserialization() {
        let json = r#"{
            "request_id": "req1",
            "objects": [{"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4}]
        }"#;

        let resp: DetectResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.request_id, Some("req1".to_string()));
        assert_eq!(
            resp.objects,
            vec![DetectionObject {
                x_min: 0.1,
                y_min: 0.2,
                x_max: 0.3,
                y_max: 0.4
            }]
        );
    }

    #[tokio::test]
    async fn test_detect_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "req1",
            "objects": [{"x_min": 0.1, "y_min": 0.2, "x_max": 0.3, "y_max": 0.4}]
        });

        Mock::given(method("POST"))
            .and(path("/detect"))
            .and(header("x-moondream-auth", "token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::new("token".to_string()).with_endpoint(server.uri());

        let resp = md
            .detect("data:image/png;base64,AAA", "object")
            .await
            .unwrap();

        assert_eq!(
            resp,
            DetectResponse {
                request_id: Some("req1".to_string()),
                objects: vec![DetectionObject {
                    x_min: 0.1,
                    y_min: 0.2,
                    x_max: 0.3,
                    y_max: 0.4
                }],
            }
        );
    }

    #[tokio::test]
    async fn test_caption_response_deserialization() {
        let json = r#"{
            "request_id": "req2",
            "caption": "a cat on a mat"
        }"#;

        let resp: CaptionResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.request_id, Some("req2".to_string()));
        assert_eq!(resp.caption, "a cat on a mat".to_string());
    }

    #[tokio::test]
    async fn test_caption_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "req2",
            "caption": "a cat on a mat"
        });

        Mock::given(method("POST"))
            .and(path("/caption"))
            .and(header("x-moondream-auth", "token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::new("token".to_string()).with_endpoint(server.uri());

        let resp = md
            .caption("data:image/png;base64,AAA", Some(CaptionLength::Normal))
            .await
            .unwrap();

        assert_eq!(
            resp,
            CaptionResponse {
                request_id: Some("req2".to_string()),
                caption: "a cat on a mat".to_string(),
            }
        );
    }

    #[tokio::test]
    async fn test_query_response_deserialization() {
        let json = r#"{
            "request_id": "req3",
            "answer": "It is a cat"
        }"#;

        let resp: QueryResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.request_id, Some("req3".to_string()));
        assert_eq!(resp.answer, "It is a cat".to_string());
    }

    #[tokio::test]
    async fn test_query_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "req3",
            "answer": "It is a cat"
        });

        Mock::given(method("POST"))
            .and(path("/query"))
            .and(header("x-moondream-auth", "token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::new("token".to_string()).with_endpoint(server.uri());

        let resp = md
            .query("data:image/png;base64,AAA", "What is this?")
            .await
            .unwrap();

        assert_eq!(
            resp,
            QueryResponse {
                request_id: Some("req3".to_string()),
                answer: "It is a cat".to_string(),
            }
        );
    }

    #[test]
    fn test_caption_length_as_str() {
        assert_eq!(CaptionLength::Short.as_str(), "short");
        assert_eq!(CaptionLength::Normal.as_str(), "normal");
    }

    #[test]
    fn test_constructors_and_setters() {
        let md_local = MoonDream::local("http://localhost:8080");
        assert_eq!(md_local.token, "");
        assert_eq!(md_local.endpoint, "http://localhost:8080".to_string());

        let md_remote = MoonDream::remote("secret");
        assert_eq!(md_remote.token, "secret".to_string());
        assert_eq!(
            md_remote.endpoint,
            "https://api.moondream.ai/v1".to_string()
        );

        let md_timeout = md_remote.clone().with_timeout(Duration::from_secs(10));
        assert_eq!(md_timeout.timeout, Duration::from_secs(10));
    }

    #[tokio::test]
    async fn test_query_remote_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "req4",
            "answer": "Remote answer",
        });

        Mock::given(method("POST"))
            .and(path("/query"))
            .and(header("x-moondream-auth", "token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::remote("token").with_endpoint(server.uri());

        let resp = md
            .query("data:image/png;base64,AAA", "What is this?")
            .await
            .unwrap();

        assert_eq!(
            resp,
            QueryResponse {
                request_id: Some("req4".to_string()),
                answer: "Remote answer".to_string(),
            }
        );
    }

    #[tokio::test]
    async fn test_points_local_functional() {
        let server = MockServer::start().await;

        let body = serde_json::json!({
            "request_id": "abc",
            "points": [{"x": 0.5, "y": 0.5}],
            "count": 1
        });

        Mock::given(method("POST"))
            .and(path("/point"))
            .and(header("x-moondream-auth", ""))
            .respond_with(ResponseTemplate::new(200).set_body_json(&body))
            .mount(&server)
            .await;

        let md = MoonDream::local(server.uri());

        let resp = md
            .points("data:image/png;base64,AAA", "object")
            .await
            .unwrap();

        assert_eq!(
            resp,
            PointsResponse {
                request_id: Some("abc".to_string()),
                points: vec![Point { x: 0.5, y: 0.5 }],
                count: Some(1),
            }
        );
    }
}