|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\alt_text_review\Service; |
| 4 | + |
| 5 | +use Drupal\Core\Config\ConfigFactoryInterface; |
| 6 | +use Drupal\Core\File\FileSystemInterface; |
| 7 | +use Drupal\Core\Image\ImageFactory; |
| 8 | +use Drupal\Core\Logger\LoggerChannelFactoryInterface; |
| 9 | +use GuzzleHttp\ClientInterface; |
| 10 | +use GuzzleHttp\Exception\RequestException; |
| 11 | +use GuzzleHttp\Psr7\Message; |
| 12 | + |
| 13 | +class AltTextGenerator |
| 14 | +{ |
| 15 | + |
| 16 | + protected $httpClient; |
| 17 | + protected $configFactory; |
| 18 | + protected $imageFactory; |
| 19 | + protected $fileSystem; |
| 20 | + protected $logger; |
| 21 | + |
| 22 | + public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory, ImageFactory $image_factory, FileSystemInterface $file_system, LoggerChannelFactoryInterface $logger_factory) |
| 23 | + { |
| 24 | + $this->httpClient = $http_client; |
| 25 | + $this->configFactory = $config_factory; |
| 26 | + $this->imageFactory = $image_factory; |
| 27 | + $this->fileSystem = $file_system; |
| 28 | + $this->logger = $logger_factory->get('alt_text_review'); |
| 29 | + } |
| 30 | + |
| 31 | + public function generateAltText(string $image_uri): string |
| 32 | + { |
| 33 | + $config = $this->configFactory->get('alt_text_review.settings'); |
| 34 | + $api_key = trim($config->get('openai_api_key')); |
| 35 | + $debug_mode = $config->get('debug_mode') ?? FALSE; |
| 36 | + |
| 37 | + if (empty($api_key)) { |
| 38 | + return 'Error: OpenAI API key is not configured.'; |
| 39 | + } |
| 40 | + |
| 41 | + if (!is_file($image_uri)) { |
| 42 | + $this->logger->error('Image file not found at URI: @uri', ['@uri' => $image_uri]); |
| 43 | + return 'Error: Image file not found.'; |
| 44 | + } |
| 45 | + |
| 46 | + $image_data = file_get_contents($image_uri); |
| 47 | + $mime_type = finfo_buffer(finfo_open(), $image_data, FILEINFO_MIME_TYPE); |
| 48 | + $base64 = base64_encode($image_data); |
| 49 | + $data_uri = 'data:' . $mime_type . ';base64,' . $base64; |
| 50 | + |
| 51 | + $max_length = $config->get('alt_text_max_length') ?? 128; |
| 52 | + $max_tokens = (int) ceil($max_length / 4); #calculate a token budget (approx. 4 chars/token) |
| 53 | + $prompt_template = $config->get('ai_prompt') ?? 'Generate a concise alt text for this image, within [max_length] characters maximum.'; |
| 54 | + $prompt_text = str_replace('[max_length]', $max_length, $prompt_template); |
| 55 | + |
| 56 | + $request_options = [ |
| 57 | + 'headers' => [ |
| 58 | + 'Authorization' => 'Bearer ' . $api_key, |
| 59 | + 'Content-Type' => 'application/json', |
| 60 | + ], |
| 61 | + 'json' => [ |
| 62 | + 'model' => 'gpt-4o-mini', |
| 63 | + 'messages' => [ |
| 64 | + [ |
| 65 | + 'role' => 'user', |
| 66 | + 'content' => [ |
| 67 | + ['type' => 'text', 'text' => $prompt_text], |
| 68 | + ['type' => 'image_url', 'image_url' => ['url' => $data_uri]], |
| 69 | + ], |
| 70 | + ], |
| 71 | + ], |
| 72 | + 'max_tokens' => $max_tokens, |
| 73 | + ], |
| 74 | + ]; |
| 75 | + |
| 76 | + if ($debug_mode) { |
| 77 | + $this->logger->debug('OpenAI Request Body: @json', ['@json' => json_encode($request_options['json'], JSON_PRETTY_PRINT)]); |
| 78 | + } |
| 79 | + |
| 80 | + try { |
| 81 | + $response = $this->httpClient->post('https://api.openai.com/v1/chat/completions', $request_options); |
| 82 | + $body = $response->getBody()->getContents(); |
| 83 | + if ($debug_mode) { |
| 84 | + $this->logger->debug('OpenAI Response: @body', ['@body' => $body]); |
| 85 | + } |
| 86 | + $data = json_decode($body, TRUE); |
| 87 | + return trim($data['choices'][0]['message']['content'] ?? ''); |
| 88 | + } |
| 89 | + catch (RequestException $e) { |
| 90 | + $this->logger->error('OpenAI API request failed: @message', ['@message' => $e->getMessage()]); |
| 91 | + if ($debug_mode && $e->hasResponse()) { |
| 92 | + $this->logger->debug("--- DEBUG: FAILED REQUEST ---\n@request\n\n--- DEBUG: FAILED RESPONSE ---\n@response", [ |
| 93 | + '@request' => Message::toString($e->getRequest()), |
| 94 | + '@response' => Message::toString($e->getResponse()), |
| 95 | + ]); |
| 96 | + } |
| 97 | + return 'Error: The AI suggestion could not be generated.'; |
| 98 | + } |
| 99 | + } |
| 100 | +} |
0 commit comments