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
//!
//! Given a prompt and/or an input image, the model will generate a new image.
//!
//! Related guide: Image generation
//!
//! Source: OpenAI documentation

////////////////////////////////////////////////////////////////////////////////

use crate::openai::{
    endpoint::{
        request_endpoint, request_endpoint_form_data, Endpoint, EndpointVariant,
        ImageEndpointVariant,
    },
    types::{
        common::Error,
        image::{Format, ImageResponse, Size},
    },
};
use log::{debug, warn};
use reqwest::multipart::{Form, Part};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

/// Given a prompt and an instruction, the model will return an edited version
/// of the prompt.
#[serde_as]
#[derive(Serialize, Deserialize, Debug)]
pub struct Image {
    #[serde(skip)]
    pub image: Option<(String, Vec<u8>)>,

    #[serde(skip)]
    pub mask: Option<(String, Vec<u8>)>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<Size>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<Format>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
}

impl Default for Image {
    fn default() -> Self {
        Self {
            image: None,
            mask: None,
            prompt: None,
            size: None,
            response_format: None,
            user: None,
            n: None,
        }
    }
}

impl Image {
    /// Determine and verify MIME type of input file.
    ///
    /// # Arguments
    /// - `file_name` - Name of the input file
    fn mime(&self, file_name: &str) -> Result<&'static str, Box<dyn std::error::Error>> {
        Ok(
            match *file_name.split('.').collect::<Vec<&str>>().last().unwrap() {
                "png" => "image/png",
                _ => return Err("Unsupported format!".into()),
            },
        )
    }

    /// The image to edit. Must be a valid PNG file, less than 4MB, and square.
    ///  If mask is not provided, image must have transparency, which will be
    /// used as the mask.
    ///
    /// # Arguments
    /// - `filename` - Image filename to edit or create variant
    /// - `bytes` - Image bytes to edit or create variant
    pub fn image(self, filename: &str, bytes: Vec<u8>) -> Self {
        Self {
            image: Some((filename.into(), bytes.clone())),
            ..self
        }
    }

    /// An additional image whose fully transparent areas (e.g. where alpha is
    /// zero) indicate where `image` should be edited. Must be a valid PNG
    /// file, less than 4MB, and have the same dimensions as `image`.
    ///
    /// # Arguments
    /// - `filename` - Image filename to edit or create variant
    /// - `bytes` - Image bytes to edit or create variant
    pub fn mask(self, filename: &str, bytes: Vec<u8>) -> Self {
        Self {
            mask: Some((filename.into(), bytes.clone())),
            ..self
        }
    }

    /// A text description of the desired image(s). The maximum length is 1000
    /// characters.
    pub fn prompt(self, content: &str) -> Self {
        Self {
            prompt: Some(content.into()),
            ..self
        }
    }

    /// The number of images to generate. Must be between 1 and 10.
    pub fn n(self, n: u32) -> Self {
        Self { n: Some(n), ..self }
    }

    /// The size of the generated images. Must be one of `256x256`, `512x512`,
    /// or `1024x1024`. Use given enum variant.
    pub fn size(self, size: Size) -> Self {
        Self {
            size: Some(size),
            ..self
        }
    }

    /// The format in which the generated images are returned. Must be one of
    /// `url` or `b64_json`.
    pub fn response_format(self, response_format: Format) -> Self {
        Self {
            response_format: Some(response_format),
            ..self
        }
    }

    /// A unique identifier representing your end-user, which can help OpenAI
    /// to monitor and detect abuse. Learn more.
    pub fn user(self, user: &str) -> Self {
        Self {
            user: Some(user.into()),
            ..self
        }
    }

    /// Send edit request to OpenAI.
    pub async fn editing(&self) -> Result<ImageResponse, Box<dyn std::error::Error>> {
        if let None = self.image {
            return Err("`image` required, call `image()` first".into());
        }
        if let None = self.prompt {
            return Err("`prompt` required, call `prompt()` first".into());
        }

        let mut image_response: Option<ImageResponse> = None;

        let mut form = Form::new();

        if let Some(image_tup) = self.image.as_ref() {
            let image = Part::bytes(image_tup.1.clone())
                .file_name(image_tup.0.clone())
                .mime_str(self.mime(&image_tup.0).unwrap())
                .unwrap();
            form = form.part("image", image);
        }

        if let Some(mask_tup) = self.mask.as_ref() {
            let mask = Part::bytes(mask_tup.1.clone())
                .file_name(mask_tup.0.clone())
                .mime_str(self.mime(&mask_tup.0).unwrap())
                .unwrap();
            form = form.part("mask", mask);
        }

        if let Some(prompt) = self.prompt.clone() {
            form = form.part("prompt", Part::text(prompt));
        }

        if let Some(n) = self.n.clone() {
            form = form.part("n", Part::text(n.to_string()));
        }

        if let Some(size) = self.size.clone() {
            let size: &str = size.into();
            form = form.part("size", Part::text(size));
        }

        if let Some(fmt) = self.response_format.clone() {
            let fmt: &str = fmt.into();
            form = form.part("response_format", Part::text(fmt));
        }

        if let Some(user) = self.user.clone() {
            form = form.part("user", Part::text(user));
        }

        let variant: String = ImageEndpointVariant::Editing.into();
        request_endpoint_form_data(form, &Endpoint::Image_v1, EndpointVariant::from(variant), |res| {
            if let Ok(text) = res {
                if let Ok(response_data) = serde_json::from_str::<ImageResponse>(&text) {
                    debug!(target: "openai", "Response parsed, image edit response deserialized.");
                    image_response = Some(response_data);
                } else {
                    if let Ok(response_error) = serde_json::from_str::<Error>(&text) {
                        warn!(target: "openai",
                            "OpenAI error code {}: `{:?}`",
                            response_error.error.code.unwrap_or(0),
                            text
                        );
                    } else {
                        warn!(target: "openai", "Image response not deserializable.");
                    }
                }
            }
        })
        .await?;

        if let Some(response_data) = image_response {
            Ok(response_data)
        } else {
            Err("No response or error parsing response".into())
        }
    }

    /// Send generation request to OpenAI.
    pub async fn generation(&mut self) -> Result<ImageResponse, Box<dyn std::error::Error>> {
        self.image = None;
        self.mask = None;

        if let None = self.prompt {
            return Err("`prompt` required, call `prompt()` first".into());
        }

        let mut image_response: Option<ImageResponse> = None;

        let variant: String = ImageEndpointVariant::Generation.into();
        request_endpoint(&self, &Endpoint::Image_v1, EndpointVariant::from(variant), |res| {
            if let Ok(text) = res {
                if let Ok(response_data) = serde_json::from_str::<ImageResponse>(&text) {
                    debug!(target: "openai", "Response parsed, image generation response deserialized.");
                    image_response = Some(response_data);
                } else {
                    if let Ok(response_error) = serde_json::from_str::<Error>(&text) {
                        warn!(target: "openai",
                            "OpenAI error code {}: `{:?}`",
                            response_error.error.code.unwrap_or(0),
                            text
                        );
                    } else {
                        warn!(target: "openai", "Image response not deserializable.");
                    }
                }
            }
        })
        .await?;

        if let Some(response_data) = image_response {
            Ok(response_data)
        } else {
            Err("No response or error parsing response".into())
        }
    }

    /// Send variation request to OpenAI.
    pub async fn variation(&mut self) -> Result<ImageResponse, Box<dyn std::error::Error>> {
        if let None = self.image {
            return Err("`image` required, call `image()` first".into());
        }
        self.prompt = None;
        self.mask = None;

        let mut image_response: Option<ImageResponse> = None;

        let mut form = Form::new();

        if let Some(image_tup) = self.image.as_ref() {
            let image = Part::bytes(image_tup.1.clone())
                .file_name(image_tup.0.clone())
                .mime_str(self.mime(&image_tup.0).unwrap())
                .unwrap();
            form = form.part("image", image);
        }

        if let Some(n) = self.n.clone() {
            form = form.part("n", Part::text(n.to_string()));
        }

        if let Some(size) = self.size.clone() {
            let size: &str = size.into();
            form = form.part("size", Part::text(size));
        }

        if let Some(fmt) = self.response_format.clone() {
            let fmt: &str = fmt.into();
            form = form.part("response_format", Part::text(fmt));
        }

        if let Some(user) = self.user.clone() {
            form = form.part("user", Part::text(user));
        }

        let variant: String = ImageEndpointVariant::Variation.into();

        request_endpoint_form_data(form, &Endpoint::Image_v1, EndpointVariant::from(variant), |res| {
            if let Ok(text) = res {
                if let Ok(response_data) = serde_json::from_str::<ImageResponse>(&text) {
                    debug!(target: "openai", "Response parsed, image variation response deserialized.");
                    image_response = Some(response_data);
                } else {
                    if let Ok(response_error) = serde_json::from_str::<Error>(&text) {
                        warn!(target: "openai",
                            "OpenAI error code {}: `{:?}`",
                            response_error.error.code.unwrap_or(0),
                            text
                        );
                    } else {
                        warn!(target: "openai", "Image response not deserializable.");
                    }
                }
            }
        })
        .await?;

        if let Some(response_data) = image_response {
            Ok(response_data)
        } else {
            Err("No response or error parsing response".into())
        }
    }
}