Skip to content
Snippets Groups Projects
Commit 8b434bcd authored by aron novak's avatar aron novak Committed by Ullrich Neiss
Browse files

Resolve #3369986 "Make backend swappable" add support for Alttext.ai

parent cdd84f4e
No related branches found
No related tags found
1 merge request!6Resolve #3369986 "Make backend swappable"
.idea
......@@ -136,9 +136,11 @@ function disableButton(array &$form, FormStateInterface $form_state) {
* File ID.
*/
function auto_alter_get_description($fid) {
if (\Drupal::service('auto_alter.get_description')->checksetup() === FALSE) {
$engine = auto_alter_get_engine();
if ($engine->checkSetup() === FALSE) {
\Drupal::messenger()->addStatus(
t('Microsoft Azure API key and Endpoint URL is not set and it is required for the module to work. Please set it up at the <a href=":settings">Image Automatic Alternative Text settings page</a>.', [
t('The selected AI engine is not set and it is required for the module to work. Please set it up at the <a href=":settings">Image Automatic Alternative Text settings page</a>.', [
':settings' => Url::fromRoute('auto_alter.settings')->toString(),
])
);
......@@ -147,18 +149,13 @@ function auto_alter_get_description($fid) {
$entity_manager = \Drupal::entityTypeManager();
$status = \Drupal::config('auto_alter.settings')->get('status');
$file = $entity_manager->getStorage('file')->load($fid);
$uri = \Drupal::service('auto_alter.get_description')->geturi($file);
$uri = $engine->getUri($file);
$path = \Drupal::service('file_system')->realpath($uri);
$path = $path ? $path : $uri;
$request = \Drupal::service('auto_alter.get_description')->getdescription($path);
if ($request !== FALSE && $request->getStatusCode() == 200) {
$response = json_decode($request->getBody());
if (isset($response->description->captions[0]->text)) {
$alternate_text = $response->description->captions[0]->text;
}
else if (isset($response->description->tags)) {
$alternate_text = rtrim(implode(',', $response->description->tags), ',');
}
$description = $engine->getDescription($path);
if (!empty($description)) {
$alternate_text = $description;
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('auto_alter_translate')) {
$active = \Drupal::config('auto_alter_translate.settings')->get('active');
......@@ -171,16 +168,9 @@ function auto_alter_get_description($fid) {
}
}
if ($status) {
if (isset($response->description->captions[0]->confidence)) {
$percent_friendly = number_format($response->description->captions[0]->confidence * 100, 2) . '%';
\Drupal::messenger()->addStatus(t('Alternate text has been changed to: %text" by a confidence of :confidence', ['%text' => $alternate_text, ':confidence' => $percent_friendly]));
}
else {
\Drupal::messenger()->addStatus(t('Alternate text has been changed to: %text", but with no confidence', ['%text' => $alternate_text]));
}
\Drupal::messenger()->addStatus(t('Alternate text has been changed to: %text"', ['%text' => $alternate_text]));
}
return $alternate_text;
}
else {
if ($status) {
......@@ -190,3 +180,20 @@ function auto_alter_get_description($fid) {
}
}
/**
* Returns the currently selected engine.
*
* @return \Drupal\auto_alter\DescribeImageServiceInterface
* The currently selected engine.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
function auto_alter_get_engine() {
$engine = \Drupal::config('auto_alter.settings')->get('engine');
/** @var \Drupal\auto_alter\Plugin\AutoAlterDescribeImagePluginManager $plugin_manager */
$plugin_manager = \Drupal::service('plugin.manager.auto_alter_describe_image');
/** @var \Drupal\auto_alter\DescribeImageServiceInterface $plugin */
$plugin = $plugin_manager->createInstance($engine);
return $plugin;
}
services:
auto_alter.get_description:
class: Drupal\auto_alter\AzureVision
arguments: ["@file_system", "@http_client", "@config.factory", "@logger.factory"]
plugin.manager.auto_alter_describe_image:
class: \Drupal\auto_alter\Plugin\AutoAlterDescribeImagePluginManager
parent: default_plugin_manager
<?php
namespace Drupal\auto_alter\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a reusable Auto Alter Describe Image plugin annotation object.
*
* @Annotation
*/
class AutoAlterDescribeImage extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The name of the form plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $name;
}
<?php
namespace Drupal\auto_alter;
use Drupal\file\Entity\File;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Component\Plugin\PluginInspectionInterface;
/**
* Interface for the DescribeImageService service.
*/
interface DescribeImageServiceInterface extends PluginInspectionInterface, ContainerFactoryPluginInterface {
/**
* Checks if setup is complete.
*
* @return bool
* TRUE if the setup is complete, FALSE otherwise.
*/
public function checkSetup();
/**
* Get the correct URI of the image.
*
* @param \Drupal\file\Entity\File $file
* The file entity.
*
* @return string
* The URI of the image.
*/
public function getUri(File $file);
/**
* Get the description of the image.
*
* @param string $uri_or_realpath
* The URI or relative path of the image.
*
* @return \Psr\Http\Message\ResponseInterface|bool
* The response from the Azure Cognitive Services API.
*/
public function getDescription(string $uri_or_realpath);
/**
* Build the configuration form.
*
* @return array
*/
public function buildConfigurationForm();
/**
* Validate the configuration form.
*
* @param $form_state
*/
public function validateConfigurationForm($form_state);
/**
* Submit the configuration form.
*
* @param $form_state
* @param $config
*/
public function submitConfigurationForm($form_state, $config);
}
......@@ -3,9 +3,9 @@
namespace Drupal\auto_alter\Form;
use Drupal\auto_alter\AutoAlterCredentials;
use Drupal\auto_alter\Plugin\AutoAlterDescribeImagePluginManager;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\auto_alter\AzureVision;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -32,13 +32,6 @@ class AutoAlterSettingsForm extends ConfigFormBase {
];
}
/**
* The file AzureVision service.
*
* @var Drupal\auto_alter\AzureVision
*/
protected $azurevision;
/**
* The Module Handler.
*
......@@ -49,9 +42,9 @@ class AutoAlterSettingsForm extends ConfigFormBase {
/**
* Class constructor.
*/
public function __construct(AzureVision $azure_vision, ModuleHandlerInterface $module_handler) {
$this->azurevision = $azure_vision;
public function __construct(ModuleHandlerInterface $module_handler, AutoAlterDescribeImagePluginManager $describe_image) {
$this->modulehandler = $module_handler;
$this->describeImage = $describe_image;
}
/**
......@@ -60,9 +53,8 @@ class AutoAlterSettingsForm extends ConfigFormBase {
public static function create(ContainerInterface $container) {
// Instantiates this form class.
return new static(
// Load the service required to construct this class.
$container->get('auto_alter.get_description'),
$container->get('module_handler')
$container->get('module_handler'),
$container->get('plugin.manager.auto_alter_describe_image')
);
}
......@@ -72,80 +64,38 @@ class AutoAlterSettingsForm extends ConfigFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('auto_alter.settings');
$form['settings'] = [
'#type' => 'details',
'#title' => $this->t('Automatic Alternative Text settings'),
'#open' => TRUE,
'#description' => $this->t('Thanks for installing Automatic Alternative Text! To start receiving alt text, enter your API key. Don\'t have one yet? Sign up <a href="@url" target="_blank">@url</a>.', [
'@url' => 'https://www.microsoft.com/cognitive-services',
]),
];
$section =& $form['settings'];
$section['credentials'] = [
'#id' => 'credentials',
'#type' => 'details',
'#title' => $this->t('Credentials'),
'#open' => TRUE,
'#tree' => TRUE,
];
$options = [];
$plugins = $this->describeImage->getDefinitions();
foreach ($plugins as $plugin) {
$options[$plugin['id']] = $plugin['title'];
}
$section['credentials']['credential_provider'] = [
$form['engine'] = [
'#type' => 'select',
'#title' => $this->t('Credential provider'),
'#options' => [
'config' => $this->t('Local configuration'),
'#title' => $this->t('Image description engine'),
'#options' => $options,
'#required' => TRUE,
'#default_value' => $config->get('engine'),
'#ajax' => [
'callback' => '::updateEngineConfiguration',
'wrapper' => 'engine-configuration-wrapper',
],
'#default_value' => $config->get('credential_provider'),
];
$section['credentials']['providers'] = [
'#type' => 'item',
'#id' => 'credentials_configuration',
$form['engine_configuration'] = [
'#type' => 'container',
'#attributes' => ['id' => 'engine-configuration-wrapper'],
];
$provider_config_state = [':input[name="credentials[credential_provider]"]' => ['value' => 'config']];
$section['credentials']['providers']['config']['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API Key (config)'),
'#default_value' => $config->get('credentials.config.api_key'),
'#states' => [
'visible' => $provider_config_state,
'required' => $provider_config_state,
],
];
if (\Drupal::moduleHandler()->moduleExists('key')) {
$section['credentials']['credential_provider']['#options']['key'] = $this->t('Key Module');
$provider_key_state = [':input[name="credentials[credential_provider]"]' => ['value' => 'key']];
$section['credentials']['providers']['key']['api_key_key'] = [
'#type' => 'key_select',
'#title' => $this->t('API Key (Key)'),
'#default_value' => $config->get('credentials.key.api_key_key'),
'#empty_option' => $this->t('- Please select -'),
'#key_filters' => ['type' => 'authentication'],
'#description' => $this->t('Your API key stored as a secure key.'),
'#states' => [
'visible' => $provider_key_state,
'required' => $provider_key_state,
],
];
}
else {
$section['credentials']['credential_provider']['#value'] = 'config';
$section['credentials']['credential_provider']['#disabled'] = TRUE;
// Load the configuration form for the selected engine.
$engine_id = $form_state->getValue('engine', $config->get('engine'));
if (isset($plugins[$engine_id])) {
$plugin = $this->describeImage->createInstance($engine_id);
$form['engine_configuration'] += $plugin->buildConfigurationForm([], $form_state);
}
$form['settings']['endpoint'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => $this->t('URL of Endpoint'),
'#default_value' => $config->get('endpoint'),
'#description' => $this->t('Enter the URL of your Endpoint here. fe. https://westeurope.api.cognitive.microsoft.com/vision/v1.0/describe?maxCandidates=1 for West Europe'),
];
$form['settings']['status'] = [
$form['status'] = [
'#type' => 'checkbox',
'#required' => FALSE,
'#title' => $this->t('Show status message to user'),
......@@ -153,7 +103,7 @@ class AutoAlterSettingsForm extends ConfigFormBase {
'#description' => $this->t('If checked, a status message is generated after saving: "Alternate text has been changed to: "%text" by a confidence of %confidence"'),
];
$form['settings']['suggestion'] = [
$form['suggestion'] = [
'#type' => 'checkbox',
'#required' => FALSE,
'#title' => $this->t('Make suggestion for alternative text'),
......@@ -163,51 +113,35 @@ class AutoAlterSettingsForm extends ConfigFormBase {
return parent::buildForm($form, $form_state);
}
public function updateEngineConfiguration(array $form, FormStateInterface $form_state) {
return $form['engine_configuration'];
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$endpoint = $values['endpoint'];
$credentials = new AutoAlterCredentials();
$credential_provider = $form_state->getValue(['credentials', 'credential_provider']);
$credentials_values = $form_state->getValue(['credentials', 'providers']);
$credentials->setCredentials($credential_provider, $credentials_values ?? []);
$api_key = $credentials->getApikey();
$path = $this->modulehandler->getModule('auto_alter')->getPath();
$request = $this->azurevision->getdescription($path . '/image/test.jpg', $endpoint, $api_key);
if ($request !== FALSE && $request->getStatusCode() == 200) {
\Drupal::messenger()->addStatus($this->t('Your settings have been successfully validated'));
}
else {
if ($request !== FALSE && $request->getStatusCode() == 401) {
$form_state->setErrorByName('credentials', $this->t('The API Key seems to be wrong. Please check in your Azure Console.'));
}
else {
$form_state->setErrorByName('endpoint', $this->t('The URL for the endpoint seems to be wrong. Please check in your Azure Console.'));
}
if ($form_state->getTriggeringElement()['#id'] !== 'edit-submit') {
return;
}
$engine = $form_state->getValue('engine');
$plugin = $this->describeImage->createInstance($engine);
$plugin->validateConfigurationForm($form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$credential_provider = $form_state->getValue(['credentials', 'credential_provider']);
$credentials = $form_state->getValue([
'credentials',
'providers',
$credential_provider,
]);
$this->config('auto_alter.settings')
->set('endpoint', $values['endpoint'])
->set('credential_provider', $credential_provider)
->set('credentials', [])
->set("credentials.$credential_provider", $credentials)
$values = &$form_state->getValues();
$engine = $form_state->getValue('engine');
$plugin = $this->describeImage->createInstance($engine);
$config = $this->config('auto_alter.settings');
$plugin->submitConfigurationForm($form_state, $config);
$config
->set('status', $values['status'])
->set('engine', $values['engine'])
->set('suggestion', $values['suggestion'])
->save();
......
<?php
namespace Drupal\auto_alter;
namespace Drupal\auto_alter\Plugin\AutoAlterDescribeImage;
use Drupal\auto_alter\DescribeImageServiceInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Link;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use GuzzleHttp\ClientInterface;
......@@ -13,9 +18,16 @@ use GuzzleHttp\Exception\RequestException;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The class to connect to Azure Cognitive Service.
* Alttext.ai integration.
*
* @AutoAlterDescribeImage(
* id = "alttext_ai",
* title = @Translation("Alttext.AI"),
* )
*/
class AzureVision {
class AlttextAi implements DescribeImageServiceInterface {
use StringTranslationTrait;
/**
* The file system service.
......@@ -46,40 +58,49 @@ class AzureVision {
protected $loggerFactory;
/**
* API key credentials
* The config object.
*
* @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* The messenger service.
*
* @var AutoAlterCredentials
* @var \Drupal\auto_alter\Plugin\AutoAlterDescribeImage\MessengerInterface
*/
protected $credentials;
protected $messenger;
/**
* Class constructor.
*/
public function __construct(FileSystemInterface $file_system, ClientInterface $http_client, ConfigFactory $configFactory, LoggerChannelFactoryInterface $loggerFactory) {
public function __construct(FileSystemInterface $file_system, ClientInterface $http_client, ConfigFactory $configFactory, LoggerChannelFactoryInterface $loggerFactory, MessengerInterface $messenger) {
$this->fileSystem = $file_system;
$this->httpClient = $http_client;
$this->config = $configFactory->get('auto_alter.settings');
$this->credentials = new AutoAlterCredentials($this->config);
$this->loggerFactory = $loggerFactory->get('auto_alter');
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('file_system'),
$container->get('http_client')
$container->get('http_client'),
$container->get('config.factory'),
$container->get('logger.factory'),
$container->get('messenger')
);
}
/**
* Check if setup is complete.
* {@inheritDoc}
*/
public function checksetup() {
$endpoint = Xss::filter($this->config->get('endpoint'));
$api_key = Xss::filter($this->credentials->getApikey());
if (empty($api_key) || empty($endpoint)) {
public function checkSetup() {
$api_key = Xss::filter($this->config->get('api_key'));
if (empty($api_key)) {
return FALSE;
}
else {
......@@ -88,9 +109,9 @@ class AzureVision {
}
/**
* Get the correct URI of the image.
* {@inheritDoc}
*/
public function geturi(File $file) {
public function getUri(File $file) {
$filesize = $file->getSize();
$uri = $file->get('uri')->value;
if ($filesize > 1048576) {
......@@ -103,53 +124,99 @@ class AzureVision {
}
/**
* Get the description of the image.
* {@inheritDoc}
*/
public function getdescription(string $uri_or_relpath, $endpoint = FALSE, $api_key = FALSE) {
$path = $this->fileSystem->realpath($uri_or_relpath);
$client = $this->httpClient;
if(empty($path)) {
$body = [
'json' => [
'url' => \Drupal::service('file_url_generator')->generateAbsoluteString($uri_or_relpath)
]
public function getDescription(string $uri_or_realpath) {
$path = $this->fileSystem->realpath($uri_or_realpath);
// We might want to force image upload from local environments.
if(empty($path) && !empty(getenv('ALTTEXT_AI_FORCE_IMAGE_UPLOAD'))) {
$json = [
'url' => file_create_url($uri_or_realpath),
];
} else {
$body = [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($path, "r"),
],
}
else {
$json = [
'image' => [
'raw' => base64_encode(file_get_contents($path)),
],
];
}
try {
$endpoint = $endpoint ? $endpoint : $this->config->get('endpoint');
$api_key = $api_key ? $api_key : $this->credentials->getApikey();
$body['headers'] = [
'Ocp-Apim-Subscription-Key' => Xss::filter($api_key),
];
$request = $client->post(Xss::filter($endpoint), $body);
}
catch (RequestException $e) {
$this->loggerFactory->error(
"Azure Cognitive Services error code @code: @message",
[
'@code' => $e->getCode(),
'@message' => $e->getMessage(),
]
);
if ($e->hasResponse()) {
$request = $e->getResponse();
$response = $this->httpClient->post('https://alttext.ai/api/v1/images', [
'headers' => ['X-API-Key' => $this->config->get('api_key')],
'json' => $json,
]);
if (empty($response)) {
$this->messenger->addWarning($this->t('The Alttext.AI service returned an empty response.'));
return '';
}
if ($response->getStatusCode() == 200) {
$data = json_decode($response->getBody(), TRUE);
if (!empty($data['alt_text'])) {
return $data['alt_text'];
}
}
else {
$request = FALSE;
$this->messenger->addWarning($this->t('The Alttext.AI service returned an error: @error', [
'@error' => $response->getReasonPhrase(),
]));
}
}
return $request;
catch (\Exception $e) {
$this->messenger->addWarning($this->t('The Alttext.AI service returned an error: @error', [
'@error' => $e->getMessage(),
]));
}
return '';
}
public function getPluginId() {
return 'alttext_ai';
}
/**
* {@inheritDoc}
*/
public function getPluginDefinition() {
return [
'id' => 'azure_cognitive_services',
'title' => 'Azure Cognitive Services',
];
}
public function buildConfigurationForm() {
$form = [];
$form['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API Key'),
'#description' => $this->t('The API key for @link', [
'@link' => Link::fromTextAndUrl($this->t('Alttext.AI'), Url::fromUri('https://alttext.ai/'))->toString(),
]),
'#default_value' => $this->config->get('api_key'),
'#required' => TRUE,
];
return $form;
}
/**
* {@inheritDoc}
*/
public function validateConfigurationForm($form_state) {
// The API key is at least 32 characters long.
if (strlen($form_state->getValue('api_key')) < 32) {
$form_state->setErrorByName('api_key', $this->t('The API key is invalid.'));
}
}
/**
* {@inheritDoc}
*/
public function submitConfigurationForm($form_state, $config) {
$api_key = $form_state->getValue('api_key');
$config->set('api_key', $api_key)->save();
}
}
<?php
namespace Drupal\auto_alter\Plugin\AutoAlterDescribeImage;
use Drupal\auto_alter\AutoAlterCredentials;
use Drupal\auto_alter\DescribeImageServiceInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Component\Utility\Xss;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Azure Cognitive Service integration.
*
* @AutoAlterDescribeImage(
* id = "azure_cognitive_services",
* title = @Translation("Azure Cognitive Services"),
* )
*/
class AzureVision implements DescribeImageServiceInterface {
use StringTranslationTrait;
/**
* The file system service.
*
* @var Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The httpClient.
*
* @var GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* The ConfigFactory.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
private $configFactory;
/**
* Logger Factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
protected $pluginId = 'azure_cognitive_services';
protected $pluginDefinition = [
'id' => 'azure_cognitive_services',
'title' => 'Azure Cognitive Services',
];
/**
* The config object.
*
* @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Class constructor.
*/
public function __construct(FileSystemInterface $file_system, ClientInterface $http_client, ConfigFactory $configFactory, LoggerChannelFactoryInterface $loggerFactory, ModuleHandlerInterface $module_handler) {
$this->fileSystem = $file_system;
$this->httpClient = $http_client;
$this->config = $configFactory->getEditable('auto_alter.settings');
$this->loggerFactory = $loggerFactory->get('auto_alter');
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('file_system'),
$container->get('http_client'),
$container->get('config.factory'),
$container->get('logger.factory'),
$container->get('module_handler')
);
}
/**
* {@inheritDoc}
*/
public function checkSetup() {
$endpoint = Xss::filter($this->config->get('endpoint'));
$api_key = Xss::filter($this->config->get('api_key'));
if (empty($api_key) || empty($endpoint)) {
return FALSE;
}
else {
return TRUE;
}
}
/**
* {@inheritDoc}
*/
public function getUri(File $file) {
$filesize = $file->getSize();
$uri = $file->get('uri')->value;
if ($filesize > 1048576) {
$style = ImageStyle::load('auto_alter_help');
$original_uri = $uri;
$uri = $style->buildUri($original_uri);
$style->createDerivative($original_uri, $uri);
}
return $uri;
}
/**
* {@inheritDoc}
*/
public function getDescription(string $uri_or_realpath) {
$alternate_text = '';
$endpoint = $this->config->get('endpoint');
$api_key = $this->config->get('api_key');
$path = $this->fileSystem->realpath($uri_or_realpath);
$client = $this->httpClient;
if(empty($path)) {
$body = [
'json' => [
'url' => file_create_url($uri_or_realpath)
]
];
} else {
$body = [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($path, "r"),
],
],
];
}
try {
$endpoint = $endpoint ?: $this->config->get('endpoint');
$api_key = $api_key ?: $this->config->get('api_key');
$body['headers'] = [
'Ocp-Apim-Subscription-Key' => Xss::filter($api_key),
];
$request = $client->post(Xss::filter($endpoint), $body);
}
catch (\Exception $e) {
$this->loggerFactory->error(
"Azure Cognitive Services error code @code: @message",
[
'@code' => $e->getCode(),
'@message' => $e->getMessage(),
]
);
return '';
}
if ($request !== FALSE && $request->getStatusCode() == 200) {
$response = json_decode($request->getBody());
if (isset($response->description->captions[0]->text)) {
$alternate_text = $response->description->captions[0]->text;
}
else {
if (isset($response->description->tags)) {
$alternate_text = rtrim(implode(',', $response->description->tags), ',');
}
}
if ($this->moduleHandler->moduleExists('auto_alter_translate')) {
$active = \Drupal::config('auto_alter_translate.settings')
->get('active');
if ($active) {
$request = \Drupal::service('auto_alter_translate.get_translation')
->gettranslation($alternate_text);
if (!empty($request) && $request->getStatusCode() == 200) {
$trans = (array) json_decode($request->getBody());
$alternate_text = $trans[0]->translations[0]->text;
}
}
}
}
return $alternate_text;
}
/**
* {@inheritDoc}
*/
public function getPluginId() {
return $this->pluginId;
}
/**
* {@inheritDoc}
*/
public function getPluginDefinition() {
return $this->pluginDefinition;
}
/**
* {@inheritDoc}
*/
public function buildConfigurationForm() {
$form = [];
$form['credentials'] = [
'#id' => 'credentials',
'#type' => 'details',
'#title' => $this->t('Credentials'),
'#open' => TRUE,
'#tree' => TRUE,
];
$form['credentials']['credential_provider'] = [
'#type' => 'select',
'#title' => $this->t('Credential provider'),
'#options' => [
'config' => $this->t('Local configuration'),
],
'#default_value' => $this->config->get('credential_provider'),
];
$form['credentials']['providers'] = [
'#type' => 'item',
'#id' => 'credentials_configuration',
];
$provider_config_state = [':input[name="credentials[credential_provider]"]' => ['value' => 'config']];
$form['credentials']['providers']['config']['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API Key (config)'),
'#default_value' => $this->config->get('credentials.config.api_key'),
'#states' => [
'visible' => $provider_config_state,
'required' => $provider_config_state,
],
];
if (\Drupal::moduleHandler()->moduleExists('key')) {
$section['credentials']['credential_provider']['#options']['key'] = $this->t('Key Module');
$provider_key_state = [':input[name="credentials[credential_provider]"]' => ['value' => 'key']];
$form['credentials']['providers']['key']['api_key_key'] = [
'#type' => 'key_select',
'#title' => $this->t('API Key (Key)'),
'#default_value' => $this->config->get('credentials.key.api_key_key'),
'#empty_option' => $this->t('- Please select -'),
'#key_filters' => ['type' => 'authentication'],
'#description' => $this->t('Your API key stored as a secure key.'),
'#states' => [
'visible' => $provider_key_state,
'required' => $provider_key_state,
],
];
}
else {
$form['credentials']['credential_provider']['#value'] = 'config';
$form['credentials']['credential_provider']['#disabled'] = TRUE;
}
$form['endpoint'] = [
'#type' => 'textfield',
'#required' => TRUE,
'#title' => $this->t('URL of Endpoint'),
'#default_value' => $this->config->get('endpoint'),
'#description' => $this->t('Enter the URL of your Endpoint here. fe. https://westeurope.api.cognitive.microsoft.com/vision/v1.0/describe?maxCandidates=1 for West Europe'),
];
return $form;
}
/**
* {@inheritDoc}
*/
public function validateConfigurationForm($form_state) {
$values = $form_state->getValues();
$endpoint = $values['endpoint'];
$credentials = new AutoAlterCredentials();
$credential_provider = $form_state->getValue(['credentials', 'credential_provider']);
$credentials_values = $form_state->getValue(['credentials', 'providers']);
$credentials->setCredentials($credential_provider, $credentials_values ?? []);
$api_key = $credentials->getApikey();
$path = $this->moduleHandler->getModule('auto_alter')->getPath();
$this->config->set('endpoint', $endpoint);
$this->config->set('api_key', $api_key);
$alt = $this->getDescription($path . '/image/test.jpg');
if (!empty($alt)) {
\Drupal::messenger()->addStatus($this->t('Your settings have been successfully validated'));
}
else {
$form_state->setErrorByName('credentials', $this->t('The API Key or the endpoint seem to be wrong. Please check in your Azure Console.'));
}
}
/**
* {@inheritDoc}
*/
public function submitConfigurationForm($form_state, $config) {
$values = $form_state->getValues();
$credential_provider = $form_state->getValue(['credentials', 'credential_provider']);
$credentials = $form_state->getValue([
'credentials',
'providers',
$credential_provider,
]);
$config
->set('endpoint', $values['endpoint'])
->set('credential_provider', $credential_provider)
->set('credentials', [])
->set("credentials.$credential_provider", $credentials)
->set('status', $values['status'])
->set('suggestion', $values['suggestion'])
->save();
}
}
<?php
namespace Drupal\auto_alter\Plugin;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Manages describe image plugins.
*
* @ingroup auto_alter
*/
class AutoAlterDescribeImagePluginManager extends DefaultPluginManager {
/**
* {@inheritdoc}
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/AutoAlterDescribeImage', $namespaces, $module_handler, 'Drupal\auto_alter\DescribeImageServiceInterface', 'Drupal\auto_alter\Annotation\AutoAlterDescribeImage');
$this->alterInfo('auto_alter_describe_image_info');
$this->setCacheBackend($cache_backend, 'auto_alter_describe_image');
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment