Advertisement
Python253

translatorinator

May 27th, 2024
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.31 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: translatorinator.py
  4. # Version: 1.0.3
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script allows you to translate text between 106 different languages using the googletrans library.
  10.    - It provides a user-friendly interface to input text, select languages, and view available language codes.
  11.    - The script handles network errors gracefully and uses the colorama library to add color to the terminal output for a better user experience.
  12.  
  13. Requirements:
  14.    - Python 3.x
  15.    - googletrans library
  16.    - requests library
  17.    - colorama library
  18.  
  19. Functions:
  20.    - translate:
  21.        Translate text from the source language to the destination language.
  22.    - display_language_codes:
  23.        Display a formatted list of all supported language codes and their corresponding language names.
  24.    - get_language_code:
  25.        Prompt the user to enter a language code or code index and validate the input.
  26.    - main:
  27.        Main function to run the translator script.
  28.  
  29. Usage:
  30.    - Run the script and follow the prompts to translate text between different languages.
  31.  
  32. Example Output:
  33.  
  34.    ┏┳┓                                 •        
  35.      ┃ ┏┓┏┓ ┏┓ ┏ ┃ ┏┓ ╋ ┏┓ ┏┓ ┓ ┏┓ ┏┓ ╋ ┏┓ ┏┓
  36.      ┻ ┛  ┗┻ ┛┗ ┛ ┗ ┗┻ ┗ ┗┛ ┛  ┗ ┛┗ ┗┻ ┗ ┗┛ ┛                            
  37.                
  38.  
  39.    Main Menu:
  40.  
  41.    1: Help
  42.    2: Translate
  43.    3: Codes
  44.    0: EXIT
  45.  
  46.    Select an option: 2
  47.  
  48.    Enter your text (or press '0' to return to the Main Menu): This Is A Simple Translation Test Example
  49.  
  50.    Enter the [INPUT] language code or code index: 22
  51.  
  52.    Enter the [OUTPUT] language code or code index: 77
  53.  
  54.    Translated text:
  55.  
  56.            Это простой пример теста на перевод
  57.  
  58.    Would you like to translate something else?
  59.  
  60.    1: Yes
  61.    2: No
  62.  
  63.    Make your selection (1-2): 2
  64.  
  65.            Exiting Program... Goodbye!
  66.  
  67. Additional Notes:
  68.    - For more information about language codes and their corresponding languages, visit the Google Translate website.
  69.    - This script handles network errors gracefully to ensure uninterrupted translation service.
  70. """
  71.  
  72. from googletrans import LANGUAGES, Translator
  73. from requests.exceptions import ConnectionError
  74. from colorama import Fore, init
  75.  
  76. # Initialize colorama with autoreset
  77. init(autoreset=True)
  78.  
  79. # Remove duplicate "iw" Hebrew language code from database
  80. LANGUAGES = {k: v for k, v in LANGUAGES.items() if k != "iw"}
  81.  
  82. def translate(text, src_lang, dest_lang):
  83.     """
  84.    Translate text from the source language to the destination language using googletrans.
  85.  
  86.    Args:
  87.        text (str): The text to be translated.
  88.        src_lang (str): The language code of the source text.
  89.        dest_lang (str): The language code of the destination text.
  90.  
  91.    Returns:
  92.        str: The translated text or an error message if translation fails.
  93.    """
  94.     translator = Translator()
  95.     try:
  96.         translation = translator.translate(text=text, src=src_lang, dest=dest_lang)
  97.         return translation.text
  98.     except ConnectionError:
  99.         return "Unable to connect to the translation service. Please check your internet connection."
  100.  
  101. def display_language_codes():
  102.     """
  103.    Display a formatted list of all supported language codes and their corresponding language names.
  104.    The list is displayed in columns for better readability.
  105.    """
  106.     print(Fore.YELLOW + "\nLanguage Codes:\n")
  107.     sorted_langs = sorted(LANGUAGES.items(), key=lambda x: x[1])
  108.  
  109.     cols = 3
  110.     lang_name_width = max(len(lang) for lang in LANGUAGES.values()) + 4
  111.     lang_code_width = max(len(code) for code in LANGUAGES.keys()) + 4
  112.  
  113.     for i in range(0, len(sorted_langs), cols):
  114.         row = sorted_langs[i : i + cols]
  115.         row_str = "    ".join(
  116.             f"{Fore.WHITE}{i+j+1:03}: {Fore.CYAN}{lang.ljust(lang_name_width)} {Fore.GREEN}{code.ljust(lang_code_width)}"
  117.             for j, (code, lang) in enumerate(row)
  118.         )
  119.         print(row_str.rstrip())
  120.  
  121. def get_language_code(input_type):
  122.     """
  123.    Prompt the user to enter a language code or code index and validate the input.
  124.  
  125.    Args:
  126.        input_type (str): Specifies whether the input is for the source language ("INPUT")
  127.                          or the destination language ("OUTPUT").
  128.  
  129.    Returns:
  130.        str: The valid language code entered by the user.
  131.    """
  132.     while True:
  133.         lang_input = input(
  134.             Fore.CYAN
  135.             + "\nEnter the "
  136.             + Fore.WHITE
  137.             + f"[{input_type}]"
  138.             + Fore.CYAN
  139.             + " language code or code index: "
  140.         ).strip()
  141.         if lang_input == "0":
  142.             print(Fore.WHITE + "\n\t\tExiting Program... Goodbye!\n")
  143.             exit()
  144.         if lang_input.isdigit():
  145.             index = int(lang_input)
  146.             if 1 <= index <= len(LANGUAGES):
  147.                 lang_code = list(LANGUAGES.keys())[index - 1]
  148.                 return lang_code
  149.             else:
  150.                 print(Fore.RED + "\nInvalid code index! Please try again.\n")
  151.         elif lang_input in LANGUAGES:
  152.             return lang_input
  153.         else:
  154.             print(
  155.                 Fore.RED
  156.                 + "\nInvalid language code! Please try again or type '3' to see all languages.\n"
  157.             )
  158.             if lang_input == "3":
  159.                 display_language_codes()
  160.  
  161. def main():
  162.     """
  163.    Main function to run the translator script. It displays a menu for the user to select options:
  164.    Help, Translate, or View Codes. Based on the user's selection, it performs the corresponding actions.
  165.    """
  166.     help_message = f"""
  167. {Fore.YELLOW}Welcome to the Translatorinator program!
  168. {Fore.GREEN}
  169. This script can translate text between 106 different languages!
  170. {Fore.WHITE}
  171. To translate text, please follow these steps:
  172.    
  173. {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.
  174. {Fore.WHITE}    2. {Fore.CYAN}Input your text and hit the {Fore.WHITE}[Enter] {Fore.CYAN}key.
  175. {Fore.WHITE}    3. {Fore.CYAN}Select the language of the {Fore.WHITE}[INPUT]{Fore.CYAN} text by entering the language code or code index.
  176. {Fore.WHITE}    4. {Fore.CYAN}Select the language of the {Fore.WHITE}[OUTPUT]{Fore.CYAN} text by entering the language code or code index.
  177. {Fore.GREEN}
  178. Let's get started!
  179. """
  180.     while True:
  181.         print(
  182.             Fore.YELLOW
  183.             + """
  184. ┏┳┓                                 •        
  185.  ┃ ┏┓┏┓ ┏┓ ┏ ┃ ┏┓ ╋ ┏┓ ┏┓ ┓ ┏┓ ┏┓ ╋ ┏┓ ┏┓
  186.  ┻ ┛  ┗┻ ┛┗ ┛ ┗ ┗┻ ┗ ┗┛ ┛  ┗ ┛┗ ┗┻ ┗ ┗┛ ┛                            
  187.            """
  188.         )
  189.         print(Fore.WHITE + "\nMain Menu:\n")
  190.         print(Fore.CYAN + "1: Help")
  191.         print(Fore.CYAN + "2: Translate")
  192.         print(Fore.CYAN + "3: Codes")
  193.         print(Fore.RED + "0: EXIT")
  194.         option = input(Fore.WHITE + "\nSelect an option: ")
  195.  
  196.         if option == "0":
  197.             print(Fore.GREEN + "\n\t\tExiting Program... Goodbye!\n")
  198.             break
  199.         elif option == "1":
  200.             print(help_message)
  201.             input(Fore.WHITE + "\nPress [ENTER] to return to Main Menu: ")
  202.         elif option == "3":
  203.             display_language_codes()
  204.             input(Fore.WHITE + "\nPress [ENTER] to return to Main Menu: ")
  205.         elif option == "2":
  206.             text = input(
  207.                 Fore.WHITE
  208.                 + "\nEnter your text "
  209.                 + Fore.CYAN
  210.                 + "(or press '0' to return to the Main Menu): "
  211.             )
  212.             if text == "0":
  213.                 continue
  214.             src_lang = get_language_code("INPUT")
  215.             dest_lang = get_language_code("OUTPUT")
  216.  
  217.             if src_lang and dest_lang:
  218.                 translation = translate(text, src_lang, dest_lang)
  219.                 print(
  220.                     Fore.WHITE
  221.                     + "\nTranslated text:\n\n"
  222.                     + Fore.GREEN
  223.                     + f"\t\t{translation}"
  224.                 )
  225.  
  226.                 another = input(
  227.                     Fore.CYAN
  228.                     + "\nWould you like to translate something else?\n\n"
  229.                     + Fore.WHITE
  230.                     + "1: Yes\n2: No\n\n"
  231.                     + Fore.CYAN
  232.                     + "Make your selection (1-2): "
  233.                 )
  234.                 if another != "1":
  235.                     print(Fore.GREEN + "\n\t\tExiting Program... Goodbye!\n")
  236.                     break
  237.         else:
  238.             print(
  239.                 Fore.RED
  240.                 + "\nInvalid option!\n\n"
  241.                 + Fore.CYAN
  242.                 + "Please select "
  243.                 + Fore.WHITE
  244.                 + "'1' "
  245.                 + Fore.CYAN
  246.                 + "for help, "
  247.                 + Fore.WHITE
  248.                 + "'2' "
  249.                 + Fore.CYAN
  250.                 + "to translate, "
  251.                 + Fore.WHITE
  252.                 + "'3' "
  253.                 + Fore.CYAN
  254.                 + "to see codes, or "
  255.                 + Fore.WHITE
  256.                 + "'0' "
  257.                 + Fore.CYAN
  258.                 + "to exit.\n\n"
  259.             )
  260.  
  261. if __name__ == "__main__":
  262.     main()
  263.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement