Created
January 28, 2019 09:10
-
-
Save tai/be9b76c9e7a45b995251df09e0bfd26d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import sys | |
| import os | |
| from argparse import ArgumentParser | |
| from google.cloud import translate | |
| def format_usage(): | |
| p = os.path.basename(sys.argv[0]) | |
| return """ | |
| {p} - Translate with Google | |
| Usage: {p} [target-language] [source-language] < input > output | |
| Example: | |
| $ echo This is a pen. | {p} ja | |
| $ echo This is a pen. | {p} zh en | {p} ja zh | |
| Note: | |
| - Either set GOOGLE_APPLICATION_CREDENTIALS envvar or save credential | |
| key in JSON at ~/.google-translate/key.json | |
| """.strip().format(**locals()) + "\n" | |
| def usage(): | |
| sys.stderr.write(format_usage()) | |
| sys.exit(0) | |
| def main(): | |
| ap = ArgumentParser() | |
| ap.format_usage = ap.format_help = format_usage | |
| ap.add_argument('args', nargs='*') | |
| opt = ap.parse_args() | |
| if len(opt.args) == 0: | |
| usage() | |
| GACK = "GOOGLE_APPLICATION_CREDENTIALS" | |
| if not os.environ.get(GACK): | |
| home = os.environ["HOME"] | |
| os.environ[GACK] = os.path.join(home, ".google-translate/credential.json") | |
| kw = { | |
| "target_language": "ja" | |
| } | |
| if len(opt.args) > 0: | |
| kw["target_language"] = opt.args[0] | |
| if len(opt.args) > 1: | |
| kw["source_language"] = opt.args[1] | |
| ua = translate.Client() | |
| text = sys.stdin.read() | |
| ret = ua.translate(text, **kw) | |
| print(ret['translatedText']) | |
| if __name__ == '__main__': | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment