-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathDallE.php
494 lines (443 loc) · 15.8 KB
/
DallE.php
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
<?php
/**
* OpenAI DALL·E integration
*/
namespace Classifai\Providers\OpenAI;
use Classifai\Features\ImageGeneration;
use Classifai\Providers\Provider;
use Classifai\Providers\OpenAI\APIRequest;
use WP_Error;
use WP_REST_Server;
class DallE extends Provider {
use \Classifai\Providers\OpenAI\OpenAI;
const ID = 'openai_dalle';
/**
* OpenAI DALL·E URL.
*
* @var string
*/
protected $dalle_url = 'https://api.openai.com/v1/images/generations';
/**
* Maximum number of characters a prompt can have.
*
* @var int
*/
public $max_prompt_chars = 4000;
/**
* OpenAI DALL·E constructor.
*
* @param \Classifai\Features\Feature $feature_instance The feature instance.
*/
public function __construct( $feature_instance = null ) {
$this->feature_instance = $feature_instance;
}
/**
* Register what we need for the provider.
*
* This only fires if can_register returns true.
*/
public function register() {
add_filter( 'classifai_' . ImageGeneration::ID . '_rest_route_generate-image_args', [ $this, 'register_rest_args' ] );
}
/**
* Register settings for the provider.
*/
public function render_provider_fields() {
$settings = $this->feature_instance->get_settings( static::ID );
add_settings_field(
static::ID . '_api_key',
esc_html__( 'API Key', 'classifai' ),
[ $this->feature_instance, 'render_input' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'api_key',
'input_type' => 'password',
'default_value' => $settings['api_key'],
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
'description' => $this->feature_instance->is_configured_with_provider( static::ID ) ?
'' :
sprintf(
wp_kses(
/* translators: %1$s is replaced with the OpenAI sign up URL */
__( 'Don\'t have an OpenAI account yet? <a title="Sign up for an OpenAI account" href="%1$s">Sign up for one</a> in order to get your API key.', 'classifai' ),
[
'a' => [
'href' => [],
'title' => [],
],
]
),
esc_url( 'https://platform.openai.com/signup' )
),
]
);
add_settings_field(
static::ID . '_number_of_images',
esc_html__( 'Number of images', 'classifai' ),
[ $this->feature_instance, 'render_select' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'number_of_images',
'options' => array_combine( range( 1, 10 ), range( 1, 10 ) ),
'default_value' => $settings['number_of_images'],
'description' => __( 'Number of images that will be generated in one request. Note that each image will incur separate costs.', 'classifai' ),
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
]
);
add_settings_field(
static::ID . '_quality',
esc_html__( 'Image quality', 'classifai' ),
[ $this->feature_instance, 'render_select' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'quality',
'options' => self::get_image_quality_options(),
'default_value' => $settings['quality'],
'description' => __( 'The quality of the image that will be generated. High Definition creates images with finer details and greater consistency across the image but costs more.', 'classifai' ),
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
]
);
add_settings_field(
static::ID . '_image_size',
esc_html__( 'Image size', 'classifai' ),
[ $this->feature_instance, 'render_select' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'image_size',
'options' => self::get_image_size_options(),
'default_value' => $settings['image_size'],
'description' => __( 'Size of generated images. Larger sizes cost more.', 'classifai' ),
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
]
);
add_settings_field(
static::ID . '_style',
esc_html__( 'Image style', 'classifai' ),
[ $this->feature_instance, 'render_select' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'style',
'options' => self::get_image_style_options(),
'default_value' => $settings['style'],
'description' => __( 'The style of the generated images. Vivid causes more hyper-real and dramatic images. Natural causes more natural, less hyper-real looking images.', 'classifai' ),
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
]
);
add_settings_field(
static::ID . '_per_image_settings',
esc_html__( 'Enable per-image settings for quality, size, and style', 'classifai' ),
[ $this, 'render_input' ],
$this->feature_instance->get_option_name(),
$this->feature_instance->get_option_name() . '_section',
[
'option_index' => static::ID,
'label_for' => 'per_image_settings',
'input_type' => 'checkbox',
'default_value' => $settings['per_image_settings'] ?? false,
'description' => __( 'Enable this to allow users to select the quality, size, and style of the generated image.', 'classifai' ),
'class' => 'classifai-user-based-opt-out',
]
);
}
/**
* Returns the quality options for the provider.
*
* @return array
*/
public static function get_image_quality_options() {
return array(
'standard' => __( 'Standard', 'classifai' ),
'hd' => __( 'High Definition', 'classifai' ),
);
}
/**
* Returns the image size options for the provider.
*
* @return array
*/
public static function get_image_size_options() {
return array(
'1024x1024' => '1024x1024 (square)',
'1792x1024' => '1792x1024 (landscape)',
'1024x1792' => '1024x1792 (portrait)',
);
}
/**
* Returns the style options for the provider.
*
* @return array
*/
public static function get_image_style_options() {
return array(
'vivid' => __( 'Vivid', 'classifai' ),
'natural' => __( 'Natural', 'classifai' ),
);
}
/**
* Returns the default settings for the provider.
*
* @return array
*/
public function get_default_provider_settings(): array {
$common_settings = [
'api_key' => '',
'authenticated' => false,
];
switch ( $this->feature_instance::ID ) {
case ImageGeneration::ID:
return array_merge(
$common_settings,
[
'number_of_images' => 1,
'quality' => 'standard',
'image_size' => '1024x1024',
'style' => 'vivid',
]
);
}
return $common_settings;
}
/**
* Sanitization for the options being saved.
*
* @param array $new_settings Array of settings about to be saved.
* @return array The sanitized settings to be saved.
*/
public function sanitize_settings( array $new_settings ): array {
$settings = $this->feature_instance->get_settings();
$api_key_settings = $this->sanitize_api_key_settings( $new_settings, $settings );
$new_settings[ static::ID ]['api_key'] = $api_key_settings[ static::ID ]['api_key'];
$new_settings[ static::ID ]['authenticated'] = $api_key_settings[ static::ID ]['authenticated'];
if ( $this->feature_instance instanceof ImageGeneration ) {
$new_settings[ static::ID ]['number_of_images'] = absint( $new_settings[ static::ID ]['number_of_images'] ?? $settings[ static::ID ]['number_of_images'] );
if ( in_array( $new_settings[ static::ID ]['quality'], [ 'standard', 'hd' ], true ) ) {
$new_settings[ static::ID ]['quality'] = sanitize_text_field( $new_settings[ static::ID ]['quality'] );
} else {
$new_settings[ static::ID ]['quality'] = $settings[ static::ID ]['quality'];
}
if ( in_array( $new_settings[ static::ID ]['image_size'], [ '1024x1024', '1792x1024', '1024x1792' ], true ) ) {
$new_settings[ static::ID ]['image_size'] = sanitize_text_field( $new_settings[ static::ID ]['image_size'] );
} else {
$new_settings[ static::ID ]['image_size'] = $settings[ static::ID ]['image_size'];
}
if ( in_array( $new_settings[ static::ID ]['style'], [ 'vivid', 'natural' ], true ) ) {
$new_settings[ static::ID ]['style'] = sanitize_text_field( $new_settings[ static::ID ]['style'] );
} else {
$new_settings[ static::ID ]['style'] = $settings[ static::ID ]['style'];
}
}
return $new_settings;
}
/**
* Common entry point for all REST endpoints for this provider.
*
* @param string $prompt The prompt used to generate an image.
* @param string $route_to_call The route we are processing.
* @param array $args Optional arguments to pass to the route.
* @return string|WP_Error
*/
public function rest_endpoint_callback( $prompt = '', string $route_to_call = '', array $args = [] ) {
$route_to_call = strtolower( $route_to_call );
$return = '';
// Handle all of our routes.
switch ( $route_to_call ) {
case 'image_gen':
$return = $this->generate_image( $prompt, $args );
break;
}
return $return;
}
/**
* Entry point for the generate-image REST endpoint.
*
* @param string $prompt The prompt used to generate an image.
* @param array $args Optional arguments passed to endpoint.
* @return string|WP_Error
*/
public function generate_image( string $prompt = '', array $args = [] ) {
if ( ! $prompt ) {
return new WP_Error( 'prompt_required', esc_html__( 'A prompt is required to generate an image.', 'classifai' ) );
}
$image_generation = new ImageGeneration();
$settings = $image_generation->get_settings( static::ID );
$args = wp_parse_args(
array_filter( $args ),
[
'num' => $settings['number_of_images'] ?? 1,
'quality' => $settings['quality'] ?? 'standard',
'size' => $settings['image_size'] ?? '1024x1024',
'style' => $settings['style'] ?? 'vivid',
'format' => 'url',
]
);
// Force proper image size for those that had been using DALL·E 2 and haven't updated settings.
if ( ! in_array( $args['size'], [ '1024x1024', '1792x1024', '1024x1792' ], true ) ) {
$args['size'] = '1024x1024';
}
if ( ! $image_generation->is_feature_enabled() ) {
return new WP_Error( 'not_enabled', esc_html__( 'Image generation is disabled or OpenAI authentication failed. Please check your settings.', 'classifai' ) );
}
/**
* Filter the prompt we will send to DALL·E.
*
* @since 2.0.0
* @hook classifai_dalle_prompt
*
* @param {string} $prompt Prompt we are sending to DALL·E.
*
* @return {string} Prompt.
*/
$prompt = apply_filters( 'classifai_dalle_prompt', $prompt );
// If our prompt exceeds the max length, throw an error.
if ( mb_strlen( $prompt ) > $this->max_prompt_chars ) {
return new WP_Error( 'invalid_param', esc_html__( 'Your image prompt is too long. Please ensure it doesn\'t exceed 1000 characters.', 'classifai' ) );
}
$request = new APIRequest( $settings['api_key'] ?? '', 'generate-image' );
/**
* Filter the request body before sending to DALL·E.
*
* @since 2.0.0
* @hook classifai_dalle_request_body
*
* @param {array} $body Request body that will be sent to DALL·E.
*
* @return {array} Request body.
*/
$body = apply_filters(
'classifai_dalle_request_body',
[
'prompt' => sanitize_text_field( $prompt ),
'model' => 'dall-e-3',
'n' => 1,
'quality' => sanitize_text_field( $args['quality'] ),
'response_format' => sanitize_text_field( $args['format'] ),
'size' => sanitize_text_field( $args['size'] ),
'style' => sanitize_text_field( $args['style'] ),
]
);
$responses = [];
// DALL·E 3 doesn't support multiple images in a single request so make one request per image.
for ( $i = 0; $i < $args['num']; $i++ ) {
$responses[] = $request->post(
$this->dalle_url,
[
'body' => wp_json_encode( $body ),
]
);
}
set_transient( 'classifai_openai_dalle_latest_response', $responses[ array_key_last( $responses ) ], DAY_IN_SECONDS * 30 );
$cleaned_responses = [];
foreach ( $responses as $response ) {
// Extract out the image response, if it exists.
if ( ! is_wp_error( $response ) && ! empty( $response['data'] ) ) {
foreach ( $response['data'] as $data ) {
if ( ! empty( $data[ $args['format'] ] ) ) {
if ( 'url' === $args['format'] ) {
$cleaned_responses[] = [ 'url' => esc_url_raw( $data[ $args['format'] ] ) ];
} else {
$cleaned_responses[] = [ 'url' => $data[ $args['format'] ] ];
}
}
}
}
}
return $cleaned_responses;
}
/**
* Returns the debug information for the provider settings.
*
* @return array
*/
public function get_debug_information(): array {
$settings = $this->feature_instance->get_settings();
$provider_settings = $settings[ static::ID ];
$debug_info = [];
if ( $this->feature_instance instanceof ImageGeneration ) {
$debug_info[ __( 'Number of images', 'classifai' ) ] = $provider_settings['number_of_images'] ?? 1;
$debug_info[ __( 'Quality', 'classifai' ) ] = $provider_settings['quality'] ?? 'standard';
$debug_info[ __( 'Size', 'classifai' ) ] = $provider_settings['image_size'] ?? '1024x1024';
$debug_info[ __( 'Style', 'classifai' ) ] = $provider_settings['style'] ?? 'vivid';
$debug_info[ __( 'Latest response:', 'classifai' ) ] = $this->get_formatted_latest_response( get_transient( 'classifai_openai_dalle_latest_response' ) );
}
return apply_filters(
'classifai_' . self::ID . '_debug_information',
$debug_info,
$settings,
$this->feature_instance
);
}
/**
* Register additional REST arguments for the provider.
*
* @since 3.0.0
*
* @param array $args Existing REST arguments.
* @return array
*/
public function register_rest_args( array $args = [] ): array {
$provider_args = [
'n' => [
'type' => 'integer',
'minimum' => 1,
'maximum' => 10,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
'description' => esc_html__( 'Number of images to generate', 'classifai' ),
],
'quality' => [
'type' => 'string',
'enum' => [
'standard',
'hd',
],
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
'description' => esc_html__( 'Quality of generated image', 'classifai' ),
],
'size' => [
'type' => 'string',
'enum' => [
'1024x1024',
'1792x1024',
'1024x1792',
],
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
'description' => esc_html__( 'Size of generated image', 'classifai' ),
],
'style' => [
'type' => 'string',
'enum' => [
'vivid',
'natural',
],
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
'description' => esc_html__( 'Style of generated image', 'classifai' ),
],
'format' => [
'type' => 'string',
'enum' => [
'url',
'b64_json',
],
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
'description' => esc_html__( 'Format of generated image', 'classifai' ),
],
];
// Merge the provider args with the existing args.
$args['args'] = array_merge( $args['args'], $provider_args );
return $args;
}
}