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
//! Utilities for interacting with models endpoints.
//!
//! This includes the following:
//! - [Get a Model](https://replicate.com/docs/reference/http#models.get)
//! - [Get a Model Version](https://replicate.com/docs/reference/http#models.versions.get)
//! - [List a Model's Versions](https://replicate.com/docs/reference/http#models.versions.list)
//! - [List all Public Models](https://replicate.com/docs/reference/http#models.list)
//!
use anyhow::anyhow;
use futures_lite::io::AsyncReadExt;
use isahc::{prelude::*, Request};
use serde::Deserialize;
use serde_json::Value;

use crate::config::ReplicateConfig;

#[derive(Debug, Deserialize)]
struct ModelVersionError {
    detail: String,
}

/// Version details for a particular model
#[derive(Debug, Deserialize, Clone)]
pub struct ModelVersion {
    /// Id of the model
    pub id: String,
    /// Time in which the model was created
    pub created_at: String,
    /// Version of cog used to create the model
    pub cog_version: String,
    /// OpenAPI Schema of model input and outputs
    pub openapi_schema: serde_json::Value,
}

/// Paginated view of all versions for a particular model
#[derive(Debug, Deserialize)]
pub struct ModelVersions {
    /// Place in pagination
    pub next: Option<String>,
    /// Place in pagination
    pub previous: Option<String>,
    /// List of all versions available
    pub results: Vec<ModelVersion>,
}

/// Paginated view of all available models
#[derive(Debug, Deserialize)]
pub struct Models {
    /// Place in pagination
    pub next: Option<String>,
    /// Place in pagination
    pub previous: Option<String>,
    /// List of all versions available
    pub results: Vec<Model>,
}

/// All details available for a particular Model
#[derive(Deserialize, Debug)]
pub struct Model {
    /// URL for model homepage
    pub url: String,
    /// The owner of the model
    pub owner: String,
    /// The name of the model
    pub name: String,
    /// A brief description of the model
    pub description: String,
    /// Whether the model is public or private
    pub visibility: String,
    /// Github URL for the associated repo
    pub github_url: String,
    /// Url for an associated paper
    pub paper_url: Option<String>,
    /// Url for the model's license
    pub license_url: Option<String>,
    /// How many times the model has been run
    pub run_count: usize,
    /// Image URL to show on Replicate's Model page
    pub cover_image_url: String,
    /// A simple example to show model's use
    pub default_example: Value,
    /// The latest version's details
    pub latest_version: ModelVersion,
}

/// A client for interacting with `models` endpoints
pub struct ModelClient {
    client: ReplicateConfig,
}

impl ModelClient {
    /// Create a new `ModelClient` based upon a `ReplicateConfig` object
    pub fn from(client: ReplicateConfig) -> Self {
        ModelClient { client }
    }

    /// Retrieve details for a specific model
    pub async fn get(&self, owner: &str, name: &str) -> anyhow::Result<Model> {
        let api_key = self.client.get_api_key()?;
        let base_url = self.client.get_base_url();
        let endpoint = format!("{base_url}/models/{owner}/{name}");
        let response = Request::get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .body({})?
            .send_async()
            .await?;

        let mut bytes = Vec::new();
        response.into_body().read_to_end(&mut bytes).await?;

        let model: Model = serde_json::from_slice(&bytes)?;
        anyhow::Ok(model)
    }

    /// Retrieve details for a specific model's version
    pub async fn get_specific_version(
        &self,
        owner: &str,
        name: &str,
        version_id: &str,
    ) -> anyhow::Result<Model> {
        let api_key = self.client.get_api_key()?;
        let base_url = self.client.get_base_url();
        let endpoint = format!("{base_url}/models/{owner}/{name}/versions/{version_id}");
        let response = Request::get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .body({})?
            .send_async()
            .await?;

        let mut bytes = Vec::new();
        response.into_body().read_to_end(&mut bytes).await?;

        let model: Model = serde_json::from_slice(&bytes)?;
        anyhow::Ok(model)
    }

    /// Retrieve details for latest version of a specific model
    pub async fn get_latest_version(
        &self,
        owner: &str,
        name: &str,
    ) -> anyhow::Result<ModelVersion> {
        let all_versions = self.list_versions(owner, name).await?;
        let latest_version = all_versions
            .results
            .get(0)
            .ok_or(anyhow!("no versions found for {owner}/{name}"))?;
        anyhow::Ok(latest_version.clone())
    }

    /// Retrieve list of all available versions of a specific model
    pub async fn list_versions(&self, owner: &str, name: &str) -> anyhow::Result<ModelVersions> {
        let base_url = self.client.get_base_url();
        let api_key = self.client.get_api_key()?;
        let endpoint = format!("{base_url}/models/{owner}/{name}/versions");
        let mut response = Request::get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .body({})?
            .send_async()
            .await?;

        let mut bytes = Vec::new();
        response.body_mut().read_to_end(&mut bytes).await?;

        if response.status().is_success() {
            let data: ModelVersions = serde_json::from_slice(&bytes)?;
            anyhow::Ok(data)
        } else {
            let data: ModelVersionError = serde_json::from_slice(&bytes)?;
            Err(anyhow!(data.detail))
        }
    }

    /// Retrieve all publically and private available models
    pub async fn get_models(&self) -> anyhow::Result<Models> {
        let base_url = self.client.get_base_url();
        let api_key = self.client.get_api_key()?;
        let endpoint = format!("{base_url}/models");
        let mut response = Request::get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .body({})?
            .send_async()
            .await?;

        let mut bytes = Vec::new();
        response.body_mut().read_to_end(&mut bytes).await?;

        let models: Models = serde_json::from_slice(&bytes)?;
        anyhow::Ok(models)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::prelude::*;
    use serde_json::json;

    #[tokio::test]
    async fn test_get_model() {
        let mock_server = MockServer::start();

        let model_mock = mock_server.mock(|when, then| {
            when.method(GET).path("/models/replicate/hello-world");
            then.status(200).json_body_obj(&json!({
                "url": "https://replicate.com/replicate/hello-world",
                "owner": "replicate",
                "name": "hello-world",
                "description": "A tiny model that says hello",
                "visibility": "public",
                "github_url": "https://github.com/replicate/cog-examples",
                "paper_url": null,
                "license_url": null,
                "run_count": 5681081,
                "cover_image_url": "...",
                "default_example": null,
                "latest_version": {
                    "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": {}
                }
            }));
        });

        let client = ReplicateConfig::test(mock_server.base_url()).unwrap();
        let model_client = ModelClient::from(client);
        model_client.get("replicate", "hello-world").await.unwrap();

        model_mock.assert();
    }

    #[tokio::test]
    async fn test_get_specific_version() {
        let mock_server = MockServer::start();

        let model_mock = mock_server.mock(|when, then| {
            when.method(GET)
                .path("/models/replicate/hello-world/versions/1234");
            then.status(200).json_body_obj(&json!({
                "url": "https://replicate.com/replicate/hello-world",
                "owner": "replicate",
                "name": "hello-world",
                "description": "A tiny model that says hello",
                "visibility": "public",
                "github_url": "https://github.com/replicate/cog-examples",
                "paper_url": null,
                "license_url": null,
                "run_count": 5681081,
                "cover_image_url": "...",
                "default_example": null,
                "latest_version": {
                    "id": "1234",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": {}
                }
            }));
        });

        let client = ReplicateConfig::test(mock_server.base_url()).unwrap();
        let model_client = ModelClient::from(client);
        model_client
            .get_specific_version("replicate", "hello-world", "1234")
            .await
            .unwrap();

        model_mock.assert();
    }
    #[tokio::test]
    async fn test_list_model_versions() {
        let mock_server = MockServer::start();

        // Model endpoints
        let model_mock = mock_server.mock(|when, then| {
            when.method(GET)
                .path("/models/replicate/hello-world/versions");

            then.status(200).json_body_obj(&json!({
                "next": null,
                "previous": null,
                "results": [{
                    "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": null
                }]
            }));
        });

        let client = ReplicateConfig::test(mock_server.base_url()).unwrap();
        let model_client = ModelClient::from(client);
        model_client
            .list_versions("replicate", "hello-world")
            .await
            .unwrap();

        model_mock.assert();
    }

    #[tokio::test]
    async fn test_get_latest_version() {
        let mock_server = MockServer::start();

        // Model endpoints
        let model_mock = mock_server.mock(|when, then| {
            when.method(GET)
                .path("/models/replicate/hello-world/versions");

            then.status(200).json_body_obj(&json!({
                "next": null,
                "previous": null,
                "results": [{
                    "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": null
                }]
            }));
        });

        let client = ReplicateConfig::test(mock_server.base_url()).unwrap();
        let model_client = ModelClient::from(client);
        model_client
            .get_latest_version("replicate", "hello-world")
            .await
            .unwrap();

        model_mock.assert();
    }

    #[tokio::test]
    async fn test_get_models() {
        let mock_server = MockServer::start();

        // Model endpoints
        let model_mock = mock_server.mock(|when, then| {
            when.method(GET).path("/models");
            then.status(200).json_body_obj(&json!({
                    "next": "some pagination string or null",
                    "previous": "some pagination string or null",
            "results": [
                {
                "url": "https://modelhomepage.example.com",
                "owner": "jdoe",
                "name": "super-cool-model",
                "description": "A model that predicts something very cool.",
                "visibility": "public",
                "github_url": "https://github.com/jdoe/super-cool-model",
                "paper_url": "https://research.example.com/super-cool-model-paper.pdf",
                "license_url": null,
                "run_count": 420,
                "cover_image_url": "https://cdn.example.com/images/super-cool-model-cover.jpg",
                "default_example": {
                    "input": "Example input data for the model."
                },
                "latest_version": {
                    "id": "v1.0.0",
                    "created_at": "2022-01-01T12:00:00Z",
                    "cog_version": "0.2",
                    "openapi_schema": null
                }
                },
                {
                "url": "https://anothermodelhomepage.example.com",
                "owner": "asmith",
                "name": "another-awesome-model",
                "description": "This model does awesome things with data.",
                "visibility": "private",
                "github_url": "https://github.com/asmith/another-awesome-model",
                "paper_url": null,
                "license_url": "https://licenses.example.com/another-awesome-model-license.txt",
                "run_count": 150,
                "cover_image_url": "https://cdn.example.com/images/another-awesome-model-cover.jpg",
                "default_example": {
                    "input": "Some example input for this awesome model."
                },
                "latest_version": {
                    "id": "v1.2.3",
                    "created_at": "2023-02-15T08:30:00Z",
                    "cog_version": "0.2",
                    "openapi_schema": null
                }
            }
        ]}));
        });

        let client = ReplicateConfig::test(mock_server.base_url()).unwrap();
        let model_client = ModelClient::from(client);
        model_client.get_models().await.unwrap();

        model_mock.assert();
    }
}