translator
This commit is contained in:
parent
96770bb1fb
commit
70c273e313
85
dotfiles-old/bin/translate
Executable file
85
dotfiles-old/bin/translate
Executable file
@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
# googletrans comes with a translate(1) command line application but I don't
|
||||||
|
# like its UI.
|
||||||
|
|
||||||
|
import sys;
|
||||||
|
|
||||||
|
stdin = sys.stdin;
|
||||||
|
stdout = sys.stdout;
|
||||||
|
stderr = sys.stderr;
|
||||||
|
|
||||||
|
_exit = exit;
|
||||||
|
exit = sys.exit;
|
||||||
|
|
||||||
|
def printf(s, *args):
|
||||||
|
printing = s if len(args) == 0 else (s % args);
|
||||||
|
return sys.stdout.write(printing);
|
||||||
|
|
||||||
|
def fprintf(f, s, *args):
|
||||||
|
printing = s if len(args) == 0 else (s % args);
|
||||||
|
return f.write(printing);
|
||||||
|
|
||||||
|
try:
|
||||||
|
import googletrans;
|
||||||
|
except:
|
||||||
|
printf(
|
||||||
|
"%s: This Python script requires the \"googletrans\" library.\n",
|
||||||
|
sys.argv[0]
|
||||||
|
);
|
||||||
|
|
||||||
|
def usage(name):
|
||||||
|
fprintf(
|
||||||
|
stderr, "Usage: %s [source language] [destination language]\n",
|
||||||
|
name
|
||||||
|
);
|
||||||
|
exit(1);
|
||||||
|
|
||||||
|
def main(argc, argv):
|
||||||
|
accepted_languages = set(list(googletrans.LANGCODES)
|
||||||
|
+ list(googletrans.LANGUAGES));
|
||||||
|
good = True;
|
||||||
|
isatty = stdout.isatty();
|
||||||
|
translator = googletrans.Translator();
|
||||||
|
|
||||||
|
if argc != 3:
|
||||||
|
usage(argv[0]);
|
||||||
|
|
||||||
|
src = argv[1].lower();
|
||||||
|
dest = argv[2].lower();
|
||||||
|
for arg in [ src, dest ]:
|
||||||
|
if not(arg in accepted_languages):
|
||||||
|
good = False;
|
||||||
|
fprintf(stderr,
|
||||||
|
"%s: %s: Language not recognized.\n",
|
||||||
|
argv[0], arg);
|
||||||
|
if(not(good)):
|
||||||
|
fprintf(stderr, "The following languages and language codes are"
|
||||||
|
+ " recognized:\n");
|
||||||
|
print(googletrans.LANGCODES);
|
||||||
|
exit(1);
|
||||||
|
|
||||||
|
try:
|
||||||
|
text = stdin.read().split('\n')[:-1]
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
fprintf(stderr, "%s: Cancelled (keyboard interrupt).\n", argv[0]);
|
||||||
|
exit(1);
|
||||||
|
if len(text) == 1:
|
||||||
|
text = text[0];
|
||||||
|
translated = translator.translate(text, src=src, dest=dest);
|
||||||
|
if not(type(translated) is list): translated = [ translated ];
|
||||||
|
for translation in translated:
|
||||||
|
if isatty:
|
||||||
|
fprintf(stdout,
|
||||||
|
"%s -> %s\n"
|
||||||
|
+ "\t%s -> %s\n"
|
||||||
|
+ "\tGiven pronunciation: %s\n",
|
||||||
|
translation.origin, translation.text,
|
||||||
|
translation.src, translation.dest,
|
||||||
|
translation.pronunciation
|
||||||
|
);
|
||||||
|
else:
|
||||||
|
printf(stdout, "%s\n", translation.text);
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
exit(main(len(sys.argv), sys.argv));
|
Loading…
Reference in New Issue
Block a user