/var/www/html_us/wp-content/plugins/woocommerce/src/Blocks/Images/Pexels.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
<?php

namespace Automattic\WooCommerce\Blocks\Images;

use 
Automattic\WooCommerce\Blocks\AI\Connection;
use 
Automattic\WooCommerce\Blocks\AIContent\ContentProcessor;
use 
Automattic\WooCommerce\Blocks\AIContent\UpdatePatterns;

/**
 * Pexels API client.
 *
 * @internal
 */
class Pexels {

    
/**
     * The Pexels API endpoint.
     */
    
const EXTERNAL_MEDIA_PEXELS_ENDPOINT '/wpcom/v2/external-media/list/pexels';

    
/**
     * Returns the list of images for the given search criteria.
     *
     * @param Connection $ai_connection The AI connection.
     * @param string     $token The JWT token.
     * @param string     $business_description The business description.
     *
     * @return array|\WP_Error Array of images, or WP_Error if the request failed.
     */
    
public function get_images$ai_connection$token$business_description ) {
        
$business_description ContentProcessor::summarize_business_description$business_description$ai_connection$token );

        if ( 
str_word_count$business_description ) === ) {
            
$search_term $business_description;
        } else {
            
$search_term $this->define_search_term$ai_connection$token$business_description );
        }

        if ( 
is_wp_error$search_term ) ) {
            return 
$search_term;
        }

        
$required_images $this->total_number_required_images();

        if ( 
is_wp_error$required_images ) ) {
            return 
$required_images;
        }

        
$returned_images $this->request$search_term );

        if ( 
is_wp_error$returned_images ) ) {
            return 
$returned_images;
        }

        
$refined_images $this->refine_returned_images_results$ai_connection$token$business_description$returned_images );

        if ( 
is_wp_error$refined_images ) ) {
            return 
$returned_images;
        }

        
$refined_images_count count$refined_images );

        
$i      0;
        
$errors = array();
        while ( 
$refined_images_count $required_images && $i ) {
            
$i ++;
            
$search_term $this->define_search_term$ai_connection$token$business_description );

            if ( 
is_wp_error$search_term ) ) {
                
$errors[] = $search_term;
                continue;
            }

            
$images_to_add $this->request$search_term );

            if ( 
is_wp_error$images_to_add ) ) {
                
$errors[] = $images_to_add;
                continue;
            }

            
$images_to_add $this->refine_returned_images_results$ai_connection$token$business_description$images_to_add );

            if ( 
is_wp_error$images_to_add ) ) {
                
$errors[] = $images_to_add;
                continue;
            }

            
$refined_images array_merge$refined_images$images_to_add );
        }

        if ( 
$refined_images_count $required_images && ! empty( $errors ) ) {
            return new 
\WP_Error'ai_service_unavailable'__'AI Service is unavailable, try again later.''woocommerce' ), $errors );
        }

        if ( empty( 
$refined_images ) ) {
            return new 
\WP_Error'woocommerce_no_images_found'__'No images found.''woocommerce' ) );
        }

        return array(
            
'images'      => $refined_images,
            
'search_term' => $search_term,
        );
    }

    
/**
     * Define the search term to be used on Pexels using the AI endpoint.
     *
     * The search term is a shorter description of the business.
     *
     * @param Connection $ai_connection The AI connection.
     * @param string     $token The JWT token.
     * @param string     $business_description The business description.
     *
     * @return mixed|\WP_Error
     */
    
private function define_search_term$ai_connection$token$business_description ) {

        
$prompt sprintf'You are a teacher. Based on the following business description, \'%s\', describe to a child exactly what this store is selling in one or two words and be as precise as you can possibly be. Do not reply with generic words that could cause confusion and be associated with other businesses as a response. Make sure you do not add double quotes in your response. Do not add any explanations in the response'$business_description );

        
$response $ai_connection->fetch_ai_response$token$prompt30 );

        if ( 
is_wp_error$response ) ) {
            return 
$response;
        }

        if ( isset( 
$response['code'] ) && 'completion_error' === $response['code'] ) {
            return new 
\WP_Error'search_term_definition_failed'__'The search term definition failed.''woocommerce' ) );
        }

        if ( ! isset( 
$response['completion'] ) ) {
            return new 
\WP_Error'search_term_definition_failed'__'The search term definition failed.''woocommerce' ) );
        }

        return 
$response['completion'];
    }

    
/**
     * Refine the results returned by Pexels API.
     *
     * @param  Connection $ai_connection  The AI connection.
     * @param  string     $token  The JWT token.
     * @param  string     $business_description  The business description.
     * @param  array      $returned_images  The returned images.
     *
     * @return array|\WP_Error The refined images, or WP_Error if the request failed.
     */
    
private function refine_returned_images_results$ai_connection$token$business_description$returned_images ) {
        
$image_titles = array();
        foreach ( 
$returned_images as $returned_image ) {
            if ( isset( 
$returned_image['title'] ) ) {
                
$image_titles[] = $returned_image['title'];
            }
        }

        
$prompt sprintf'Given that you own a store described as "%s", remove from the following JSON all titles that do not represent products that could be sold on your store: %s'$business_descriptionwp_json_encode$image_titles ) );

        
$response $ai_connection->fetch_ai_response$token$prompt30 );

        if ( 
is_wp_error$response ) || ! isset( $response['completion'] ) ) {
            return 
$returned_images;
        }

        
$filtered_image_titles json_decode$response['completion'] );

        if ( ! 
is_array$filtered_image_titles ) ) {
            
$response $ai_connection->fetch_ai_response$token$prompt30 );

            if ( 
is_wp_error$response ) || ! isset( $response['completion'] ) ) {
                return 
$returned_images;
            }

            
$filtered_image_titles json_decode$response['completion'] );
        }

        if ( ! 
is_array$filtered_image_titles ) ) {
            return new 
\WP_Error'ai_service_unavailable'__'AI Service is unavailable, try again later.''woocommerce' ) );
        }

        
// Remove the images that are not aligned with the business description.
        
foreach ( $returned_images as $returned_image ) {
            if ( isset( 
$returned_image['title'] ) && ! in_array$returned_image['title'], $filtered_image_titlestrue ) ) {
                unset( 
$returned_image );
            }
        }

        return 
$returned_images;
    }

    
/**
     * Make a request to the Pexels API.
     *
     * @param string $search_term The search term to use.
     * @param int    $per_page The number of images to return.
     *
     * @return array|\WP_Error The response body, or WP_Error if the request failed.
     */
    
private function requeststring $search_termint $per_page 100 ) {
        
$request = new \WP_REST_Request'GET'self::EXTERNAL_MEDIA_PEXELS_ENDPOINT );

        
$request->set_param'search'esc_html$search_term ) );
        
$request->set_param'number'$per_page );
        
$request->set_param'size''small' );

        
$response      rest_do_request$request );
        
$response_data $response->get_data();

        if ( 
$response->is_error() ) {
            
$error_msg = [
                
'code' => $response->get_status(),
                
'data' => $response_data,
            ];

            return new 
\WP_Error'pexels_api_error'__'Request to the Pexels API failed.''woocommerce' ), $error_msg );
        }

        
$response $response_data['media'] ?? $response_data;

        if ( 
is_array$response ) ) {
            
shuffle$response );

            return 
$response;
        }

        return array();
    }

    
/**
     * Total number of required images.
     *
     * @return array|\WP_Error The total number of required images, or WP_Error if the request failed.
     */
    
private function total_number_required_images() {
        
$patterns_dictionary UpdatePatterns::get_patterns_dictionary();

        if ( 
is_wp_error$patterns_dictionary ) ) {
            return 
$patterns_dictionary;
        }

        
$required_images 0;
        foreach ( 
$patterns_dictionary as $pattern ) {
            if ( isset( 
$pattern['images_total'] ) && $pattern['images_total'] > ) {
                
$required_images += $pattern['images_total'];
            }
        }

        
// Adding +6 images for the dummy products.
        
$required_images += 6;

        return 
$required_images;
    }
}