In this article, we will guide you through the process of creating a Multilingual Dictionary app using Python. The core functionality of this application involves translating words using the OpenAI API. To provide a user-friendly interface, we will leverage the Streamlit library.
With this setup, translating words becomes a seamless process - a simple click of a button. Users only need to input the word they want to translate and select the desired languages, and the API will automatically generate translations in the specified languages. This combination of Python, OpenAI API, and Streamlit makes it easy for users to effortlessly translate words across different languages.
Multilingual Dictionary App Using Python
Here, for creating the Multilingual Dictionary App Using Python follow the below steps
To install the required libraries, OpenAI and Streamlit, use the following commands:
pip install openai pip install streamlit
These commands will install the necessary dependencies for utilizing OpenAI and Streamlit in your Python environment
Import Necessary libraries
First, import the OpenAI, Streamlit, and languages library in the following manner to create the GUI, use the API, and handle language conversion
import openai import streamlit as st from languages import *
Code Implementation
app.py : Here, The Python code defines a Streamlit app for a Multilingual Dictionary. It uses the OpenAI API to retrieve the meaning of a user-entered text in a specified language. The app has a State class to manage the application state, including the entered text, selected language, and retrieved definition. The get_meaning() method sends a request to the OpenAI API with a prompt based on the user's input and stores the obtained definition.
The main() function sets up the Streamlit app interface with a text area for input, a dropdown for language selection, and a button to trigger the meaning retrieval. The retrieved definition is displayed below the horizontal line. The app is run when the script is executed, utilizing the Streamlit framework for creating the graphical user interface.
importopenaiasOpenAIimportstreamlitasstfromlanguagesimport*# Set OpenAI API keyOpenAI.api_key="OpenAIAPIKey"classState:"""Thisistheappstate."""text=""language=""define=""@staticmethoddefget_meaning():"""Getthemeaningoftheenteredtextinthespecifiedlanguage."""# Check if text is enteredifnotState.text:st.warning("Pleaseentersometext.")return# Check if a language is selectedifnotState.language:st.warning("Pleaseselectalanguage.")return# Generate prompt for OpenAI APIprompt=f"getmeaningof'{State.text}'in{State.language}"try:# Make a request to OpenAI APIresponse=OpenAI.Completion.create(model="text-davinci-002",prompt=prompt,temperature=1,max_tokens=256,top_p=1,frequency_penalty=0,presence_penalty=0,)# Extract and store the definition from the API responseState.define=response.choices[0].text.strip()exceptExceptionase:# Handle errors from OpenAI APIst.error(f"ErrorwithOpenAIAPI:{e}")@staticmethoddefset_text(text):"""Settheenteredtextintheappstate."""State.text=text@staticmethoddefset_language(language):"""Settheselectedlanguageintheappstate."""State.language=languagedefmain():# Set Streamlit page configurationst.set_page_config(page_title="Streamlit:MultilingualDictionaryApp",page_icon=":globe_with_meridians:",layout="wide",)# Main title of the appst.title("MultilingualDictionaryApp")# Text area for user inputState.text=st.text_area("Entertext")# Dropdown for selecting a languageState.language=st.selectbox("Selectalanguage",languages)# Button to trigger the meaning retrievalifst.button("GetMeaning",key="meaning_button"):State.get_meaning()# Horizontal line for visual separationst.markdown("---")# Display the retrieved definitionifState.define:st.subheader("Definition:")st.write(State.define)# Run the app when the script is executedif__name__=="__main__":main()# This code is contributed by sourabh_jain
languages.py : The code defines a list of various languages .
Python3
# List of languageslanguages=["Afrikaans","Akan","Albanian","Amharic","Arabic","Armenian","Assamese","Aymara","Azerbaijani","Bambara","Bangla","Basque","Belarusian","Bhojpuri","Bosnian","Bulgarian","Burmese","Catalan","Cebuano","CentralKurdish","Chinese(Simplified)","Chinese(Traditional)","Corsican","Croatian","Czech","Danish","Divehi","Dogri","Dutch","English","Esperanto","Estonian","Ewe","Filipino","Finnish","French","Galician","Ganda","Georgian","German","GoanKonkani","Greek","Guarani","Gujarati","HaitianCreole","Hausa","Hawaiian","Hebrew","Hindi","Hmong","Hungarian","Icelandic","Igbo","Iloko","Indonesian","Irish","Italian","Japanese","Javanese","Kannada","Kazakh","Khmer","Kinyarwanda","Korean","Krio","Kurdish","Kyrgyz","Lao","Latin","Latvian","Lingala","Lithuanian","Luxembourgish","Macedonian","Maithili","Malagasy","Malay","Malayalam","Maltese","Manipuri(MeiteiMayek)","Māori","Marathi","Mizo","Mongolian","Nepali","NorthernSotho","Norwegian","Nyanja","Odia","Oromo","Pashto","Persian","Polish","Portuguese","Punjabi","Quechua","Romanian","Russian","Samoan","Sanskrit","ScottishGaelic","Serbian","Shona","Sindhi","Sinhala","Slovak","Slovenian","Somali","SouthernSotho","Spanish","Sundanese","Swahili","Swedish","Tajik","Tamil","Tatar","Telugu","Thai","Tigrinya","Tsonga","Turkish","Turkmen","Ukrainian","Urdu","Uyghur","Uzbek","Vietnamese","Welsh","WesternFrisian","Xhosa","Yiddish","Yoruba","Zulu"]
Run the Server
For run the server use the below commands:
streamlit run "app.py_file_path"
Output
Multilingual Dictionary App
Video Demonstration
Conclusion
In conclusion, the Multilingual Dictionary App created using Python leverages the power of OpenAI's language model and the Streamlit library to provide a user-friendly interface for translating words into multiple languages. The app allows users to input a word, select a target language from an extensive list, and seamlessly retrieve the translated result with the click of a button. The integration of OpenAI's API enhances the app's functionality, making it a versatile tool for linguistic exploration and communication across different languages. The simplicity of the user interface, combined with the robust translation capabilities, makes this Multilingual Dictionary App a valuable asset for users seeking quick and efficient language translation solutions.