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
use anyhow::Context;
use async_trait::async_trait;
use comfyui_api::{comfy::getter::*, models::AsAny};
use dyn_clone::DynClone;
use stable_diffusion_api::{Img2ImgRequest, Txt2ImgRequest};

use crate::{ComfyParams, Img2ImgParams, Txt2ImgParams};

/// Struct representing a response from a Stable Diffusion API image generation endpoint.
#[derive(Debug, Clone)]
pub struct Response {
    /// A vector of images.
    pub images: Vec<Vec<u8>>,
    /// The parameters describing the generated image.
    pub params: Box<dyn crate::image_params::ImageParams>,
    /// The parameters that were provided for the generation request.
    pub gen_params: Box<dyn crate::gen_params::GenParams>,
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum ComfyPromptApiError {
    /// Error creating a ComfyUI Client
    #[error("Error creating a ComfyUI Client")]
    CreateClient(#[from] comfyui_api::comfy::ComfyApiError),
}

/// Struct wrapping a connection to the ComfyUI API.
#[derive(Debug, Clone, Default)]
pub struct ComfyPromptApi {
    /// The ComfyUI client.
    pub client: comfyui_api::comfy::Comfy,
    /// Default parameters for the ComfyUI API.
    pub params: crate::gen_params::ComfyParams,
    /// The output node.
    pub output_node: Option<String>,
    /// The prompt node.
    pub prompt_node: Option<String>,
}

impl ComfyPromptApi {
    /// Constructs a new `ComfyPromptApi` client with the provided prompt.
    ///
    /// # Arguments
    ///
    /// * `prompt` - The prompt to use for the API.
    ///
    /// # Returns
    ///
    /// A new `ComfyPromptApi` instance on success, or an error if there was a failure in the ComfyUI API client.
    pub fn new(prompt: comfyui_api::models::Prompt) -> Result<Self, ComfyPromptApiError> {
        Ok(Self {
            client: comfyui_api::comfy::Comfy::new()?,
            params: crate::gen_params::ComfyParams {
                prompt: Some(prompt),
                count: 1,
                seed: Some(-1),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    /// Constructs a new `ComfyPromptApi` client with the provided url and prompt.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to use for the API. Must be a valid URL, e.g. `http://localhost:8188
    /// * `prompt` - The prompt to use for the API.
    ///
    /// # Returns
    ///
    /// A new `ComfyPromptApi` instance on success, or an error if there was a failure in the ComfyUI API client.
    pub fn new_with_url<S>(
        url: S,
        prompt: comfyui_api::models::Prompt,
    ) -> Result<Self, ComfyPromptApiError>
    where
        S: AsRef<str>,
    {
        Ok(Self {
            client: comfyui_api::comfy::Comfy::new_with_url(url)?,
            params: crate::gen_params::ComfyParams {
                prompt: Some(prompt),
                count: 1,
                seed: Some(-1),
                ..Default::default()
            },
            ..Default::default()
        })
    }

    /// Constructs a new `ComfyPromptApi` client with the provided url and prompt.
    ///
    /// # Arguments
    ///
    /// * `client` - An instance of `reqwest::Client`.
    /// * `url` - The URL to use for the API. Must be a valid URL, e.g. `http://localhost:8188
    /// * `prompt` - The prompt to use for the API.
    ///
    /// # Returns
    ///
    /// A new `ComfyPromptApi` instance on success, or an error if there was a failure in the ComfyUI API client.
    pub fn new_with_client_and_url<S>(
        client: reqwest::Client,
        url: S,
        prompt: comfyui_api::models::Prompt,
    ) -> anyhow::Result<Self>
    where
        S: AsRef<str>,
    {
        Ok(Self {
            client: comfyui_api::comfy::Comfy::new_with_client_and_url(client, url)?,
            params: crate::gen_params::ComfyParams {
                prompt: Some(prompt),
                count: 1,
                seed: Some(-1),
                ..Default::default()
            },
            ..Default::default()
        })
    }
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Txt2ImgApiError {
    /// Prompt was empty.
    #[error("Prompt was empty.")]
    EmptyPrompt,
    /// Error running txt2img.
    #[error("Error running txt2img.")]
    Txt2Img(#[from] anyhow::Error),
    /// Error parsing response.
    #[error("Error parsing response.")]
    ParseResponse(#[source] anyhow::Error),
}

dyn_clone::clone_trait_object!(Txt2ImgApi);

/// Trait representing a Txt2Img endpoint.
#[async_trait]
pub trait Txt2ImgApi: std::fmt::Debug + DynClone + Send + Sync + AsAny {
    /// Generates an image using text-to-image.
    ///
    /// # Arguments
    ///
    /// * `config` - The configuration to use for the generation.
    ///
    /// # Returns
    ///
    /// A `Result` containing a `Response` on success, or an error if the request failed.
    async fn txt2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Txt2ImgApiError>;

    /// Returns the default generation parameters for this endpoint.
    ///
    /// # Arguments
    ///
    /// * `user_settings` - The user settings to merge with the defaults.
    ///
    /// # Returns
    ///
    /// A `Box<dyn crate::gen_params::GenParams>` containing the generation parameters.
    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams>;
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Img2ImgApiError {
    /// Prompt was empty.
    #[error("Prompt was empty.")]
    EmptyPrompt,
    /// Error running txt2img.
    #[error("Error running img2img.")]
    Img2Img(#[from] anyhow::Error),
    /// Error parsing response.
    #[error("Error parsing response.")]
    ParseResponse(#[source] anyhow::Error),
    /// No image provided.
    #[error("No image provided.")]
    NoImage,
    /// Error uploading image.
    #[error("Error uploading image.")]
    UploadImage(#[source] anyhow::Error),
}

dyn_clone::clone_trait_object!(Img2ImgApi);

/// Trait representing an Img2Img endpoint.
#[async_trait]
pub trait Img2ImgApi: std::fmt::Debug + DynClone + Send + Sync + AsAny {
    /// Generates an image using image-to-image.
    ///
    /// # Arguments
    ///
    /// * `config` - The configuration to use for the generation.
    ///
    /// # Returns
    ///
    /// A `Result` containing a `Response` on success, or an error if the request failed.
    async fn img2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Img2ImgApiError>;

    /// Returns the default generation parameters for this endpoint.
    ///
    /// # Arguments
    ///
    /// * `user_settings` - The user settings to merge with the defaults.
    ///
    /// # Returns
    ///
    /// A `Box<dyn crate::gen_params::GenParams>` containing the generation parameters.
    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams>;
}

#[async_trait]
impl Txt2ImgApi for ComfyPromptApi {
    async fn txt2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Txt2ImgApiError> {
        let base_prompt = config.as_any().downcast_ref().unwrap_or(&self.params);

        let mut new_prompt = base_prompt.clone();
        if let Some(-1) = new_prompt.seed {
            new_prompt.seed = Some(rand::random::<i64>().abs());
        }

        let prompt = new_prompt.apply().context(Txt2ImgApiError::EmptyPrompt)?;

        let images = self
            .client
            .execute_prompt(&prompt)
            .await
            .context("Failed to execute prompt")?;
        Ok(Response {
            images: images.into_iter().map(|image| image.image).collect(),
            params: Box::new(prompt),
            gen_params: Box::new(base_prompt.clone()),
        })
    }

    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams> {
        if let Some(user_settings) = user_settings {
            let mut params = ComfyParams::from(user_settings);
            params.prompt = self.params.prompt.clone();
            Box::new(params)
        } else {
            Box::new(self.params.clone())
        }
    }
}

#[async_trait]
impl Img2ImgApi for ComfyPromptApi {
    async fn img2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Img2ImgApiError> {
        let base_prompt = config.as_any().downcast_ref().unwrap_or(&self.params);

        let resp = if let Some(image) = &base_prompt.image {
            self.client
                .upload_file(image.clone())
                .await
                .context("Failed to upload image")
                .map_err(Img2ImgApiError::UploadImage)?
        } else {
            return Err(Img2ImgApiError::NoImage);
        };

        let mut new_prompt = base_prompt.clone();
        if let Some(-1) = new_prompt.seed {
            new_prompt.seed = Some(rand::random::<i64>().abs());
        }

        let mut prompt = new_prompt.apply().context(Img2ImgApiError::EmptyPrompt)?;

        *prompt.image_mut()? = resp.name;

        let images = self
            .client
            .execute_prompt(&prompt)
            .await
            .context("Failed to execute prompt")?;
        Ok(Response {
            images: images.into_iter().map(|image| image.image).collect(),
            params: Box::new(prompt.clone()),
            gen_params: Box::new(base_prompt.clone()),
        })
    }

    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams> {
        if let Some(user_settings) = user_settings {
            let mut params = ComfyParams::from(user_settings);
            params.prompt = self.params.prompt.clone();
            Box::new(params)
        } else {
            Box::new(self.params.clone())
        }
    }
}

/// Struct wrapping a connection to the Stable Diffusion WebUI API.
#[derive(Debug, Clone, Default)]
pub struct StableDiffusionWebUiApi {
    /// The Stable Diffusion WebUI client.
    pub client: stable_diffusion_api::Api,
    /// Default parameters for the Txt2Img endpoint.
    pub txt2img_defaults: Txt2ImgRequest,
    /// Default parameters for the Img2Img endpoint.
    pub img2img_defaults: Img2ImgRequest,
}

impl StableDiffusionWebUiApi {
    /// Constructs a new `StableDiffusionWebUiApi` client with the default parameters.
    pub fn new() -> Self {
        Self::default()
    }
}

#[async_trait]
impl Txt2ImgApi for StableDiffusionWebUiApi {
    async fn txt2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Txt2ImgApiError> {
        let config = Txt2ImgParams::from(config);
        let txt2img = self
            .client
            .txt2img()
            .context("Failed to open txt2img API")?;
        let resp = txt2img
            .send(&config.user_params)
            .await
            .context("Failed to send request")?;
        let params = Box::new(
            resp.info()
                .context("Failed to parse info from response")
                .map_err(Txt2ImgApiError::ParseResponse)?,
        );
        Ok(Response {
            images: resp
                .images()
                .context("Failed to parse image from response")
                .map_err(Txt2ImgApiError::ParseResponse)?,
            params: params.clone(),
            gen_params: Box::new(Txt2ImgParams {
                user_params: resp.parameters.clone(),
                defaults: Some(self.txt2img_defaults.clone()),
            }),
        })
    }

    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams> {
        if let Some(user_settings) = user_settings {
            Box::new(Txt2ImgParams {
                user_params: Txt2ImgParams::from(user_settings).user_params,
                defaults: Some(self.txt2img_defaults.clone()),
            })
        } else {
            Box::new(Txt2ImgParams {
                user_params: Txt2ImgRequest::default(),
                defaults: Some(self.txt2img_defaults.clone()),
            })
        }
    }
}

#[async_trait]
impl Img2ImgApi for StableDiffusionWebUiApi {
    async fn img2img(
        &self,
        config: &dyn crate::gen_params::GenParams,
    ) -> Result<Response, Img2ImgApiError> {
        let config = Img2ImgParams::from(config);
        let img2img = self
            .client
            .img2img()
            .context("Failed to open img2img API")?;
        let resp = img2img
            .send(&config.user_params)
            .await
            .context("Failed to send request")?;
        let params = Box::new(
            resp.info()
                .context("Failed to parse info from response")
                .map_err(Img2ImgApiError::ParseResponse)?,
        );
        Ok(Response {
            images: resp
                .images()
                .context("Failed to parse image from response")
                .map_err(Img2ImgApiError::ParseResponse)?,
            params: params.clone(),
            gen_params: Box::new(Img2ImgParams {
                user_params: resp.parameters.clone(),
                defaults: Some(self.img2img_defaults.clone()),
            }),
        })
    }

    fn gen_params(
        &self,
        user_settings: Option<&dyn crate::gen_params::GenParams>,
    ) -> Box<dyn crate::gen_params::GenParams> {
        if let Some(user_settings) = user_settings {
            Box::new(Txt2ImgParams {
                user_params: Txt2ImgParams::from(user_settings).user_params,
                defaults: Some(self.txt2img_defaults.clone()),
            })
        } else {
            Box::new(Txt2ImgParams {
                user_params: Txt2ImgRequest::default(),
                defaults: Some(self.txt2img_defaults.clone()),
            })
        }
    }
}