Sonata Extra Bundle exposes a translation API that delegates processing to a configurable provider. The application can thus translate a text into multiple languages while keeping the choice of provider at the configuration level.
Understanding the translation API
The translation API is a feature that leverages AI-powered translation services to provide automatic text translation. By integrating different translation providers, users can translate text into multiple languages without manual intervention.
Configuration
Here is an overview of the default configuration of the translation API feature in the Sonata Extra Bundle:
partitech_sonata_extra:
translation_api:
translate_on_create_page: true
default_provider: open_ai
providers:
open_ai:
class: Partitech\SonataExtra\Translation\Provider\OpenAiProvider
api_key: '%open_ai_api_key%'
model: '%open_ai_api_model%'
max_token_per_request: 200
Explanation of configuration settings:
- translate_on_create_page: When enabled, allows translation on the creation page.
- default_provider: Specifies the default translation provider to use. Set to null if you do not want to use the translation API.
- suppliers: A list of translation suppliers. Each supplier has its own set of configurations.
Store the key and the model name in environment variables. Avoid placing a secret key directly in the versioned YAML file.
partitech_sonata_extra:
translation_api:
providers:
open_ai:
api_key: '%open_ai_api_key%'
model: '%open_ai_api_model%'
OPEN_AI_API_KEY="[API_KEY]"
OPEN_AI_API_MODEL="[MODEL_NAME]"
Configurer le fournisseur OpenAI
Le fournisseur configuré par défaut est OpenAI. Ses principaux paramètres sont les suivants :
class: classe qui implémente le fournisseur.api_key: clé d’API, à injecter depuis une variable d’environnement.model: modèle utilisé pour la traduction ; vérifiez sa disponibilité dans la documentation du fournisseur.max_token_per_request: volume maximal envoyé par requête.
Ajouter un fournisseur
L’ajout d’un fournisseur repose sur deux étapes principales :
- Créer une classe de fournisseur :
- Créez une classe qui implémente
TranslationProviderInterface. - Implémentez la méthode
translate()avec le fournisseur choisi.
- Créez une classe qui implémente
namespace App\Translation\Provider;
class YourProvider implements TranslationProviderInterface
{
private $config;
public function setConfig($config)
{
// Your provider's configuration is automatically passed here
$this->config=$config;
}
public function translate(string $text, string $targetLanguage): string
{
// Translation logic here
return $translated_string;
}
public function translateArray(array $arrayOfText, string $targetLanguage): array
{
// Translation logic here
$translated_array[$key] = [
'original' => 'original text',
'translated' => 'translated text',
];
return $translated_array;
}
}
So you can call the translator anywhere
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Service\Attribute\Required;
use Partitech\SonataExtra\Translation\TranslationProviderFactoryInterface;
class TranslationController extends AbstractController
{
private TranslationProviderFactoryInterface $translationProviderFactory;
#[Required]
public function autowireDependencies(
TranslationProviderFactoryInterface $translationProviderFactory
):void{
$this->translationProviderFactory = $translationProviderFactory;
}
/**
* @Route("test/translate", name="translate")
*/
public function translate(Request $request): Response
{
/* you can force the provider */
$translationProvider = $this->translationProviderFactory->create('open_ai');
/* or you can use the default one */
$translationProvider = $this->translationProviderFactory->create();
$text = 'Il fera beau demain';
$targetLanguage = 'de';
/*
You can use any locals that the api can understand, depending on the service.
fr
fr_FR
*/
$translatedText = $translationProvider->translate($text, $targetLanguage);
return $this->render('translation/translate.html.twig', [
'original_text' => $text,
'translated_text' => $translatedText,
]);
}
}
- Update the configuration:
- Add your new supplier to the suppliers section in the configuration.
partitech_sonata_extra:
translation_api:
providers:
your_provider:
class: App\Translation\Provider\YourProvider
# Other provider-specific configuration here
By following these steps, you can add and configure new translation providers in order to extend the capabilities of the Translation API feature in the Sonata Extra Bundle.
Adapt the example to the installed version
The Symfony and Sonata examples remain tied to the versions indicated in the article. Symfony 4.x and Symfony 6.2 are no longer maintained: for a current project, use a maintained branch and the documentation that exactly matches your dependencies.
php bin/console about
composer show symfony/framework-bundle sonata-project/admin-bundle
Before resuming the code, check the signatures, services, routes, and templates concerned. Then add a functional test covering permissions, HTTP code, and the visible result.
Reference: maintained Symfony versions.