If you’re building a cool side project or an MVP, you must store user and application content. This article will teach you about Strapi, a headless CMS you can use as your application backend. You will build a language translator application using Streamlit and a language translation model from Hugging Face that allows users to translate text written in any language to English, using Strapi as a back-end to store user inputs and outputs.
Benefits of a Language Translator Application
A language translator application is handy, especially when you come across texts online that you need help understanding because you are unfamiliar with the language. It can also serve as an educational tool, improving your understanding of foreign languages by learning through provided translations. Here is a demo of the language translator application you will build in this tutorial.
Prerequisites
Before starting, ensure you have;
- Installed Python 3.9+ or above.
- Installed Node.js
- Installed npm
- Set up a Hugging Face account.
- Set up a Strapi account.
- Set up a Streamlit Cloud account.
- Set up a Github Account.
Set up the Project Directory
On your terminal, create a new project
language_translator
.$ mkdir language_translator
Inside the project directory, create a Python virtual environment. This environment maintains the library versions used in your code, ensuring your code is reproducible every time it runs.
$ python -m venv venv
The first
venv
command creates a virtual environment, while the secondvenv
specifies the name of your virtual environment, which you can give any name you like. After running the above command, avenv
folder should be created in your project directory.Run the following code to activate the virtual environment and start working on it.
$ ./venv/Scripts/Activate
Upon activation, you should see the name of your virtual environment in green, signifying that you are already in a virtual environment.
Inside the project directory, create a
requirements.txt
filenano requirements.txt
Copy and paste the following Python Libraries into the
requirements.txt
file.streamlit python-dotenv requests
streamlit
is a Python UI library for building interactive web applications.python-dotenv
is a Python library for working with environment variables.requests
is an HTTP client library that you can use to make requests from an API.
Install the above Python libraries using the following command
$ pip install -r requirements.txt
Create a
.env
file to store environment variables such as API keys and secrets.$ touch .env
Inside your
language_translator
directory, create a folderfrontend
for the application frontend.$ mkdir frontend
In the folder
frontend
, create the filesmain.py
andutilis.py
touch main.py utilis.py
In the project folder, create a
.gitignore
file, to ignore thevenv
and.env
path when pushing to git./venv .env
Build the Front-end
The front end is where users will interact with the application. You will build it using Streamlit and translate user inputs using a language translator model from Hugging Face.
Select a Model from Hugging Face
Log in to Hugging Face, go to the search bar, and search for facebook/mbart-large-50-many-to-one-mmt. This is the model you will use to allow users to give input in any language and translate it into English.
Click on Deploy, then Inference API.
Copy the code displayed to you and paste it into
utilis.py
.import requests = "<https://api-inference.huggingface.co/models/facebook/mbart-large-50-many-to-one-mmt>" API_URL = {"Authorization": "Bearer <your-api-token>"} headers def query(payload): = requests.post(API_URL, headers=headers, json=payload) response return response.json() = query({ output "inputs": "The answer to the universe is", })
API_URL
is the variable storing the link to the model API.headers
is the variable storing your Hugging Face authorization token to use the API.- The
query
function makes a POST request to the model API to translate a given input text and return the JSON output.
Copy your
API-TOKEN
, go to the.env
file, and create the variable.HUGGING_FACE_TOKEN
.HUGGING_FACE_TOKEN="<your-api-token>"
Go back to the
utilis.py
file, copy and paste the following code to create a function of Step 3 that accepts a text in any language and translates it to English.import requests import os import json from datetime import datetime from dotenv import load_dotenv ".env") load_dotenv( = os.getenv("HUGGING_FACE_TOKEN") HUGGING_FACE_TOKEN = "<https://api-inference.huggingface.co/models/facebook/mbart-large-50-many-to-one-mmt>" API_URL = {"Authorization": f"Bearer {HUGGING_FACE_TOKEN}"} headers def translate(inputs): def query(payload): = requests.post(API_URL, headers=headers, json=payload) response return response.json() = query( output {"inputs": inputs, } )return output[0]["generated_text"]
load_dotenv(".env")
loads your.env
file, making it visible foros.getenv()
to get the environment variable specified.- The
translate()
function takes input text, while thequery
function processes it and returns it in JSON. Finally, thetranslate()
function extracts the translated text. - Here is an example of how the
translate
function works. Copy and run the text below.
= "संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है" text translate(text) >>Output: 'The head of the UN says there is no military solution in Syria'
Build the User Interface with Streamlit
Inside your
main.py
file, import thetranslate
function and streamlit.from utilis import translate import streamlit as st
Create a title and input area.
"Language Translator to English") st.title( = st.text_area("Enter the text you want to translate:", height=150) input_text
st.title
sets a text in bold and large size.st.text_area
is a multi-line text input widget that allows users to give input.
Run the code below on your terminal to launch the Streamlit application.
streamlit run main.py
Create a button to process any input given in the text area.
if st.button("Translate"): if input_text: = translate(input_text) translated_text "## Translated Text") st.write( st.write(translated_text)else: "Please enter some text to translate.") st.warning(
st.button
creates a button to translate a text.I
f
there is aninput text
, thetranslation
function is called on theinput_text
and saved astranslated_text
; otherwise, a warning is given.Save your file and go to the Streamlit application to see the changes.
Paste the Hindi text given earlier into the text area and click on translate.
What is left is to set up a back-end on Strapi to save any translated text.
Build the Back-end
Set up Strapi
In your main directory
language_translator
, create a new Strapi project calledbackend
.npx create-strapi-app@latest backend --quickstart
This will install Strapi and an SQLite database in your project directory.
Run the following code in your terminal to open the admin panel at http://localhost:1337/admin. Fill in your credentials, Sign up, and Log in.
npm run develop
Go to Content Type Builder, click Create a new collection, create a new collection Translation, then Continue.
Create
input_text
andtranslated_text
as Text fields whiletranslation_date
is a Date field and Save.Go to Settings on your admin menu, under User & Permissions Plugin, click on Roles, and edit the Public role.
In the Public role, set the Translation permission to create and find, then Save.
Connect Strapi with Streamlit
Copy and paste the following code to create a function
save_translation
that saves both theinput_text
andoutput_text
to Strapi.= "<http://localhost:1337/api>" STRAPI_URL def save_translation(input_text, translated_text): = { data "data": { "input_text": input_text, "translated_text": translated_text, "translation_date": datetime.now().isoformat(), } } = requests.post( response f"{STRAPI_URL}/translations", ={"Content-Type": "application/json"}, headers=json.dumps(data), data )return response.json()
STRAPI_URL
is the link to the Strapi backend API. You will use this to send and receive data from Strapi.- The
save_translation()
function receives the userinput_text
,translated_text
, andtranslation_date
as JSON in the variable data and sends it for storage in the Strapi back-end. datetime.now().isoformat()
saves the current date and time aninput_text
was translated as"translation_date"
into data.- The
response
variable makes aPOST
request to save the values into theTranslation
collection in Strapi.
Go back to
main.py
and update the code just before the end of the innerif
condition. This will ensure that anytime a user clicks the Translate button, the text displays, and the input and output text are saved to Strapi through thesave_translation()
function.
if st.button("Translate"):
if input_text:
#code to display text after input is given
#....
#code to update
#--------------
save_translation(input_text, translated_text)else:
"Please enter some text to translate.") st.warning(
Try to translate a text, and go back to your dashboard under the Content Manager menu to see the saved text.
To output the history from latest to oldest, add the
get_history()
function toutilis.py
.def get_history(): = requests.get(f"{STRAPI_URL}/translations") response if response.status_code == 200: return response.json() return []
- This function gets all the items stored in the Translation collection using a
GET
request and saves it in the variableresponse
as JSON.
- This function gets all the items stored in the Translation collection using a
Update
main.py
with the following code to create a History button where users can view previous translations.if st.button("History"): = get_history() history if history: for item in reversed(history["data"]): st.text(f"Date: {item['attributes']['translation_date']}\\nInput: {item['attributes']['input_text']}\\nTranslated: {item['attributes']['translated_text']}" )else: "No history found.") st.write(
- If the History button is clicked, the
get_history()
is called, fetching and displaying all items in the Translation collection. - The
reversed()
function loops the listhistory[data]
in a reverse order to display recently added text first. - If no
history
is found, the application returns a warning. - If you click the
history
button, you should have something like this.
- If the History button is clicked, the
Deployment
The application consists of two components: the back end and the front end. There are various ways to deploy these components, but for this tutorial, you will use Strapi Cloud to deploy the back end and Streamlit Cloud to deploy the front end.
Strapi Cloud deployment is free for 14 days, but the Streamlit Cloud is completely free. Before proceeding, ensure you have already versioned your project on GitHub.
Deploy the Backend on Strapi Cloud
Go to Deploy on your admin dashboard menu, and click Deploy to Strapi Cloud.
Sign in to Strapi Cloud.
Click on Create Project to create a new project.
Select the Free trial and click on GitHub to permit Strapi to authorize your GitHub account.
After completing the authorization steps, you should have something like this. Select the account you want Strapi to access and the project repository.
Give the application a display name, and leave other options as the default.
Under Show Advanced Settings, type the backend directory, which is
/backend
, leave other options as default, and click on Create Project.You can see the application build and deploy logs displayed while the application is being built.
Click on the Visit app to open up the live admin panel.
Like before, when you open the admin panel locally, fill in your credentials and log in.
Since the backend is deployed, change the
STRAPI_URL
variable inutilis.py
to the live URL. Copy the URL of the live dashboard, excluding the part/admin
, and include/
API at the end.="<your-strapi-api-url>/api" STRAPI_URL
Ensure you cross-check your settings to see if all the roles are set. If not, you can set them back using Step 6 in the Set up Strapi section.
That’s it, you now have your back-end live, let’s deploy the frontend and the back-end.
Deploy the Frontend on Streamlit Cloud
Log in to Streamlit Cloud and authorize Streamlit to access your GitHub account.
Click on Create app.
Please complete the form by providing the project repository and the path of the streamlet application, which is
/frontend/main.py
. If you have authorized Streamlit to access your GitHub repositories, it will list all the repositories in your GitHub account.Click on Advanced Settings, type in your
HUGGING_FACE_TOKEN
as it is in your.env
file, and Save.Click on Deploy! to start building the application. This is going to take a while.
Now, you have successfully deployed the Streamlit application.
Conclusion
In this article, you have learned how to use a model from Hugging Face to build a Streamlit application and store your user inputs and outputs on a Strapi backend. You also learned how to deploy the back-end and front-end components on Strapi and Streamlit Cloud. Strapi has a fun and active Discord community to help answer your questions whenever you feel stuck.
Here is the GitHub repository for the language translator application. You can further extend the application by:
- Add authorization to your Streamlit front end and set various user roles and permissions for your Strapi backend.
- Exploring various language models on Hugging Face, such as English-to-many language translators or audio translators.
Recommended Reads
- ML Model Deployment with FastAPI and Streamlit
- Using Python with Strapi
- Deploying to Strapi Cloud
- Admin Panel Customization
- Analyzing data from a Strapi API with Python
- Deploying to Streamlit Cloud
Need Help with Data? Let’s Make It Simple.
At LearnData.xyz, we’re here to help you solve tough data challenges and make sense of your numbers. Whether you need custom data science solutions or hands-on training to upskill your team, we’ve got your back.
📧 Shoot us an email at admin@learndata.xyz—let’s chat about how we can help you make smarter decisions with your data.