-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathAmazonPolly.php
More file actions
625 lines (548 loc) · 19.2 KB
/
AmazonPolly.php
File metadata and controls
625 lines (548 loc) · 19.2 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
<?php
/**
* Provides Text to Speech synthesis feature using Amazon Polly.
*
* @package Classifai\Providers\AWS
* @since 3.1.0
*/
namespace Classifai\Providers\AWS;
use Classifai\Providers\Provider;
use Classifai\Features\TextToSpeech;
use WP_Error;
use Aws\Sdk;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class AmazonPolly extends Provider {
const ID = 'aws_polly';
/**
* AmazonPolly Text to Speech constructor.
*
* @param \Classifai\Features\Feature $feature_instance The feature instance.
*/
public function __construct( $feature_instance = null ) {
$this->feature_instance = $feature_instance;
do_action( 'classifai_' . static::ID . '_init', $this );
add_action( 'wp_ajax_classifai_get_voice_dropdown', [ $this, 'get_voice_dropdown' ] );
}
/**
* Render the provider fields.
*/
public function render_provider_fields() {
$settings = $this->feature_instance->get_settings( static::ID );
add_settings_field(
'access_key_id',
esc_html__( 'Access 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' => 'access_key_id',
'input_type' => 'text',
'default_value' => $settings['access_key_id'],
'class' => 'large-text 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 */
__( 'Enter the AWS access key. Please follow the steps given <a title="AWS documentation" href="%1$s">here</a> to generate AWS credentials.', 'classifai' ),
[
'a' => [
'href' => [],
'title' => [],
],
]
),
esc_url( 'https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey' )
),
]
);
add_settings_field(
'secret_access_key',
esc_html__( 'Secret access 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' => 'secret_access_key',
'input_type' => 'password',
'default_value' => $settings['secret_access_key'],
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
'description' => $this->feature_instance->is_configured_with_provider( static::ID ) ?
'' :
esc_html__( 'Enter the AWS secret access key.', 'classifai' ),
]
);
add_settings_field(
'aws_region',
esc_html__( 'Region', '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' => 'aws_region',
'input_type' => 'text',
'default_value' => $settings['aws_region'],
'class' => 'large-text classifai-provider-field hidden provider-scope-' . static::ID,
'description' => $this->feature_instance->is_configured_with_provider( static::ID ) ?
'' :
wp_kses(
__( 'Enter the AWS Region. eg: <code>us-east-1</code>', 'classifai' ),
[
'code' => [],
]
),
]
);
add_settings_field(
'voice_engine',
esc_html__( 'Engine', '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' => 'voice_engine',
'options' => array(
'standard' => esc_html__( 'Standard', 'classifai' ),
'neural' => esc_html__( 'Neural', 'classifai' ),
'long-form' => esc_html__( 'Long Form', 'classifai' ),
),
'default_value' => $settings['voice_engine'],
'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 */
__( 'Amazon Polly offers <a href="%1$s">Long-Form</a>, <a href="%2$s">Neural</a> and Standard text-to-speech voices. Please check the <a title="Pricing" href="%3$s">documentation</a> to review pricing for Long-Form, Neural and Standard usage.', 'classifai' ),
[
'a' => [
'href' => [],
'title' => [],
],
]
),
esc_url( 'https://docs.aws.amazon.com/polly/latest/dg/long-form-voice-overview.html' ),
esc_url( 'https://docs.aws.amazon.com/polly/latest/dg/NTTS-main.html' ),
esc_url( 'https://aws.amazon.com/polly/pricing/' )
),
]
);
$voices_options = $this->get_voices_select_options( $settings['voice_engine'] ?? '' );
if ( ! empty( $voices_options ) ) {
add_settings_field(
'voice',
esc_html__( 'Voice', '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' => 'voice',
'options' => $voices_options,
'default_value' => $settings['voice'],
'class' => 'classifai-aws-polly-voices classifai-provider-field hidden provider-scope-' . static::ID,
]
);
}
do_action( 'classifai_' . static::ID . '_render_provider_fields', $this );
}
/**
* Returns the default settings for this provider.
*
* @return array
*/
public function get_default_provider_settings(): array {
$common_settings = [
'access_key_id' => '',
'secret_access_key' => '',
'aws_region' => '',
'authenticated' => false,
'voice_engine' => 'standard',
'voices' => [],
'voice' => '',
];
switch ( $this->feature_instance::ID ) {
case TextToSpeech::ID:
return $common_settings;
}
return [];
}
/**
* Sanitization callback for settings.
*
* @param array $new_settings The settings being saved.
* @return array
*/
public function sanitize_settings( array $new_settings ): array {
$settings = $this->feature_instance->get_settings();
$authenticated = $this->authenticate_credentials( $new_settings );
if ( is_wp_error( $authenticated ) ) {
$new_settings[ static::ID ]['authenticated'] = false;
add_settings_error(
'api_key',
'classifai-auth',
$authenticated->get_error_message(),
'error'
);
} else {
$new_settings[ static::ID ]['authenticated'] = true;
}
$new_access_key_id = sanitize_text_field( $new_settings[ static::ID ]['access_key_id'] ?? $settings[ static::ID ]['access_key_id'] );
$new_secret_access_key = sanitize_text_field( $new_settings[ static::ID ]['secret_access_key'] ?? $settings[ static::ID ]['secret_access_key'] );
$new_aws_region = sanitize_text_field( $new_settings[ static::ID ]['aws_region'] ?? $settings[ static::ID ]['aws_region'] );
$new_settings[ static::ID ]['access_key_id'] = $new_access_key_id;
$new_settings[ static::ID ]['secret_access_key'] = $new_secret_access_key;
$new_settings[ static::ID ]['aws_region'] = $new_aws_region;
// Connect to the service and get voices.
$new_settings[ static::ID ]['voices'] = $this->connect_to_service(
array(
'access_key_id' => $new_access_key_id,
'secret_access_key' => $new_secret_access_key,
'aws_region' => $new_aws_region,
)
);
if ( ! empty( $new_settings[ static::ID ]['voices'] ) ) {
$new_settings[ static::ID ]['authenticated'] = true;
} else {
$new_settings[ static::ID ]['voices'] = [];
$new_settings[ static::ID ]['authenticated'] = false;
}
$new_settings[ static::ID ]['voice'] = sanitize_text_field( $new_settings[ static::ID ]['voice'] ?? $settings[ static::ID ]['voice'] );
return $new_settings;
}
/**
* Authenticate our credentials.
*
* @param array $settings Settings being saved.
* @return bool|WP_Error
*/
protected function authenticate_credentials( array $settings = [] ) {
$response = false;
try {
/**
* Filters the return value of the connect to services function.
*
* Returning a non-false value from the filter will short-circuit
* the describe voices request and return early with that value.
* This filter is useful for E2E tests.
*
* @since 3.1.0
* @hook classifai_aws_polly_pre_connect_to_service
*
* @param bool $pre The value of pre connect to service. Default false. A non-false value will short-circuit the describe voices request.
*
* @return bool|mixed The filtered value of connect to service.
*/
$pre = apply_filters( 'classifai_' . self::ID . '_pre_connect_to_service', false );
if ( false !== $pre ) {
return $pre;
}
$polly_client = $this->get_polly_client( $settings[ static::ID ] );
if ( $polly_client ) {
$polly_voices = $polly_client->describeVoices();
$polly_voices = $polly_voices->get( 'Voices' );
} else {
$polly_voices = [];
}
$response = ! empty( $polly_voices ) ? true : new WP_Error( 'auth', esc_html__( 'Connection to Amazon Polly failed.', 'classifai' ) );
} catch ( \Exception $e ) {
$response = new WP_Error( 'auth', esc_html__( 'Connection to Amazon Polly failed.', 'classifai' ) );
}
return ! is_wp_error( $response ) ? true : $response;
}
/**
* Connects to the Amazon Polly service.
*
* @param array $args Overridable args.
* @return array
*/
public function connect_to_service( array $args = array() ): array {
$settings = $this->feature_instance->get_settings( static::ID );
$default = array(
'access_key_id' => $settings[ static::ID ]['access_key_id'] ?? '',
'secret_access_key' => $settings[ static::ID ]['secret_access_key'] ?? '',
'aws_region' => $settings[ static::ID ]['aws_region'] ?? 'us-east-1',
);
$default = wp_parse_args( $args, $default );
// Return if credentials don't exist.
if ( empty( $default['access_key_id'] ) || empty( $default['secret_access_key'] ) ) {
return array();
}
try {
/**
* Filters the return value of the connect to services function.
*
* Returning a non-false value from the filter will short-circuit the describe voices request and return early with that value.
* This filter is useful for E2E tests.
*
* @since 3.1.0
* @hook classifai_aws_polly_pre_connect_to_service
*
* @param bool $pre The value of pre connect to service. Default false. non-false value will short-circuit the describe voices request.
*
* @return bool|mixed The filtered value of connect to service.
*/
$pre = apply_filters( 'classifai_' . self::ID . '_pre_connect_to_service', false );
if ( false !== $pre ) {
return $pre;
}
$polly_client = $this->get_polly_client( $default );
$polly_voices = $polly_client->describeVoices();
return $polly_voices->get( 'Voices' );
} catch ( \Exception $e ) {
add_settings_error(
$this->feature_instance->get_option_name(),
'aws-polly-auth-failed',
esc_html__( 'Connection to Amazon Polly failed.', 'classifai' ),
'error'
);
return array();
}
}
/**
* Returns HTML select dropdown options for voices.
*
* @param string $engine Engine type.
* @return array
*/
public function get_voices_select_options( string $engine = '' ): array {
$settings = $this->feature_instance->get_settings( static::ID );
$voices = $settings['voices'];
$options = array();
if ( false === $voices ) {
return $options;
}
foreach ( $voices as $voice ) {
if (
! is_array( $voice ) ||
empty( $voice ) ||
(
! empty( $engine ) &&
! in_array( $engine, $voice['SupportedEngines'], true )
)
) {
continue;
}
$options[ $voice['Id'] ] = sprintf(
'%1$s - %2$s (%3$s)',
esc_html( $voice['LanguageName'] ),
esc_html( $voice['Name'] ),
esc_html( $voice['Gender'] )
);
}
// Sort the options.
asort( $options );
return $options;
}
/**
* Synthesizes speech from a post item.
*
* @param int $post_id Post ID.
* @return string|WP_Error
*/
public function synthesize_speech( int $post_id ) {
if ( empty( $post_id ) ) {
return new WP_Error(
'aws_polly_post_id_missing',
esc_html__( 'Post ID missing.', 'classifai' )
);
}
// We skip the user cap check if running under WP-CLI.
if ( ! current_user_can( 'edit_post', $post_id ) && ( ! defined( 'WP_CLI' ) || ! WP_CLI ) ) {
return new WP_Error(
'aws_polly_user_not_authorized',
esc_html__( 'Unauthorized user.', 'classifai' )
);
}
$feature = new TextToSpeech();
$settings = $feature->get_settings();
$post_content = $feature->normalize_post_content( $post_id );
$content_hash = get_post_meta( $post_id, TextToSpeech::AUDIO_HASH_KEY, true );
$saved_attachment_id = (int) get_post_meta( $post_id, $feature::AUDIO_ID_KEY, true );
// Don't regenerate the audio file it it already exists and the content hasn't changed.
if ( $saved_attachment_id ) {
// Check if the audio file exists.
$audio_attachment_url = wp_get_attachment_url( $saved_attachment_id );
if ( $audio_attachment_url && ! empty( $content_hash ) && ( md5( $post_content ) === $content_hash ) ) {
return $saved_attachment_id;
}
}
if ( mb_strlen( $post_content ) > 3000 ) {
return new WP_Error(
'aws_polly_length_error',
esc_html__( 'Maximum text length has been exceeded.', 'classifai' )
);
}
$voice = $settings[ static::ID ]['voice'] ?? '';
try {
/**
* Filter Synthesize speech args.
*
* @since 3.1.0
* @hook classifai_aws_polly_synthesize_speech_args
*
* @param array $args Associative array of synthesize speech args.
* @param int $post_id Post ID.
* @param object $provider_instance Provider instance.
* @param object $feature_instance Feature instance.
*
* @return array The filtered array of synthesize speech args.
*/
$synthesize_data = apply_filters(
'classifai_' . self::ID . '_synthesize_speech_args',
array(
'OutputFormat' => 'mp3',
'Text' => $post_content,
'TextType' => 'text',
'Engine' => $settings[ static::ID ]['voice_engine'] ?? 'standard',
'VoiceId' => $voice,
),
$post_id,
$this,
$this->feature_instance
);
/**
* Filters the return value of the synthesize speech function.
*
* Returning a non-false value from the filter will short-circuit the synthesize speech request and return early with that value.
* This filter is useful for E2E tests.
*
* @since 3.1.0
* @hook classifai_aws_polly_pre_synthesize_speech
*
* @param bool $pre A value of pre synthesize speech. Default false.
* @param array $synthesize_data HTTP request arguments.
*
* @return bool|mixed The filtered value of pre synthesize speech.
*/
$pre = apply_filters( 'classifai_' . self::ID . '_pre_synthesize_speech', false, $synthesize_data );
if ( false !== $pre ) {
return $pre;
}
$polly_client = $this->get_polly_client();
$result = $polly_client->synthesizeSpeech( $synthesize_data );
update_post_meta( $post_id, TextToSpeech::AUDIO_HASH_KEY, md5( $post_content ) );
$contents = $result['AudioStream']->getContents();
return $contents;
} catch ( \Exception $e ) {
return new WP_Error(
'aws_polly_http_error',
esc_html( $e->getMessage() )
);
}
}
/**
* Common entry point for all REST endpoints for this provider.
*
* @param int $post_id The post ID we're processing.
* @param string $route_to_call The name of the route we're going to be processing.
* @param array $args Optional arguments to pass to the route.
* @return array|string|WP_Error
*/
public function rest_endpoint_callback( $post_id, string $route_to_call = '', array $args = [] ) {
if ( ! $post_id || ! get_post( $post_id ) ) {
return new WP_Error( 'post_id_required', esc_html__( 'A valid post ID is required.', 'classifai' ) );
}
$route_to_call = strtolower( $route_to_call );
$return = '';
// Handle all of our routes.
switch ( $route_to_call ) {
case 'synthesize':
$return = $this->synthesize_speech( $post_id );
break;
}
return $return;
}
/**
* 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 TextToSpeech ) {
$post_types = array_filter(
$settings['post_types'],
function ( $value ) {
return '0' !== $value;
}
);
$debug_info[ __( 'Allowed post types', 'classifai' ) ] = implode( ', ', $post_types );
$debug_info[ __( 'Voice', 'classifai' ) ] = $provider_settings['voice'];
$debug_info[ __( 'Latest response - Voices', 'classifai' ) ] = $this->get_formatted_latest_response( $provider_settings['voices'] );
}
return apply_filters(
'classifai_' . self::ID . '_debug_information',
$debug_info,
$settings,
$this->feature_instance
);
}
/**
* Returns aws polly client.
*
* @param array $aws_config AWS configuration array.
* @return \Aws\Polly\PollyClient|null
*/
public function get_polly_client( array $aws_config = array() ) {
$credentials = $this->get_credentials( [ static::ID => $aws_config ] );
// Return if credentials don't exist.
if ( empty( $credentials['access_key_id'] ) || empty( $credentials['secret_access_key'] ) ) {
return null;
}
// Set the AWS SDK configuration.
$aws_sdk_config = [
'region' => $credentials['aws_region'] ?? 'us-east-1',
'version' => 'latest',
'ua_append' => [ 'request-source/classifai' ],
'credentials' => [
'key' => $credentials['access_key_id'],
'secret' => $credentials['secret_access_key'],
],
];
$sdk = new Sdk( $aws_sdk_config );
return $sdk->createPolly();
}
/**
* Returns the voice dropdown for the selected engine.
*/
public function get_voice_dropdown() {
if ( ! wp_doing_ajax() ) {
return;
}
// Nonce check.
if ( ! check_ajax_referer( 'classifai', 'nonce', false ) ) {
$error = new WP_Error( 'classifai_nonce_error', __( 'Nonce could not be verified.', 'classifai' ) );
wp_send_json_error( $error );
exit();
}
// Set the feature instance if it's not already set.
if ( ! $this->feature_instance instanceof TextToSpeech ) {
$this->feature_instance = new TextToSpeech();
}
// Attachment ID check.
$engine = isset( $_POST['engine'] ) ? sanitize_text_field( wp_unslash( $_POST['engine'] ) ) : 'standard';
$settings = $this->feature_instance->get_settings( static::ID );
$voices_options = $this->get_voices_select_options( $engine );
ob_start();
$this->feature_instance->render_select(
[
'option_index' => static::ID,
'label_for' => 'voice',
'options' => $voices_options,
'default_value' => $settings['voice'],
'class' => 'classifai-provider-field hidden provider-scope-' . static::ID,
]
);
$voice_dropdown = ob_get_clean();
wp_send_json_success( $voice_dropdown );
}
}