Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 2f9bd03

Browse files
Jon Wayne Parrottdanoscarmike
Jon Wayne Parrott
authored andcommitted
Add translate samples [(#574)](GoogleCloudPlatform/python-docs-samples#574)
1 parent 8493bee commit 2f9bd03

File tree

3 files changed

+222
-0
lines changed

3 files changed

+222
-0
lines changed

samples/snippets/README.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
2+
3+
# Google Translate API Python Samples
4+
5+
With the [Google Translate API][translate_docs], you can dynamically translate
6+
text between thousands of language pairs.
7+
8+
[translate_docs]: https://cloud.google.com/translate/docs/
9+
10+
## Table of Contents
11+
12+
* [Setup](#setup)
13+
* [Samples](#samples)
14+
* [Translate](#translate)
15+
16+
## Setup
17+
18+
You will need to enable the Translate API and acquire and API key. See the
19+
[documentation][translate_docs] for details on how to do this.
20+
21+
Install dependencies:
22+
23+
virtualenv env
24+
source env/bin/activate
25+
pip install -r requirements.txt
26+
27+
## Samples
28+
29+
### Translate
30+
31+
View the [documentation][translate_docs] or the [source code][translate_code].
32+
33+
__Usage:__ `python snippets.py --help`
34+
35+
```
36+
usage: snippets.py [-h]
37+
api_key
38+
{detect-language,list-languages,list-languages-with-target,translate-text}
39+
...
40+
41+
This application demonstrates how to perform basic operations with the
42+
Google Cloud Translate API
43+
44+
For more information, the documentation at
45+
https://cloud.google.com/translate/docs.
46+
47+
positional arguments:
48+
api_key Your API key.
49+
{detect-language,list-languages,list-languages-with-target,translate-text}
50+
detect-language Detects the text's language.
51+
list-languages Lists all available langauges.
52+
list-languages-with-target
53+
Lists all available langauges and localizes them to
54+
the target language. Target must be an ISO 639-1
55+
language code.
56+
translate-text Translates text into the target language. Target must
57+
be an ISO 639-1 language code.
58+
59+
optional arguments:
60+
-h, --help show this help message and exit
61+
```
62+
63+
[translate_docs]: https://cloud.google.com/translate/docs
64+
[translate_code]: snippets.py

samples/snippets/snippets.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 Google, Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""This application demonstrates how to perform basic operations with the
18+
Google Cloud Translate API
19+
20+
For more information, the documentation at
21+
https://cloud.google.com/translate/docs.
22+
"""
23+
24+
import argparse
25+
26+
from google.cloud import translate
27+
28+
29+
def detect_language(api_key, text):
30+
"""Detects the text's language."""
31+
translate_client = translate.Client(api_key)
32+
33+
# Text can also be a sequence of strings, in which case this method
34+
# will return a sequence of results for each text.
35+
result = translate_client.detect_language(text)
36+
37+
print('Text: {}'.format(text))
38+
print('Confidence: {}'.format(result['confidence']))
39+
print('Language: {}'.format(result['language']))
40+
41+
42+
def list_languages(api_key):
43+
"""Lists all available languages."""
44+
translate_client = translate.Client(api_key)
45+
46+
results = translate_client.get_languages()
47+
48+
for language in results:
49+
print(u'{name} ({language})'.format(**language))
50+
51+
52+
def list_languages_with_target(api_key, target):
53+
"""Lists all available languages and localizes them to the target language.
54+
55+
Target must be an ISO 639-1 language code.
56+
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
57+
"""
58+
translate_client = translate.Client(api_key)
59+
60+
results = translate_client.get_languages(target_language=target)
61+
62+
for language in results:
63+
print(u'{name} ({language})'.format(**language))
64+
65+
66+
def translate_text(api_key, target, text):
67+
"""Translates text into the target language.
68+
69+
Target must be an ISO 639-1 language code.
70+
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
71+
"""
72+
translate_client = translate.Client(api_key)
73+
74+
# Text can also be a sequence of strings, in which case this method
75+
# will return a sequence of results for each text.
76+
result = translate_client.translate(text, target_language=target)
77+
78+
print(u'Text: {}'.format(result['input']))
79+
print(u'Translation: {}'.format(result['translatedText']))
80+
print(u'Detected source language: {}'.format(
81+
result['detectedSourceLanguage']))
82+
83+
84+
if __name__ == '__main__':
85+
parser = argparse.ArgumentParser(
86+
description=__doc__,
87+
formatter_class=argparse.RawDescriptionHelpFormatter)
88+
parser.add_argument('api_key', help='Your API key.')
89+
subparsers = parser.add_subparsers(dest='command')
90+
91+
detect_langage_parser = subparsers.add_parser(
92+
'detect-language', help=detect_language.__doc__)
93+
detect_langage_parser.add_argument('text')
94+
95+
list_languages_parser = subparsers.add_parser(
96+
'list-languages', help=list_languages.__doc__)
97+
98+
list_languages_with_target_parser = subparsers.add_parser(
99+
'list-languages-with-target', help=list_languages_with_target.__doc__)
100+
list_languages_with_target_parser.add_argument('target')
101+
102+
translate_text_parser = subparsers.add_parser(
103+
'translate-text', help=translate_text.__doc__)
104+
translate_text_parser.add_argument('target')
105+
translate_text_parser.add_argument('text')
106+
107+
args = parser.parse_args()
108+
109+
if args.command == 'detect-language':
110+
detect_language(args.api_key, args.text)
111+
elif args.command == 'list-languages':
112+
list_languages(args.api_key)
113+
elif args.command == 'list-languages-with-target':
114+
list_languages_with_target(args.api_key, args.target)
115+
elif args.command == 'translate-text':
116+
translate_text(args.api_key, args.target, args.text)

samples/snippets/snippets_test.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# -*- coding: utf-8 -*-
2+
3+
# Copyright 2016 Google, Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
18+
import snippets
19+
20+
21+
def test_detect_language(cloud_config, capsys):
22+
snippets.detect_language(cloud_config.api_key, 'Hæ sæta')
23+
out, _ = capsys.readouterr()
24+
assert 'is' in out
25+
26+
27+
def test_list_languages(cloud_config, capsys):
28+
snippets.list_languages(cloud_config.api_key)
29+
out, _ = capsys.readouterr()
30+
assert 'Icelandic (is)' in out
31+
32+
33+
def test_list_languages_with_target(cloud_config, capsys):
34+
snippets.list_languages_with_target(cloud_config.api_key, 'is')
35+
out, _ = capsys.readouterr()
36+
assert u'íslenska (is)' in out
37+
38+
39+
def test_translate_text(cloud_config, capsys):
40+
snippets.translate_text(cloud_config.api_key, 'is', 'Hello world')
41+
out, _ = capsys.readouterr()
42+
assert u'Halló heimur' in out

0 commit comments

Comments
 (0)