Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: translatorinator.py
- # Version: 1.0.3
- # Author: Jeoi Reqi
- """
- Description:
- - This script allows you to translate text between 106 different languages using the googletrans library.
- - It provides a user-friendly interface to input text, select languages, and view available language codes.
- - The script handles network errors gracefully and uses the colorama library to add color to the terminal output for a better user experience.
- Requirements:
- - Python 3.x
- - googletrans library
- - requests library
- - colorama library
- Functions:
- - translate:
- Translate text from the source language to the destination language.
- - display_language_codes:
- Display a formatted list of all supported language codes and their corresponding language names.
- - get_language_code:
- Prompt the user to enter a language code or code index and validate the input.
- - main:
- Main function to run the translator script.
- Usage:
- - Run the script and follow the prompts to translate text between different languages.
- Example Output:
- ┏┳┓ •
- ┃ ┏┓┏┓ ┏┓ ┏ ┃ ┏┓ ╋ ┏┓ ┏┓ ┓ ┏┓ ┏┓ ╋ ┏┓ ┏┓
- ┻ ┛ ┗┻ ┛┗ ┛ ┗ ┗┻ ┗ ┗┛ ┛ ┗ ┛┗ ┗┻ ┗ ┗┛ ┛
- Main Menu:
- 1: Help
- 2: Translate
- 3: Codes
- 0: EXIT
- Select an option: 2
- Enter your text (or press '0' to return to the Main Menu): This Is A Simple Translation Test Example
- Enter the [INPUT] language code or code index: 22
- Enter the [OUTPUT] language code or code index: 77
- Translated text:
- Это простой пример теста на перевод
- Would you like to translate something else?
- 1: Yes
- 2: No
- Make your selection (1-2): 2
- Exiting Program... Goodbye!
- Additional Notes:
- - For more information about language codes and their corresponding languages, visit the Google Translate website.
- - This script handles network errors gracefully to ensure uninterrupted translation service.
- """
- from googletrans import LANGUAGES, Translator
- from requests.exceptions import ConnectionError
- from colorama import Fore, init
- # Initialize colorama with autoreset
- init(autoreset=True)
- # Remove duplicate "iw" Hebrew language code from database
- LANGUAGES = {k: v for k, v in LANGUAGES.items() if k != "iw"}
- def translate(text, src_lang, dest_lang):
- """
- Translate text from the source language to the destination language using googletrans.
- Args:
- text (str): The text to be translated.
- src_lang (str): The language code of the source text.
- dest_lang (str): The language code of the destination text.
- Returns:
- str: The translated text or an error message if translation fails.
- """
- translator = Translator()
- try:
- translation = translator.translate(text=text, src=src_lang, dest=dest_lang)
- return translation.text
- except ConnectionError:
- return "Unable to connect to the translation service. Please check your internet connection."
- def display_language_codes():
- """
- Display a formatted list of all supported language codes and their corresponding language names.
- The list is displayed in columns for better readability.
- """
- print(Fore.YELLOW + "\nLanguage Codes:\n")
- sorted_langs = sorted(LANGUAGES.items(), key=lambda x: x[1])
- cols = 3
- lang_name_width = max(len(lang) for lang in LANGUAGES.values()) + 4
- lang_code_width = max(len(code) for code in LANGUAGES.keys()) + 4
- for i in range(0, len(sorted_langs), cols):
- row = sorted_langs[i : i + cols]
- row_str = " ".join(
- f"{Fore.WHITE}{i+j+1:03}: {Fore.CYAN}{lang.ljust(lang_name_width)} {Fore.GREEN}{code.ljust(lang_code_width)}"
- for j, (code, lang) in enumerate(row)
- )
- print(row_str.rstrip())
- def get_language_code(input_type):
- """
- Prompt the user to enter a language code or code index and validate the input.
- Args:
- input_type (str): Specifies whether the input is for the source language ("INPUT")
- or the destination language ("OUTPUT").
- Returns:
- str: The valid language code entered by the user.
- """
- while True:
- lang_input = input(
- Fore.CYAN
- + "\nEnter the "
- + Fore.WHITE
- + f"[{input_type}]"
- + Fore.CYAN
- + " language code or code index: "
- ).strip()
- if lang_input == "0":
- print(Fore.WHITE + "\n\t\tExiting Program... Goodbye!\n")
- exit()
- if lang_input.isdigit():
- index = int(lang_input)
- if 1 <= index <= len(LANGUAGES):
- lang_code = list(LANGUAGES.keys())[index - 1]
- return lang_code
- else:
- print(Fore.RED + "\nInvalid code index! Please try again.\n")
- elif lang_input in LANGUAGES:
- return lang_input
- else:
- print(
- Fore.RED
- + "\nInvalid language code! Please try again or type '3' to see all languages.\n"
- )
- if lang_input == "3":
- display_language_codes()
- def main():
- """
- Main function to run the translator script. It displays a menu for the user to select options:
- Help, Translate, or View Codes. Based on the user's selection, it performs the corresponding actions.
- """
- help_message = f"""
- {Fore.YELLOW}Welcome to the Translatorinator program!
- {Fore.GREEN}
- This script can translate text between 106 different languages!
- {Fore.WHITE}
- To translate text, please follow these steps:
- {Fore.WHITE} 1. {Fore.CYAN}Select {Fore.WHITE}[Option 2]{Fore.CYAN} from the Main Menu or {Fore.WHITE}[Option 3]{Fore.CYAN} to see all language codes.
- {Fore.WHITE} 2. {Fore.CYAN}Input your text and hit the {Fore.WHITE}[Enter] {Fore.CYAN}key.
- {Fore.WHITE} 3. {Fore.CYAN}Select the language of the {Fore.WHITE}[INPUT]{Fore.CYAN} text by entering the language code or code index.
- {Fore.WHITE} 4. {Fore.CYAN}Select the language of the {Fore.WHITE}[OUTPUT]{Fore.CYAN} text by entering the language code or code index.
- {Fore.GREEN}
- Let's get started!
- """
- while True:
- print(
- Fore.YELLOW
- + """
- ┏┳┓ •
- ┃ ┏┓┏┓ ┏┓ ┏ ┃ ┏┓ ╋ ┏┓ ┏┓ ┓ ┏┓ ┏┓ ╋ ┏┓ ┏┓
- ┻ ┛ ┗┻ ┛┗ ┛ ┗ ┗┻ ┗ ┗┛ ┛ ┗ ┛┗ ┗┻ ┗ ┗┛ ┛
- """
- )
- print(Fore.WHITE + "\nMain Menu:\n")
- print(Fore.CYAN + "1: Help")
- print(Fore.CYAN + "2: Translate")
- print(Fore.CYAN + "3: Codes")
- print(Fore.RED + "0: EXIT")
- option = input(Fore.WHITE + "\nSelect an option: ")
- if option == "0":
- print(Fore.GREEN + "\n\t\tExiting Program... Goodbye!\n")
- break
- elif option == "1":
- print(help_message)
- input(Fore.WHITE + "\nPress [ENTER] to return to Main Menu: ")
- elif option == "3":
- display_language_codes()
- input(Fore.WHITE + "\nPress [ENTER] to return to Main Menu: ")
- elif option == "2":
- text = input(
- Fore.WHITE
- + "\nEnter your text "
- + Fore.CYAN
- + "(or press '0' to return to the Main Menu): "
- )
- if text == "0":
- continue
- src_lang = get_language_code("INPUT")
- dest_lang = get_language_code("OUTPUT")
- if src_lang and dest_lang:
- translation = translate(text, src_lang, dest_lang)
- print(
- Fore.WHITE
- + "\nTranslated text:\n\n"
- + Fore.GREEN
- + f"\t\t{translation}"
- )
- another = input(
- Fore.CYAN
- + "\nWould you like to translate something else?\n\n"
- + Fore.WHITE
- + "1: Yes\n2: No\n\n"
- + Fore.CYAN
- + "Make your selection (1-2): "
- )
- if another != "1":
- print(Fore.GREEN + "\n\t\tExiting Program... Goodbye!\n")
- break
- else:
- print(
- Fore.RED
- + "\nInvalid option!\n\n"
- + Fore.CYAN
- + "Please select "
- + Fore.WHITE
- + "'1' "
- + Fore.CYAN
- + "for help, "
- + Fore.WHITE
- + "'2' "
- + Fore.CYAN
- + "to translate, "
- + Fore.WHITE
- + "'3' "
- + Fore.CYAN
- + "to see codes, or "
- + Fore.WHITE
- + "'0' "
- + Fore.CYAN
- + "to exit.\n\n"
- )
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement