PluginProbe
Auto Alt Text / 1.3.2
Auto Alt Text v1.3.2
3.0.3 2.8.2 1.3.1 1.3.2 2.0.0 2.1.0 2.1.1 2.2.0 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.4.0 2.4.1 2.4.2 2.5.0 2.5.1 2.5.2 2.5.3 2.6.0 2.6.1 2.7.0 2.8.0 2.8.1 All 28 releases
auto-alt-text / src / App / AIProviders / OpenAI / OpenAIResponse.php

OpenAIResponse.php in Auto Alt Text 1.3.2, at src/App/AIProviders/OpenAI/OpenAIResponse.php

89 lines 2.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace AATXT\App\AIProviders\OpenAI;
3
4 use AATXT\App\Admin\PluginOptions;
5 use AATXT\App\AIProviders\AIProviderInterface;
6 use AATXT\App\Exceptions\OpenAI\OpenAIException;
7 use AATXT\Config\Constants;
8
9 abstract class OpenAIResponse implements AIProviderInterface
10 {
11 abstract public function response(string $imageUrl): string;
12
13 /**
14 * Send the request to the OpenAI APIs and return the decoded response
15 * @param array $requestBody
16 * @param string $endpoint
17 * @return array
18 * @throws OpenAIException
19 */
20 protected function decodedResponseBody(array $requestBody, string $endpoint): array
21 {
22
23 $apiKey = PluginOptions::apiKeyOpenAI();
24
25 $headers = [
26 'Authorization' => 'Bearer ' . $apiKey,
27 'Content-Type' => 'application/json; charset=utf-8',
28 ];
29
30 $args = [
31 'headers' => $headers,
32 'body' => json_encode($requestBody),
33 'method' => 'POST',
34 'data_format' => 'body',
35 ];
36
37 $response = wp_remote_post($endpoint, $args);
38
39 if (is_wp_error($response)) {
40 $error_message = $response->get_error_message();
41 throw new OpenAIException("Something went wrong: $error_message");
42 }
43
44 $responseBody = wp_remote_retrieve_body($response);
45 $decodedBody = json_decode($responseBody, true);
46
47 if (isset($decodedBody['error'])) {
48 throw new OpenAIException('Error type: ' . $decodedBody['error']['type'] . ' - Error code: ' . $decodedBody['error']['code'] . ' - ' . $decodedBody['error']['message']);
49 }
50
51 return $decodedBody;
52
53 }
54
55 /**
56 * Return the main OpenAI prompt
57 * @return string
58 */
59 protected function prompt(): string
60 {
61 return PluginOptions::prompt() ?: Constants::AATXT_OPENAI_DEFAULT_PROMPT;
62 }
63
64 /**
65 * Compute the fallback prompt based on the template saved in the options and the imageUrl passed
66 * @param string $imageUrl
67 * @return string
68 */
69 protected function fallbackPrompt(string $imageUrl): string
70 {
71 $prompt = PluginOptions::fallbackPrompt() ?: Constants::AATXT_OPENAI_DEFAULT_FALLBACK_PROMPT;
72 return str_replace(Constants::AATXT_IMAGE_URL_TAG, $imageUrl, $prompt);
73 }
74
75 /**
76 * @param string $text
77 * @return string
78 */
79 protected function cleanString(string $text): string
80 {
81 $patterns = array(
82 '/\"/', // Double quotes
83 '/\s\s+/', // Double or more consecutive white spaces
84 '/&quot;/' // HTML sequence for double quotes
85 );
86
87 return trim(preg_replace($patterns, '', $text));
88 }
89 }