Performing the translation task – Implementing NLP Techniques for Text Analysis and Processing in Streamlit

Performing the translation task

To perform the translation task, we will use a new library named deep_translator. So, first of all, let’s install it by simply typing the following command:
pipenv install deep_translator

After that, let’s import this library by typing the following:
from deep_translator import GoogleTranslator

As you can see, we are leveraging GoogleTranslator services.

If you want to get more information about deep_translator, please check its dedicated space on PyPI (https://pypi.org/project/deep-translator/). You really will find out about a lot of extremely valuable features to explore.

Figure 6.6: Deep-translator on PyPI

It is very important to define the language of the translation. So, let’s create a select_box that will enable users to choose a specific language:

Figure 6.7: Text language selection

This code is very simple: we are just selecting a language from among a little subset (actually, a list) and assigning the proper code to it (de for German, es for Spanish, etc.).

Finally, now that we have the target language, we just need to execute the translation and we can perform it, for example, by clicking on the Translate button; this is the complete code:

Figure 6.8: The Translation function code

So, when the Translate button is pressed, we call the GoogleTranslator function of the deep_translator package (already imported previously), put the result into a translated_text variable, and then write it on the screen.

This is the result on the browser side:

Figure 6.9: The Translation function in action

Everything is very neat and clean and works perfectly! Of course, you can personalize this feature as you like, for example, by adding more target languages or performing different kinds of checks on the input text.

Figure 6.10 shows the Target Language selection in action:

Figure 6.10: Target Language selection

Up to now, we have written less than 200 lines of code and our web application is working very well. With just a small amount of code, we were able to put together a backend and frontend, business logic running on a server, and a presentation layer living on a browser. Everything is in Python and is quite simple. This is the power of Streamlit.

Let’s move on to our last NLP task: sentiment analysis. As we discovered in the introduction, it is a fascinating topic.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *