Pluggability of Transaltion service

In this guide, we will learn how to plugin a new translation service by extending the BaseTranslationClass interface.

You can seamlessly leverage it within existing Sakhi API workflows with minimal code changes.

Integration

Translation service is used for supporting multiple languages in Sakhi-api-service.

BaseTranslationClass

This BaseTranslationClass class has below methods which are to be implemented mandatorily.

Implementation

Let's say we create a YourTranslationClass class inheriting from BaseTranslationClass. The class needs to implement the following methods translate_text, text_to_speech and speech_to_text.

Add the necessary environment variables to .env file. TRANSLATION_TYPE is to be defined mandatorily.

TRANSLATION_TYPE=your_translation_service

Now go to the 'translation' folder and create your plugin 'your_translation_service.py'. Provide the implementation for the abstract methods.

your_translation_service.py

from translation.base import BaseTranslationClass


class YourTranslationClass(BaseTranslationClass):

    def translate_text(self, text: str, source: str, destination: str) -> str:
        # code to translate text
        return translated_text

    def text_to_speech(self, language: str, text: str) -> Any:
        return base_64_decoded_audio
        
    def speech_to_text(self, audio_file: Any, input_language: str) -> str:
        return transcripted_text    

Go to the 'translation' folder and update __init__.py with the module lookup entry for "YourTranslationClass" and also for TYPE_CHECKING.

if TYPE_CHECKING:
    ...
    from translation.your_translation_service import (
        YourTranslationClass
    )

_module_lookup = {
    ...,
    "YourTranslationClass": "translation.your_translation_service"
}

Modify env_manager.py to import YourTranslationClass and add a mapping for YourTranslationClass in the self.indexes dictionary.

from translation import (
    ...,
    YourTranslationClass
)
self.indexes = {
    "translation": {
        "class": {
            ...,
            "your_translation_service": YourTranslationClass
        },
        "env_key": "TRANSLATION_TYPE"
    }
}

This setup ensures that YourTranslationClass can be instantiated based on specific environment variables, effectively integrating it into the environment management system. The self.indexes the dictionary now includes a mapping where "your_translation_service" corresponds to the "YourTranslationClass" class and uses "TRANSLATION_TYPE" as the environment key.

Last updated