Let's use Watson from Python! --How to use Developer Cloud Python SDK

This article is the 16th day article of IBM Cloud Advent Calendar 2020.

IBM Cloud AI service Watson can be called with REST API. You can also use SDK in various major languages.

This article describes how to use IBM Watson services from Python using the SDK. This article has been tested based on the following versions: v5.0.0

Please note that the usage changes depending on the version.

In v5.0.0, the following API calls can be made.

0. Prerequisites

--Has an IBM Cloud account --Service created (Language Translator in the example below)

--If you don't know how to do it, please refer to here.

--There is an execution environment of python 3.5 or higher

1. Preparation

Make sure that you can check the API KEY and URL of the service you created. If you don't know how to do it, please refer to here: Get Service Credentials (https://qiita.com/nishikyon/items/9b8f697db7ad0a693839#2-%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%81%AE%E8%B3%87%E6%A0%BC%E6%83%85%E5%A0%B1%E5%8F%96%E5%BE%97)

2. Basics of using Watson SDK

First of all, I will introduce how to find out how to use it in general regardless of the language. How to use the SDKs for various major languages ​​is actually in the API documentation on IBM Cloud!

In the API & SDK Reference Library category [AI / Machine Learning](https://cloud.ibm.com/docs?tab=api-docs & category = ai), there are links to the API & SDK documentation for each service.

In this article, we will use Language Translator as an example, so please create a service for Language Translator.

Basic 1: Click the service you want to use from the API & SDK reference library

This time, we will use Language Translator, so click ** Language Translator ** from API & SDK Reference Library Category ** AI / Machine Learning **. image.png

Basic 2: Click the language you want to use from the tab on the right that says "Curl Java Node Python Go" etc.

This time it's Python, so click "Python". By the way, when I checked on 2020/12/15, Curl, Java, Node, Python, Go, .NET, Ruby, Swift, Unity were in the tabs. image.png

Basic 3: Click Subject you want to know how to use from the menu on the left.

For example, if it is "Introduction", the installation method with pip is described. You can copy and execute it. image.png

For example, if Method "Translate", the definition and sample code of the selected language will be displayed on the right side. You can copy and paste the sample code and execute it. However, note that you need to replace {apikey} and {url} with those of your service. Replace it with the one prepared in 1. Preparation. image.png

3. Let's start with Python!

For those who have drawn "2. Basics of using Watson SDK, the document is in English, but ...", I will explain how to use it. However, you can't understand the use of detailed SDK without looking at the SDK reference, so if you get a feel for it, please check the SDK reference for details. Code is a common language, isn't it?

Here, Language Translator is used as an example.

3.1 First, install the library

You can install it with the following pip command.

pip install --upgrade ibm-watson

3.2 Creating an instance

Almost a copy of the sample code here (https://cloud.ibm.com/apidocs/language-translator?code=python#authentication).

In the sample code of here, for example, '{apikey}' is written, it is better to write '{xxxxxxxxx}' (xxxxxxxxx is your apikey) in the code. It's fine to do it. It's hard to understand, but ** {} ** is unnecessary. Replace with {apikey}. The code below was first defined as a variable without the ** {} ** description.

APIKEY='Enter your API KEY'
URL='Enter your URL'
VERSION='2018-05-01' #Please enter the version you want to use

from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator(APIKEY)
language_translator = LanguageTranslatorV3(
    version=VERSION,
    authenticator=authenticator
)

language_translator.set_service_url(URL)

For the above VERSION, click "Versioning" on the right side of API Document, and the version assumed in the document is described, so I think it is better to use that value.

image.png

3.3 Method call

Language Translator is a translation service, so let's call the translation method "Translate".

For the Method name of the calling method, the contents of the parameters, etc., click Basic 3: Subject to know how to use from the menu on the left. , click the content you want to know from the right side of API Document and it will be displayed with the sample code.

Write the following code after the 3.2 Create Instance code. Since model_id ='en-es', it is a translation from English (en) to Spanish (es).

translation = language_translator.translate(
    text='Hello, how are you today?',
    model_id='en-es').get_result()

What is returned by get_result () in the return value of language_translator.translate () is written in the middle column of API documentation. image.png

Also, the whole return value can be found in the API document under Data Handling Response details. In addition to get_result (), it is possible to get Header information and HTTP Status Code. image.png

Let's view the results. Indented for easy viewing:

import json

print(json.dumps(translation, indent=2, ensure_ascii=False))

What you see:

{
  "translations": [
    {
      "translation": "Hola, ¿cómo estás hoy?"
    }
  ],
  "word_count": 7,
  "character_count": 25
}

If you want only the translation result, specify as follows (it will be a dictionary type):

print (translation[ "translations"][0]["translation"])

What you see:

Hola, ¿cómo estás hoy?

that's all.

4. Finally

If you suppress the points of usage, I think that Code can be easily applied even if the API document is in English, so please try it with other APIs!

Recommended Posts

Let's use Watson from Python! --How to use Developer Cloud Python SDK
Study from Python Hour7: How to use classes
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
Python: How to use async with
[Hyperledger Iroha] Notes on how to use the Python SDK
How to use Requests (Python Library)
How to use SQLite in Python
How to upload files to Cloud Storage with Firebase's python SDK
[Introduction to Python] Let's use pandas
[Python] How to use list 3 Added
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to access wikipedia from python
How to use python zip function
[Introduction to Python] Let's use pandas
[Python] How to use Typetalk API
How to connect to Cloud Firestore from Google Cloud Functions with python code
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to use cybozu.com developer network (Part 2)
How to update Google Sheets from Python
[TF] How to use Tensorboard from Keras
[python] How to use __command__, function explanation
I want to use jar from python
[Introduction to Python] Let's use foreach with Python
[Python] How to use import sys sys.argv
Use Google Cloud Vision API from Python
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
How to access RDS from Lambda (python)
python: How to use locals () and globals ()
How to switch python versions in cloud9
How to use __slots__ in Python class
How to use "deque" for Python data
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Summary of how to use Python list
How to use GCP's Cloud Vision API
How to use regular expressions in Python
[Python2.7] Summary of how to use subprocess
How to use is and == in Python
[Blender x Python] How to use modifiers
[Question] How to use plot_surface of python
How to use the C library in Python
[Python] How to use two types of type ()
How to open a web browser from python
[Introduction to Udemy Python3 + Application] 23. How to use tuples
Firebase: Use Cloud Firestore and Cloud Storage from Python