Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate samples #574

Merged
merged 4 commits into from
Oct 12, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ include =
pubsub/*
speech/*
storage/*
translate/*
vision/*
[report]
exclude_lines =
Expand Down
64 changes: 64 additions & 0 deletions translate/cloud-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<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"/>

# 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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about auth?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a notice and a link to the docs to do this.


## 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
116 changes: 116 additions & 0 deletions translate/cloud-client/snippets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!/usr/bin/env python

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonparrott README?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a basic one. Most of our samples do not have READMEs and instead lean on the docs. I want to do something similar to what Jason has done for Node, but it's low on the priority list.

# 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))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This stuff should probably be unicodes too, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one works better with native strings.

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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might also provide a link to //g.co/cloud/translate/v2/translate-reference#supported_languages since I don't think every language is supported.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

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)
42 changes: 42 additions & 0 deletions translate/cloud-client/snippets_test.py
Original file line number Diff line number Diff line change
@@ -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