joxeankoret icon

Untitled

joxeankoret | PRO | 08/13/24 02:28:51 PM UTC | 0 ⭐ | 389 👁️ | Never ⏰ | []
Python |

3 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/python3
 
"""
Written by Joxean Koret in 2024
Public Domain
"""
 
import os
import sys
 
import argostranslate.package
import argostranslate.translate
 
try:
  import readline
except ImportError:
  pass
 
#-------------------------------------------------------------------------------
def translate(from_code : str, to_code : str, text : str) -> str:
  # Download and install Argos Translate package if required
  argostranslate.package.update_package_index()
  available_packages = argostranslate.package.get_available_packages()
 
  try:
    package_to_install = next(
      filter(
          lambda x: x.from_code == from_code and x.to_code == to_code, available_packages
      )
    )
    argostranslate.package.install_from_path(package_to_install.download())
  except StopIteration:
    pass
  except:
    print("Error:", sys.exc_info()[1])
 
  # Translate
  translatedText = argostranslate.translate.translate(text, from_code, to_code)
  return translatedText
 
#-------------------------------------------------------------------------------
def show_help():
  print("""Options:
.quit/.exit       Exit
.from <lang>      Set the language to translate from.
.to   <lang>      Set the language to translate to.
.list             List the pair of supported languages to translate to/from.
 
Anything else will be accumulated in a buffer until a single '.' character is typed in a line.
Example:
 
(es-fr) Hola!
>> Qué tal?
>> .
'Hola!\nQué tal?\n'
Bonjour !
Ça va ?
 
""")
 
#-------------------------------------------------------------------------------
def main():
  from_code = "es"
  to_code = "fr"
  text = ""
 
  buf = ""
  prompt = f"({from_code}-{to_code}) "
  while 1:
    try:
      if buf == "":
        prompt = f"({from_code}-{to_code}) "
      else:
        prompt = ">> "
      command = input(prompt)
    except EOFError:
      break
    except KeyboardInterrupt:
      break
 
    command = command.strip(" ")
    if command == "":
      continue
    elif command == "?":
      show_help()
      continue
    elif len(command) > 1 and command.startswith("."):
      args = command[1:].split(" ")
      cmd = args[0].lower()
      if cmd in ["quit", "exit"]:
        break
      elif cmd == "from":
        if len(args) == 1:
          print("Usage: .from <lang_code>")
        else:
          from_code = args[1]
      elif cmd == "to":
        if len(args) == 1:
          print("Usage: .to <lang_code>")
        else:
          to_code = args[1]
      elif cmd == "list":
        pkgs = argostranslate.package.get_available_packages()
        print("\n".join(map(str, pkgs)))
      else:
        print(f"Unknown command '{command}'")
        show_help()
      continue
    elif command.startswith("!"):
      os.system(command[1:])
      continue
 
    if command != ".":
      buf += command + "\n"
      continue
 
    ret = translate(from_code, to_code, buf)
    print(ret)
    buf = ""
 
if __name__ == "__main__":
  main()
 

Comments