Using Machine Learning APIs

First, visit API console, choose "Credentials" on the left-hand menu. Choose "Create Credentials" and generate an API key for your application. You should probably restrict it by IP address to prevent abuse, but for now, just leave that field blank and delete the API key after trying out this demo.

Copy-paste your API Key here:


In [ ]:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst

In [2]:
APIKEY="CHANGE-THIS-KEY"  # Replace with your API key

Note: Make sure you generate an API Key and replace the value above. The sample key will not work.

From the same API console, choose "Dashboard" on the left-hand menu and "Enable API".

Enable the following APIs for your project (search for them) if they are not already enabled:

  1. Google Translate API
  2. Google Cloud Vision API
  3. Google Natural Language API
  4. Google Cloud Speech API

Finally, because we are calling the APIs from Python (clients in many other languages are available), let's install the Python package (it's not installed by default on Datalab)


In [ ]:
!pip install --user --upgrade google-api-python-client

Invoke Translate API


In [3]:
# running Translate API
from googleapiclient.discovery import build
service = build('translate', 'v2', developerKey=APIKEY)

# use the service
inputs = ['is it really this easy?', 'amazing technology', 'wow']
outputs = service.translations().list(source='en', target='fr', q=inputs).execute()
# print outputs
for input, output in zip(inputs, outputs['translations']):
  print("{0} -> {1}".format(input, output['translatedText']))


is it really this easy? -> est-ce vraiment si facile?
amazing technology -> technologie incroyable
wow -> sensationnel

Invoke Vision API

The Vision API can work off an image in Cloud Storage or embedded directly into a POST message. I'll use Cloud Storage and do OCR on this image: . That photograph is from http://www.publicdomainpictures.net/view-image.php?image=15842


In [5]:
# Running Vision API
import base64
IMAGE="gs://cloud-training-demos/vision/sign2.jpg"
vservice = build('vision', 'v1', developerKey=APIKEY)
request = vservice.images().annotate(body={
        'requests': [{
                'image': {
                    'source': {
                        'gcs_image_uri': IMAGE
                    }
                },
                'features': [{
                    'type': 'TEXT_DETECTION',
                    'maxResults': 3,
                }]
            }],
        })
responses = request.execute(num_retries=3)
print(responses)


{'responses': [{'textAnnotations': [{'description': '请您爱护和保\n护卫生创建优\n美水环境\n', 'locale': 'zh', 'boundingPoly': {'vertices': [{'y': 104, 'x': 152}, {'y': 104, 'x': 1082}, {'y': 658, 'x': 1082}, {'y': 658, 'x': 152}]}}, {'description': '请', 'boundingPoly': {'vertices': [{'y': 104, 'x': 179}, {'y': 104, 'x': 321}, {'y': 243, 'x': 321}, {'y': 243, 'x': 179}]}}, {'description': '您', 'boundingPoly': {'vertices': [{'y': 108, 'x': 329}, {'y': 108, 'x': 471}, {'y': 243, 'x': 471}, {'y': 243, 'x': 329}]}}, {'description': '爱护', 'boundingPoly': {'vertices': [{'y': 108, 'x': 479}, {'y': 108, 'x': 775}, {'y': 243, 'x': 775}, {'y': 243, 'x': 479}]}}, {'description': '和', 'boundingPoly': {'vertices': [{'y': 111, 'x': 786}, {'y': 111, 'x': 925}, {'y': 243, 'x': 925}, {'y': 243, 'x': 786}]}}, {'description': '保', 'boundingPoly': {'vertices': [{'y': 104, 'x': 933}, {'y': 104, 'x': 1079}, {'y': 239, 'x': 1079}, {'y': 239, 'x': 933}]}}, {'description': '护', 'boundingPoly': {'vertices': [{'y': 300, 'x': 165}, {'y': 300, 'x': 312}, {'y': 440, 'x': 312}, {'y': 440, 'x': 165}]}}, {'description': '卫生', 'boundingPoly': {'vertices': [{'y': 304, 'x': 316}, {'y': 304, 'x': 619}, {'y': 440, 'x': 619}, {'y': 440, 'x': 316}]}}, {'description': '创建', 'boundingPoly': {'vertices': [{'y': 304, 'x': 631}, {'y': 304, 'x': 930}, {'y': 444, 'x': 930}, {'y': 444, 'x': 631}]}}, {'description': '优', 'boundingPoly': {'vertices': [{'y': 300, 'x': 938}, {'y': 300, 'x': 1082}, {'y': 440, 'x': 1082}, {'y': 440, 'x': 938}]}}, {'description': '美', 'boundingPoly': {'vertices': [{'y': 503, 'x': 158}, {'y': 509, 'x': 304}, {'y': 655, 'x': 297}, {'y': 649, 'x': 152}]}}, {'description': '水', 'boundingPoly': {'vertices': [{'y': 501, 'x': 313}, {'y': 508, 'x': 464}, {'y': 653, 'x': 457}, {'y': 647, 'x': 307}]}}, {'description': '环境', 'boundingPoly': {'vertices': [{'y': 499, 'x': 466}, {'y': 512, 'x': 772}, {'y': 658, 'x': 765}, {'y': 645, 'x': 460}]}}], 'fullTextAnnotation': {'text': '请您爱护和保\n护卫生创建优\n美水环境\n', 'pages': [{'blocks': [{'boundingBox': {'vertices': [{'y': 104, 'x': 152}, {'y': 104, 'x': 1082}, {'y': 658, 'x': 1082}, {'y': 658, 'x': 152}]}, 'blockType': 'TEXT', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}, 'paragraphs': [{'boundingBox': {'vertices': [{'y': 104, 'x': 152}, {'y': 104, 'x': 1082}, {'y': 658, 'x': 1082}, {'y': 658, 'x': 152}]}, 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}, 'words': [{'boundingBox': {'vertices': [{'y': 104, 'x': 179}, {'y': 104, 'x': 321}, {'y': 243, 'x': 321}, {'y': 243, 'x': 179}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 104, 'x': 179}, {'y': 104, 'x': 321}, {'y': 243, 'x': 321}, {'y': 243, 'x': 179}]}, 'text': '请', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 108, 'x': 329}, {'y': 108, 'x': 471}, {'y': 243, 'x': 471}, {'y': 243, 'x': 329}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 108, 'x': 329}, {'y': 108, 'x': 471}, {'y': 243, 'x': 471}, {'y': 243, 'x': 329}]}, 'text': '您', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 108, 'x': 479}, {'y': 108, 'x': 775}, {'y': 243, 'x': 775}, {'y': 243, 'x': 479}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 108, 'x': 479}, {'y': 108, 'x': 621}, {'y': 243, 'x': 621}, {'y': 243, 'x': 479}]}, 'text': '爱', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 108, 'x': 633}, {'y': 108, 'x': 775}, {'y': 243, 'x': 775}, {'y': 243, 'x': 633}]}, 'text': '护', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 111, 'x': 786}, {'y': 111, 'x': 925}, {'y': 243, 'x': 925}, {'y': 243, 'x': 786}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 111, 'x': 786}, {'y': 111, 'x': 925}, {'y': 243, 'x': 925}, {'y': 243, 'x': 786}]}, 'text': '和', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 104, 'x': 933}, {'y': 104, 'x': 1079}, {'y': 239, 'x': 1079}, {'y': 239, 'x': 933}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 104, 'x': 933}, {'y': 104, 'x': 1079}, {'y': 239, 'x': 1079}, {'y': 239, 'x': 933}]}, 'text': '保', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}], 'detectedBreak': {'type': 'EOL_SURE_SPACE'}}}], 'property': {'detectedLanguages': [{'languageCode': 'ja'}]}}, {'boundingBox': {'vertices': [{'y': 300, 'x': 165}, {'y': 300, 'x': 312}, {'y': 440, 'x': 312}, {'y': 440, 'x': 165}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 300, 'x': 165}, {'y': 300, 'x': 312}, {'y': 440, 'x': 312}, {'y': 440, 'x': 165}]}, 'text': '护', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 304, 'x': 316}, {'y': 304, 'x': 619}, {'y': 440, 'x': 619}, {'y': 440, 'x': 316}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 311, 'x': 316}, {'y': 311, 'x': 460}, {'y': 436, 'x': 460}, {'y': 436, 'x': 316}]}, 'text': '卫', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 304, 'x': 472}, {'y': 304, 'x': 619}, {'y': 440, 'x': 619}, {'y': 440, 'x': 472}]}, 'text': '生', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 304, 'x': 631}, {'y': 304, 'x': 930}, {'y': 444, 'x': 930}, {'y': 444, 'x': 631}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 304, 'x': 631}, {'y': 304, 'x': 771}, {'y': 444, 'x': 771}, {'y': 444, 'x': 631}]}, 'text': '创', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 308, 'x': 786}, {'y': 308, 'x': 930}, {'y': 444, 'x': 930}, {'y': 444, 'x': 786}]}, 'text': '建', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 300, 'x': 938}, {'y': 300, 'x': 1082}, {'y': 440, 'x': 1082}, {'y': 440, 'x': 938}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 300, 'x': 938}, {'y': 300, 'x': 1082}, {'y': 440, 'x': 1082}, {'y': 440, 'x': 938}]}, 'text': '优', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}], 'detectedBreak': {'type': 'EOL_SURE_SPACE'}}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 503, 'x': 158}, {'y': 509, 'x': 304}, {'y': 655, 'x': 297}, {'y': 649, 'x': 152}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 503, 'x': 158}, {'y': 509, 'x': 304}, {'y': 655, 'x': 297}, {'y': 649, 'x': 152}]}, 'text': '美', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 501, 'x': 313}, {'y': 508, 'x': 464}, {'y': 653, 'x': 457}, {'y': 647, 'x': 307}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 501, 'x': 313}, {'y': 508, 'x': 464}, {'y': 653, 'x': 457}, {'y': 647, 'x': 307}]}, 'text': '水', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}], 'property': {'detectedLanguages': [{'languageCode': 'ja'}]}}, {'boundingBox': {'vertices': [{'y': 499, 'x': 466}, {'y': 512, 'x': 772}, {'y': 658, 'x': 765}, {'y': 645, 'x': 460}]}, 'symbols': [{'boundingBox': {'vertices': [{'y': 503, 'x': 465}, {'y': 510, 'x': 623}, {'y': 652, 'x': 617}, {'y': 645, 'x': 459}]}, 'text': '环', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}, {'boundingBox': {'vertices': [{'y': 506, 'x': 620}, {'y': 513, 'x': 771}, {'y': 658, 'x': 764}, {'y': 652, 'x': 614}]}, 'text': '境', 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}], 'detectedBreak': {'type': 'EOL_SURE_SPACE'}}}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}}]}]}], 'property': {'detectedLanguages': [{'languageCode': 'zh-Hans'}]}, 'width': 1280, 'height': 818}]}}]}

In [6]:
foreigntext = responses['responses'][0]['textAnnotations'][0]['description']
foreignlang = responses['responses'][0]['textAnnotations'][0]['locale']
print(foreignlang, foreigntext)


zh 请您爱护和保
护卫生创建优
美水环境

Translate sign


In [7]:
inputs=[foreigntext]
outputs = service.translations().list(source=foreignlang, target='en', q=inputs).execute()
# print(outputs)
for input, output in zip(inputs, outputs['translations']):
  print("{0} -> {1}".format(input, output['translatedText']))


请您爱护和保
护卫生创建优
美水环境
 -> Please care for and protect the health to create a beautiful water environment

Sentiment analysis with Language API

Let's evaluate the sentiment of some famous quotes using Google Cloud Natural Language API.


In [8]:
lservice = build('language', 'v1beta1', developerKey=APIKEY)
quotes = [
  'To succeed, you must have tremendous perseverance, tremendous will.',
  'It’s not that I’m so smart, it’s just that I stay with problems longer.',
  'Love is quivering happiness.',
  'Love is of all passions the strongest, for it attacks simultaneously the head, the heart, and the senses.',
  'What difference does it make to the dead, the orphans and the homeless, whether the mad destruction is wrought under the name of totalitarianism or in the holy name of liberty or democracy?',
  'When someone you love dies, and you’re not expecting it, you don’t lose her all at once; you lose her in pieces over a long time — the way the mail stops coming, and her scent fades from the pillows and even from the clothes in her closet and drawers. '
]
for quote in quotes:
  response = lservice.documents().analyzeSentiment(
    body={
      'document': {
         'type': 'PLAIN_TEXT',
         'content': quote
      }
    }).execute()
  polarity = response['documentSentiment']['polarity']
  magnitude = response['documentSentiment']['magnitude']
  print('POLARITY=%s MAGNITUDE=%s for %s' % (polarity, magnitude, quote))


POLARITY=1 MAGNITUDE=0.9 for To succeed, you must have tremendous perseverance, tremendous will.
POLARITY=-1 MAGNITUDE=0.5 for It’s not that I’m so smart, it’s just that I stay with problems longer.
POLARITY=1 MAGNITUDE=0.9 for Love is quivering happiness.
POLARITY=1 MAGNITUDE=0.9 for Love is of all passions the strongest, for it attacks simultaneously the head, the heart, and the senses.
POLARITY=1 MAGNITUDE=0.2 for What difference does it make to the dead, the orphans and the homeless, whether the mad destruction is wrought under the name of totalitarianism or in the holy name of liberty or democracy?
POLARITY=-1 MAGNITUDE=0.4 for When someone you love dies, and you’re not expecting it, you don’t lose her all at once; you lose her in pieces over a long time — the way the mail stops coming, and her scent fades from the pillows and even from the clothes in her closet and drawers. 

Speech API

The Speech API can work on streaming data, audio content encoded and embedded directly into the POST message, or on a file on Cloud Storage. Here I'll pass in this audio file in Cloud Storage.


In [10]:
sservice = build('speech', 'v1', developerKey=APIKEY)
response = sservice.speech().recognize(
    body={
        'config': {
            'languageCode' : 'en-US',
            'encoding': 'LINEAR16',
            'sampleRateHertz': 16000
        },
        'audio': {
            'uri': 'gs://cloud-training-demos/vision/audio.raw'
            }
        }).execute()
print(response)


{'results': [{'alternatives': [{'confidence': 0.98360395, 'transcript': 'how old is the Brooklyn Bridge'}]}]}

In [11]:
print(response['results'][0]['alternatives'][0]['transcript'])
print('Confidence=%f' % response['results'][0]['alternatives'][0]['confidence'])


how old is the Brooklyn Bridge
Confidence=0.983604

Clean up

Remember to delete the API key by visiting API console.

If necessary, commit all your notebooks to git.

If you are running Datalab on a Compute Engine VM or delegating to one, remember to stop or shut it down so that you are not charged.

Challenge Exercise

Here are a few portraits from the Metropolitan Museum of Art, New York (they are part of a BigQuery public dataset ):

  • gs://cloud-training-demos/images/met/APS6880.jpg
  • gs://cloud-training-demos/images/met/DP205018.jpg
  • gs://cloud-training-demos/images/met/DP290402.jpg
  • gs://cloud-training-demos/images/met/DP700302.jpg

Use the Vision API to identify which of these images depict happy people and which ones depict unhappy people.

Hint (highlight to see):

You will need to look for joyLikelihood and/or sorrowLikelihood from the response.

Copyright 2018 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.


In [ ]: