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
use anyhow::Result;
use reqwest::header;
use reqwest::Client as ReqClient;
use std::fmt;
use crate::request::{
ControlNetRequest, EditImageRequest, ImageToImageRequest, RepaintImageRequest,
TextToImageRequest,
};
use crate::response::ToImageResponse;
// Constants
pub(crate) const BASE_URL: &str = "https://api.getimg.ai/v1";
/// GetImg API client structure.
#[derive(Clone)]
pub struct Client {
/// Reqwest client instance.
pub client: ReqClient,
/// API key for authentication.
pub api_key: String,
/// Model to be used.
pub model: String,
/// API URL for GetImg.
pub api_url: &'static str,
}
impl Client {
/// Creates a new instance of the GetImg Client.
///
/// # Arguments
///
/// * `api_key` - A string representing the API key for authentication.
/// * `model` - A string representing the model to be used.
///
/// # Returns
///
/// A new instance of the GetImg Client.
///
/// # Panics
///
/// Panics if there is an issue parsing the GetImg API URL.
///
/// # Examples
///
/// ```
/// use getimg::client::Client;
///
/// let client = Client::new("your_api_key", "your_model");
/// ```
pub fn new(api_key: &str, model: &str) -> Self {
Self {
client: ReqClient::new(),
api_key: api_key.to_owned(),
model: model.to_owned(),
api_url: BASE_URL,
}
}
/// Generates an image based on a text prompt.
///
/// # Arguments
///
/// * `prompt` - A string representing the input text for content generation.
/// * `width` - Width of the generated image.
/// * `height` - Height of the generated image.
/// * `steps` - The number of denoising steps.
/// * `output_format` - File format of the output image.
/// * `negative_prompt` - Text input that will not guide the image generation.
/// * `seed` - Seed for making generation deterministic.
///
/// # Returns
///
/// A Result containing the generated content as a string or a reqwest::Error on failure.
///
/// # Examples
///
/// ```
/// use getimg::client::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let mut client = Client::new("your_api_key", "your_model");
/// let result = client.generate_image_from_text("Rusty crab on the beach", 512, 512, 4, "jpeg", None, Some(512)).await;
/// match result {
/// Ok(content) => println!("Generated Content: {:?}", content),
/// Err(err) => eprintln!("Error: {:?}", err),
/// }
/// }
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn generate_image_from_text(
&mut self,
prompt: &str,
width: usize,
height: usize,
steps: usize,
output_format: &str,
negative_prompt: Option<&str>,
seed: Option<usize>,
) -> Result<ToImageResponse> {
let request_body = TextToImageRequest {
prompt: prompt.to_string(),
model: self.model.clone(),
negative_prompt: negative_prompt.map(|s| s.to_string()),
width,
height,
steps,
output_format: output_format.to_string(),
seed,
};
let response = self
.client
.post(format!("{}/latent-consistency/text-to-image", self.api_url))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
.header(header::CONTENT_TYPE, "application/json")
.json(&request_body)
.send()
.await?;
let result = response.json::<ToImageResponse>().await?;
Ok(result)
}
/// Generates an image based on an image prompt.
///
/// # Arguments
///
/// * `prompt` - A string representing the input text for content generation.
/// * `image_data` - A base64-encoded string representing the image data.
/// * `negative_prompt` - Text input that will not guide the image generation.
/// * `strength` - Indicates how much to transform the reference image.
/// * `steps` - The number of denoising steps.
/// * `seed` - Makes generation deterministic.
/// * `output_format` - File format of the output image.
///
/// # Returns
///
/// A Result containing the generated content as a string or a reqwest::Error on failure.
///
/// # Examples
///
/// ```
/// use getimg::client::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let mut client = Client::new("your_api_key", "your_model");
/// let result = client.generate_image_from_image("a photo of an astronaut riding a crab on mars", "base64_encoded_image_data", 5, 512, "png",None, Some(0.5)).await;
/// match result {
/// Ok(content) => println!("Generated Content: {:?}", content),
/// Err(err) => eprintln!("Error: {:?}", err),
/// }
/// }
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn generate_image_from_image(
&mut self,
prompt: &str,
image_data: &str,
steps: usize,
seed: usize,
output_format: &str,
negative_prompt: Option<&str>,
strength: Option<f64>,
) -> Result<ToImageResponse> {
let request_body = ImageToImageRequest {
model: self.model.clone(),
prompt: prompt.to_string(),
negative_prompt: negative_prompt.map(|s| s.to_string()),
image: image_data.to_string(),
strength,
steps,
output_format: output_format.to_string(),
seed: Some(seed),
};
let response = self
.client
.post(format!(
"{}/latent-consistency/image-to-image",
self.api_url
))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
.header(header::CONTENT_TYPE, "application/json")
.json(&request_body)
.send()
.await?;
let result = response.json::<ToImageResponse>().await?;
Ok(result)
}
/// Generates an image using the ControlNet endpoint.
///
/// # Arguments
///
/// * `controlnet` - Type of ControlNet conditioning.
/// * `prompt` - Text input required to guide the image generation.
/// * `negative_prompt` - Text input that will not guide the image generation.
/// * `image` - Base64 encoded image that will be used as the ControlNet input condition.
/// * `strength` - Indicates the scale at which ControlNet conditioning is applied.
/// * `width` - The width of the generated image in pixels.
/// * `height` - The height of the generated image in pixels.
/// * `steps` - The number of denoising steps.
/// * `guidance` - Guidance scale as defined in Classifier-Free Diffusion Guidance.
/// * `seed` - Makes generation deterministic.
/// * `scheduler` - Scheduler used to denoise the encoded image latents.
/// * `output_format` - File format of the output image.
///
/// # Returns
///
/// A Result containing the generated content as a string or a reqwest::Error on failure.
///
/// # Examples
///
/// ```
/// use getimg::client::Client;
///
/// #[tokio::main]
/// async fn main() {
/// let mut client = Client::new("your_api_key", "your_model");
/// let result = client.generate_image_using_controlnet("softedge-1.1", "a photo of an astronaut riding a crab on mars", "Disfigured, cartoon, blurry", "base64_encoded_image_data", 1.0, 512, 512, 25, 7.5, 512, "euler", "png").await;
/// match result {
/// Ok(content) => println!("Generated Content: {:?}", content),
/// Err(err) => eprintln!("Error: {:?}", err),
/// }
/// }
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn generate_image_using_controlnet(
&mut self,
controlnet: &str,
prompt: &str,
negative_prompt: &str,
image: &str,
strength: f64,
width: usize,
height: usize,
steps: usize,
guidance: f64,
seed: usize,
scheduler: &str,
output_format: &str,
) -> Result<ToImageResponse> {
let request_body = ControlNetRequest {
controlnet: controlnet.to_string(),
model: "stable-diffusion-v1-5".to_string(),
prompt: prompt.to_string(),
negative_prompt: Some(negative_prompt.to_string()),
image: image.to_string(),
strength,
width,
height,
steps,
guidance,
seed,
scheduler: scheduler.to_string(),
output_format: output_format.to_string(),
};
let response = self
.client
.post(format!("{}/stable-diffusion/controlnet", self.api_url))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
.header(header::CONTENT_TYPE, "application/json")
.json(&request_body)
.send()
.await?;
let result = response.json::<ToImageResponse>().await?;
Ok(result)
}
/// Generates a repainted image using the GetImg API.
///
/// # Arguments
///
/// * `prompt` - Text input that guides the image repainting process.
/// * `negative_prompt` - Optional text input that contradicts the guidance for repainting.
/// * `image_data` - Base64 encoded image data to be repainted.
/// * `mask_image_data` - Base64 encoded mask image data indicating areas to be repainted.
/// * `strength` - Strength of the repainting effect.
/// * `width` - Width of the generated image.
/// * `height` - Height of the generated image.
/// * `steps` - Number of steps in the repainting process.
/// * `guidance` - Guidance scale for the repainting process.
/// * `seed` - Seed for deterministic generation.
/// * `scheduler` - Scheduler used in the repainting process.
/// * `output_format` - Output format of the generated image.
///
/// # Returns
///
/// A Result containing the repainted image response or an error if the request fails.
#[allow(clippy::too_many_arguments)]
pub async fn generate_repainted_image(
&mut self,
prompt: &str,
negative_prompt: Option<&str>,
image_data: &str,
mask_image_data: &str,
strength: Option<f64>,
width: usize,
height: usize,
steps: usize,
guidance: f64,
seed: usize,
scheduler: &str,
output_format: &str,
) -> Result<ToImageResponse> {
let request_body = RepaintImageRequest {
model: "stable-diffusion-v1-5-inpainting".to_string(),
prompt: prompt.to_string(),
negative_prompt: negative_prompt.map(|s| s.to_string()),
image: image_data.to_string(),
mask_image: mask_image_data.to_string(),
strength,
width,
height,
steps,
guidance,
seed,
scheduler: scheduler.to_string(),
output_format: output_format.to_string(),
};
let response = self
.client
.post(format!("{}/stable-diffusion/inpaint", self.api_url))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
.header(header::CONTENT_TYPE, "application/json")
.json(&request_body)
.send()
.await?;
let result = response.json::<ToImageResponse>().await?;
Ok(result)
}
/// Generates an edited image using the GetImg API.
///
/// # Arguments
///
/// * `prompt` - Text input guiding the image editing process.
/// * `negative_prompt` - Optional text input that contradicts the guidance for editing.
/// * `image_data` - Base64 encoded image data to be edited.
/// * `image_guidance` - Guidance scale for the image editing process.
/// * `steps` - Number of steps in the editing process.
/// * `guidance` - Guidance scale for the editing process.
/// * `seed` - Seed for deterministic generation.
/// * `scheduler` - Scheduler used in the editing process.
/// * `output_format` - Output format of the generated image.
///
/// # Returns
///
/// A Result containing the edited image response or an error if the request fails.
#[allow(clippy::too_many_arguments)]
pub async fn generate_edited_image(
&mut self,
prompt: &str,
negative_prompt: Option<&str>,
image_data: &str,
image_guidance: f64,
steps: usize,
guidance: f64,
seed: usize,
scheduler: &str,
output_format: &str,
) -> Result<ToImageResponse> {
let request_body = EditImageRequest {
model: "instruct-pix2pix".to_string(),
prompt: prompt.to_string(),
negative_prompt: negative_prompt.map(|s| s.to_string()),
image: image_data.to_string(),
image_guidance,
steps,
guidance,
seed,
scheduler: scheduler.to_string(),
output_format: output_format.to_string(),
};
let response = self
.client
.post(format!("{}/stable-diffusion/instruct", self.api_url))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", self.api_key))
.header(header::CONTENT_TYPE, "application/json")
.json(&request_body)
.send()
.await?;
let result = response.json::<ToImageResponse>().await?;
Ok(result)
}
}
/// Custom Debug trait implementation for Client struct.
///
/// This implementation hides the API key from being exposed in debug output.
impl fmt::Debug for Client {
/// Formats the Client struct for debug output.
///
/// # Arguments
///
/// * `f` - The formatter used to write the output.
///
/// # Returns
///
/// A fmt::Result indicating success or failure of the formatting operation.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("model", &self.model)
.finish()
}
}