From 2f9bd030a72606e4f22463716dd9edbcfd484f88 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Wed, 12 Oct 2016 12:13:45 -0700 Subject: [PATCH] Add translate samples [(#574)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/574) --- samples/snippets/README.md | 64 +++++++++++++++++ samples/snippets/snippets.py | 116 ++++++++++++++++++++++++++++++ samples/snippets/snippets_test.py | 42 +++++++++++ 3 files changed, 222 insertions(+) create mode 100644 samples/snippets/README.md create mode 100644 samples/snippets/snippets.py create mode 100644 samples/snippets/snippets_test.py diff --git a/samples/snippets/README.md b/samples/snippets/README.md new file mode 100644 index 00000000..55aa8431 --- /dev/null +++ b/samples/snippets/README.md @@ -0,0 +1,64 @@ +Google Cloud Platform logo + +# Google Translate API Python Samples + +With the [Google Translate API][translate_docs], you can dynamically translate +text between thousands of language pairs. + +[translate_docs]: https://cloud.google.com/translate/docs/ + +## Table of Contents + +* [Setup](#setup) +* [Samples](#samples) + * [Translate](#translate) + +## Setup + +You will need to enable the Translate API and acquire and API key. See the +[documentation][translate_docs] for details on how to do this. + +Install dependencies: + + virtualenv env + source env/bin/activate + pip install -r requirements.txt + +## Samples + +### Translate + +View the [documentation][translate_docs] or the [source code][translate_code]. + +__Usage:__ `python snippets.py --help` + +``` +usage: snippets.py [-h] + api_key + {detect-language,list-languages,list-languages-with-target,translate-text} + ... + +This application demonstrates how to perform basic operations with the +Google Cloud Translate API + +For more information, the documentation at +https://cloud.google.com/translate/docs. + +positional arguments: + api_key Your API key. + {detect-language,list-languages,list-languages-with-target,translate-text} + detect-language Detects the text's language. + list-languages Lists all available langauges. + list-languages-with-target + Lists all available langauges and localizes them to + the target language. Target must be an ISO 639-1 + language code. + translate-text Translates text into the target language. Target must + be an ISO 639-1 language code. + +optional arguments: + -h, --help show this help message and exit +``` + +[translate_docs]: https://cloud.google.com/translate/docs +[translate_code]: snippets.py diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py new file mode 100644 index 00000000..1b5cad92 --- /dev/null +++ b/samples/snippets/snippets.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python + +# Copyright 2016 Google, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This application demonstrates how to perform basic operations with the +Google Cloud Translate API + +For more information, the documentation at +https://cloud.google.com/translate/docs. +""" + +import argparse + +from google.cloud import translate + + +def detect_language(api_key, text): + """Detects the text's language.""" + translate_client = translate.Client(api_key) + + # Text can also be a sequence of strings, in which case this method + # will return a sequence of results for each text. + result = translate_client.detect_language(text) + + print('Text: {}'.format(text)) + print('Confidence: {}'.format(result['confidence'])) + print('Language: {}'.format(result['language'])) + + +def list_languages(api_key): + """Lists all available languages.""" + translate_client = translate.Client(api_key) + + results = translate_client.get_languages() + + for language in results: + print(u'{name} ({language})'.format(**language)) + + +def list_languages_with_target(api_key, target): + """Lists all available languages and localizes them to the target language. + + Target must be an ISO 639-1 language code. + See https://g.co/cloud/translate/v2/translate-reference#supported_languages + """ + translate_client = translate.Client(api_key) + + results = translate_client.get_languages(target_language=target) + + for language in results: + print(u'{name} ({language})'.format(**language)) + + +def translate_text(api_key, target, text): + """Translates text into the target language. + + Target must be an ISO 639-1 language code. + See https://g.co/cloud/translate/v2/translate-reference#supported_languages + """ + translate_client = translate.Client(api_key) + + # Text can also be a sequence of strings, in which case this method + # will return a sequence of results for each text. + result = translate_client.translate(text, target_language=target) + + print(u'Text: {}'.format(result['input'])) + print(u'Translation: {}'.format(result['translatedText'])) + print(u'Detected source language: {}'.format( + result['detectedSourceLanguage'])) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('api_key', help='Your API key.') + subparsers = parser.add_subparsers(dest='command') + + detect_langage_parser = subparsers.add_parser( + 'detect-language', help=detect_language.__doc__) + detect_langage_parser.add_argument('text') + + list_languages_parser = subparsers.add_parser( + 'list-languages', help=list_languages.__doc__) + + list_languages_with_target_parser = subparsers.add_parser( + 'list-languages-with-target', help=list_languages_with_target.__doc__) + list_languages_with_target_parser.add_argument('target') + + translate_text_parser = subparsers.add_parser( + 'translate-text', help=translate_text.__doc__) + translate_text_parser.add_argument('target') + translate_text_parser.add_argument('text') + + args = parser.parse_args() + + if args.command == 'detect-language': + detect_language(args.api_key, args.text) + elif args.command == 'list-languages': + list_languages(args.api_key) + elif args.command == 'list-languages-with-target': + list_languages_with_target(args.api_key, args.target) + elif args.command == 'translate-text': + translate_text(args.api_key, args.target, args.text) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py new file mode 100644 index 00000000..79843233 --- /dev/null +++ b/samples/snippets/snippets_test.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- + +# Copyright 2016 Google, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import snippets + + +def test_detect_language(cloud_config, capsys): + snippets.detect_language(cloud_config.api_key, 'Hæ sæta') + out, _ = capsys.readouterr() + assert 'is' in out + + +def test_list_languages(cloud_config, capsys): + snippets.list_languages(cloud_config.api_key) + out, _ = capsys.readouterr() + assert 'Icelandic (is)' in out + + +def test_list_languages_with_target(cloud_config, capsys): + snippets.list_languages_with_target(cloud_config.api_key, 'is') + out, _ = capsys.readouterr() + assert u'íslenska (is)' in out + + +def test_translate_text(cloud_config, capsys): + snippets.translate_text(cloud_config.api_key, 'is', 'Hello world') + out, _ = capsys.readouterr() + assert u'Halló heimur' in out