Add translation capability to your application

Make all the changes for this step in the view/wl.py file.

Start by updating the code. All of this code is available in GitHub.

 

    1. Create a function that will encapsulate the service credentials:
      def getTranslationService():

        return LanguageTranslation(username='<uid>',

                                  password='<pwd>')

 

    1. Create a new function named identifyLanguage:
      def identifyLanguage(data):

        txt = data.encode("utf-8", "replace")

        language_translation = getTranslationService()

       

        langsdetected = language_translation.identify(txt)

        logger.info(json.dumps(langsdetected, indent=2)) 

        logger.info(langsdetected["languages"][0]['language'])    

        logger.info(langsdetected["languages"][0]['confidence'])  

       

        primarylang = langsdetected["languages"][0]['language'] 

        confidence = langsdetected["languages"][0]['confidence']

       

        retData = {"language" : primarylang,

                   "confidence" : confidence}

               

        return retData

      This function calls the identify function that you coded before. It will allow you to refine the main logic, which you’ll do shortly. Before you do so, you need to add several new functions.

 

    1. Add a function to check whether a translation for a specific language is supported:
      def identifyLanguage(data):

        txt = data.encode("utf-8", "replace")

        language_translation = getTranslationService()

       

        langsdetected = language_translation.identify(txt)

        logger.info(json.dumps(langsdetected, indent=2)) 

        logger.info(langsdetected["languages"][0]['language'])    

        logger.info(langsdetected["languages"][0]['confidence'])  

       

        primarylang = langsdetected["languages"][0]['language'] 

        confidence = langsdetected["languages"][0]['confidence']

       

        retData = {"language" : primarylang,

                   "confidence" : confidence}

               

        return retData

      This function iterates through all the supported translation models and checks which ones support the required translation.

 

    1. Add a function that performs the translation:
      def performTranslation(txt, primarylang, targetlang):

        lt = getTranslationService()

        translation = lt.translate(txt, source=primarylang, target=targetlang)

        return translation

 

    1. Modify the index method for the page, the core logic of which is shown here:
         try:

              lang = identifyLanguage(data)

              primarylang = lang["language"]

              confidence = lang["confidence"]

              outputTxt = "I am %s confident that it is %s" % (confidence, primarylang)       

              if targetlang != primarylang:

                logger.info("Language %s is not %s" % (primarylang, targetlang))

                supportedModels = checkForTranslation(primarylang, targetlang)

                if supportedModels:

                  logger.info("We have some supported translation models")

                  englishTxt = performTranslation(data, primarylang, targetlang)

                  outputTxt += ", which in english is %s" % englishTxt              

                else:

                  outputTxt += " ,which unfortunately we can't translate into English"          

            except WatsonException as err:

              allinfo['error'] = err;

      The full method should look something like this:
      def index(request):

        allinfo = {}

        outputTxt = "TBD"

        targetlang = 'en'

        form = None 

        if request.POST:

          form = Form_language(request.POST)

          if form.is_valid():

            data = form.cleaned_data['txtdata']

            logger.info("Text to be processed is %s " % data) 

            lang = "TBD"

            try:

              lang = identifyLanguage(data)

              primarylang = lang["language"]

              confidence = lang["confidence"]

              outputTxt = "I am %s confident that it is %s" % (confidence, primarylang)       

              if targetlang != primarylang:

                logger.info("Language %s is not %s" % (primarylang, targetlang))

                supportedModels = checkForTranslation(primarylang, targetlang)

                if supportedModels:

                  logger.info("We have some supported translation models")

                  englishTxt = performTranslation(data, primarylang, targetlang)

                  outputTxt += ", which in english is %s" % englishTxt              

                else:

                  outputTxt += " ,which unfortunately we can't translate into English"          

            except WatsonException as err:

              allinfo['error'] = err;

            

            allinfo['lang'] = outputTxt

          else:

            allinfo['error'] = "Form is invalid"

        else:

           form = Form_language()

            

        allinfo['form'] = form

        return render(request, 'watson/wlindex.html', allinfo )

 

  1. Try it out with several languages.
    • For languages that can’t be translated, you should see a message that reflects that situation.
    • For languages that can be translated, you should see that the language is accurately detected and translated.