Using Google Translator api to convert text in python.
Step 1: Sign Up for Google Cloud Translation API
- Go to Google Cloud Console.
- Create a new project or select an existing project.
- Enable the “Cloud Translation API” for your project.
- Create credentials: Choose “Service Account Key,” select “JSON” format, and download the credentials JSON file.
Step 2: Install Required Libraries
First, make sure you have Streamlit and the googletrans library installed. You can install them using the following commands:
pip install streamlit googletrans==4.0.0-rc1Step 3: Create the Translation App
Create a Python script named translation_app.py and follow the steps below:
import streamlit as st
from googletrans import Translatordef translate_text(text, source_lang, target_lang):
translator = Translator()
translated_text = translator.translate(text, src=source_lang, dest=target_lang)
return translated_text.textdef main():
st.title("Multilingual Text Translation App")
# Load Google API credentials credentials_path = "YOUR_GOOGLE_CREDENTIALS_JSON_FILE.json" os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path st.sidebar.header("Settings")
source_lang = st.sidebar.selectbox("Select Source Language", ("en", "es", "fr", "de", "ja"))
target_lang = st.sidebar.selectbox("Select Target Language", ("en", "es", "fr", "de", "ja")) text = st.text_area("Enter Text to Translate") if st.button("Translate"):
if text:
translated_text = translate_text(text, source_lang, target_lang)
st.write("Translated Text:")
st.write(translated_text)
else:
st.write("Please enter text to translate.")if __name__ == "__main__":
main()Explanation:
- Import the required libraries:
streamlitfor creating the app interface andgoogletransfor translation. - Define the
translate_textfunction to translate the input text from the source language to the target language using thegoogletranslibrary. - Create the main function for the Streamlit app:
- Use
st.titleto set the app title. - Create a sidebar with language selection using
st.sidebar. - Get the source and target languages from the sidebar using
st.sidebar.selectbox. - Allow the user to enter text using
st.text_area. - When the “Translate” button is clicked, call the
translate_textfunction and display the translated text usingst.write.
Step 4: Run the Translation App
- Save the
translation_app.pyscript. - Open a terminal and navigate to the script’s directory.
- Run the app using the command:
streamlit run translation_app.pyA web browser window will open with the app. Use the sidebar to select source and target languages, enter text, and click “Translate” to see the translation.





