Coder Social home page Coder Social logo

watson-developer-cloud / python-sdk Goto Github PK

View Code? Open in Web Editor NEW
1.5K 126.0 830.0 39.61 MB

:snake: Client library to use the IBM Watson services in Python and available in pip as watson-developer-cloud

Home Page: https://pypi.org/project/ibm-watson/

License: Apache License 2.0

Python 99.56% Shell 0.01% HTML 0.44% Dockerfile 0.01%
hacktoberfest

python-sdk's Introduction

Watson Developer Cloud Python SDK

Build and Test Deploy and Publish Latest Stable Version CLA assistant

Deprecated builds

Build Status

Python client library to quickly get started with the various [Watson APIs][wdc] services.

Before you begin

  • You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support python 3.5 and above

Installation

To install, use pip or easy_install:

pip install --upgrade ibm-watson

or

easy_install --upgrade ibm-watson

Note the following: a) Versions prior to 3.0.0 can be installed using:

pip install --upgrade watson-developer-cloud

b) If you run into permission issues try:

sudo -H pip install --ignore-installed six ibm-watson

For more details see #225

c) In case you run into problems installing the SDK in DSX, try

!pip install --upgrade pip

Restarting the kernel

For more details see #405

Examples

The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have service credentials.

Running in IBM Cloud

If you run your app in IBM Cloud, the SDK gets credentials from the [VCAP_SERVICES][vcap_services] environment variable.

Authentication

Watson services are migrating to token-based Identity and Access Management (IAM) authentication.

  • With some service instances, you authenticate to the API by using IAM.
  • In other instances, you authenticate by providing the username and password for the service instance.

Getting credentials

To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:

  1. Go to the IBM Cloud Dashboard page.
  2. Either click an existing Watson service instance in your resource list or click Create resource > AI and create a service instance.
  3. Click on the Manage item in the left nav bar of your service instance.

On this page, you should be able to see your credentials for accessing your service instance.

Supplying credentials

There are three ways to supply the credentials you found above to the SDK for authentication.

Credential file

With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking the Download button for the credentials in the Manage tab of your service instance.

The file downloaded will be called ibm-credentials.env. This is the name the SDK will search for and must be preserved unless you want to configure the file path (more on that later). The SDK will look for your ibm-credentials.env file in the following places (in order):

  • The top-level directory of the project you're using the SDK in
  • Your system's home directory

As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:

discovery = DiscoveryV1(version='2019-04-30')

And that's it!

If you're using more than one service at a time in your code and get two different ibm-credentials.env files, just put the contents together in one ibm-credentials.env file and the SDK will handle assigning credentials to their appropriate services.

If you would like to configure the location/name of your credential file, you can set an environment variable called IBM_CREDENTIALS_FILE. This will take precedence over the locations specified above. Here's how you can do that:

export IBM_CREDENTIALS_FILE="<path>"

where <path> is something like /home/user/Downloads/<file_name>.env.

Environment Variables

Simply set the environment variables using _ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance:

export ASSISTANT_APIKEY="<your apikey>"
export ASSISTANT_AUTH_TYPE="iam"

The credentials will be loaded from the environment automatically

assistant = AssistantV1(version='2018-08-01')

Manually

If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you.

IAM

IBM Cloud has migrated to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.

You supply either an IAM service API key or a bearer token:

  • Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
  • Use the access token if you want to manage the lifecycle yourself. For details, see Authenticating with IAM tokens.
  • Use a server-side to generate access tokens using your IAM API key for untrusted environments like client-side scripts. The generated access tokens will be valid for one hour and can be refreshed.

Supplying the API key

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

# In the constructor, letting the SDK manage the token
authenticator = IAMAuthenticator('apikey',
                                 url='<iam_url>') # optional - the default value is https://iam.cloud.ibm.com/identity/token
discovery = DiscoveryV1(version='2019-04-30',
                        authenticator=authenticator)
discovery.set_service_url('<url_as_per_region>')

Generating bearer tokens using API key

from ibm_watson import IAMTokenManager

# In your API endpoint use this to generate new bearer tokens
iam_token_manager = IAMTokenManager(apikey='<apikey>')
token = iam_token_manager.get_token()
Supplying the bearer token
from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator

# in the constructor, assuming control of managing the token
authenticator = BearerTokenAuthenticator('your bearer token')
discovery = DiscoveryV1(version='2019-04-30',
                        authenticator=authenticator)
discovery.set_service_url('<url_as_per_region>')

Username and password

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

authenticator = BasicAuthenticator('username', 'password')
discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator)
discovery.set_service_url('<url_as_per_region>')

No Authentication

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator

authenticator = NoAuthAuthenticator()
discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator)
discovery.set_service_url('<url_as_per_region>')

MCSP

To use the SDK through a third party cloud provider (such as AWS), use the MCSPAuthenticator. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey.

from ibm_watson import AssistantV2
from ibm_cloud_sdk_core.authenticators import MCSPAuthenticator

# In the constructor, letting the SDK manage the token
authenticator = MCSPAuthenticator('apikey', 'token_service_endpoint')
assistant = AssistantV2(version='2023-06-15',
                        authenticator=authenticator)
assistant.set_service_url('<url_as_per_region>')

Python version

Tested on Python 3.9, 3.10, and 3.11.

Questions

If you have issues with the APIs or have a question about the Watson services, see Stack Overflow.

Configuring the http client (Supported from v1.1.0)

To set client configs like timeout use the set_http_config() function and pass it a dictionary of configs. See this documentation for more information about the options. All options shown except method, url, headers, params, data, and auth are configurable via set_http_config(). For example for a Assistant service instance

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your apikey')
assistant = AssistantV1(
    version='2021-11-27',
    authenticator=authenticator)
assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')

assistant.set_http_config({'timeout': 100})
response = assistant.message(workspace_id=workspace_id, input={
    'text': 'What\'s the weather like?'}).get_result()
print(json.dumps(response, indent=2))

Use behind a corporate proxy

To use the SDK with any proxies you may have they can be set as shown below. For documentation on proxies see here

See this example configuration:

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your apikey')
assistant = AssistantV1(
    version='2021-11-27',
    authenticator=authenticator)
assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')

assistant.set_http_config({'proxies': {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}})

Sending custom certificates

To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent.

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your apikey')
assistant = AssistantV1(
    version='2021-11-27',
    authenticator=authenticator)
assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')

assistant.set_http_config({'cert': ('path_to_cert_file','path_to_key_file')})

Disable SSL certificate verification

For ICP(IBM Cloud Private), you can disable the SSL certificate verification by:

service.set_disable_ssl_verification(True)

Or can set it from extrernal sources. For example set in the environment variable.

export <service name>_DISABLE_SSL=True

Setting the service url

To set the base service to be used when contacting the service

service.set_service_url('my_new_service_url')

Or can set it from extrernal sources. For example set in the environment variable.

export <service name>_URL="<your url>"

Sending request headers

Custom headers can be passed in any request in the form of a dict as:

headers = {
    'Custom-Header': 'custom_value'
}

For example, to send a header called Custom-Header to a call in Watson Assistant, pass the headers parameter as:

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your apikey')
assistant = AssistantV1(
    version='2018-07-10',
    authenticator=authenticator)
assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api')

response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result()

Parsing HTTP response information

If you would like access to some HTTP response information along with the response model, you can set the set_detailed_response() to True. Since Python SDK v2.0, it is set to True

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your apikey')
assistant = AssistantV1(
    version='2018-07-10',
    authenticator=authenticator)
assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api')

assistant.set_detailed_response(True)
response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result()
print(response)

This would give an output of DetailedResponse having the structure:

{
    'result': <response returned by service>,
    'headers': { <http response headers> },
    'status_code': <http status code>
}

You can use the get_result(), get_headers() and get_status_code() to return the result, headers and status code respectively.

Getting the transaction ID

Every SDK call returns a response with a transaction ID in the X-Global-Transaction-Id header. Together the service instance region, this ID helps support teams troubleshoot issues from relevant logs.

Suceess

from ibm_watson import AssistantV1

service = AssistantV1(authenticator={my_authenticator})
response_headers = service.my_service_call().get_headers()
print(response_headers.get('X-Global-Transaction-Id'))

Failure

from ibm_watson import AssistantV1, ApiException

try:
    service = AssistantV1(authenticator={my_authenticator})
    service.my_service_call()
except ApiException as e:
    print(e.global_transaction_id)
    # OR
    print(e.http_response.headers.get('X-Global-Transaction-Id'))

However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace <my-unique-transaction-id> in the following example with a unique transaction ID.

from ibm_watson import AssistantV1

service = AssistantV1(authenticator={my_authenticator})
service.my_service_call(headers={'X-Global-Transaction-Id': '<my-unique-transaction-id>'})

Using Websockets

The Text to Speech service supports synthesizing text to spoken audio using web sockets with the synthesize_using_websocket. The Speech to Text service supports recognizing speech to text using web sockets with the recognize_using_websocket. These methods need a custom callback class to listen to events. Below is an example of synthesize_using_websocket. Note: The service accepts one request per connection.

from ibm_watson.websocket import SynthesizeCallback

class MySynthesizeCallback(SynthesizeCallback):
    def __init__(self):
        SynthesizeCallback.__init__(self)

    def on_audio_stream(self, audio_stream):
        return audio_stream

    def on_data(self, data):
        return data

my_callback = MySynthesizeCallback()
service.synthesize_using_websocket('I like to pet dogs',
                                   my_callback,
                                   accept='audio/wav',
                                   voice='en-US_AllisonVoice'
                                  )

Cloud Pak for Data

If your service instance is of CP4D, below are two ways of initializing the assistant service.

1) Supplying the username, password and authentication url

The SDK will manage the token for the user

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator

authenticator = CloudPakForDataAuthenticator(
    '<your username>',
    '<your password>',
    '<authentication url>', # should be of the form https://{icp_cluster_host}{instance-id}/api
    disable_ssl_verification=True) # Disable ssl verification for authenticator

assistant = AssistantV1(
    version='<version>',
    authenticator=authenticator)
assistant.set_service_url('<service url>') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api
assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED

2) Supplying the access token

from ibm_watson import AssistantV1
from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator

authenticator = BearerTokenAuthenticator('your managed access token')
assistant = AssistantV1(version='<version>',
                        authenticator=authenticator)
assistant.set_service_url('<service url>') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api
assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED

Logging

Enable logging

import logging
logging.basicConfig(level=logging.DEBUG)

This would show output of the form:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): iam.cloud.ibm.com:443
DEBUG:urllib3.connectionpool:https://iam.cloud.ibm.com:443 "POST /identity/token HTTP/1.1" 200 1809
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "POST /assistant/api/v1/workspaces?version=2018-07-10 HTTP/1.1" 201 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "GET /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10&export=true HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "DELETE /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10 HTTP/1.1" 200 28

Low level request and response dump

To get low level information of the requests/ responses:

from http.client import HTTPConnection
HTTPConnection.debuglevel = 1

Dependencies

  • [requests]
  • python_dateutil >= 2.5.3
  • [responses] for testing
  • Following for web sockets support in speech to text
    • websocket-client 1.1.0
  • ibm_cloud_sdk_core >= 3.16.2

Contributing

See [CONTRIBUTING.md][contributing].

License

This library is licensed under the [Apache 2.0 license][license].

python-sdk's People

Contributors

1ucian0 avatar ammardodin avatar apaparazzi0329 avatar aprilwebster avatar cclauss avatar ehdsouza avatar g-may avatar germanattanasio avatar glennrfisher avatar herchu avatar hsaylor avatar jeffpk62 avatar jsstylos avatar kcheat avatar kingsodigie avatar kognate avatar mamoonraja avatar maniax89 avatar manishth avatar mediumtaj avatar michelle-miller avatar mikemosca avatar mnr avatar samir-patel avatar samuel500 avatar sdague avatar semantic-release-bot avatar shuisman avatar sirspidey avatar w0o avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-sdk's Issues

Current build of master branch is failing

From the Travis CI logs of the failures for what seems to be all supported versions of Python....

The command "openssl aes-256-cbc -K $encrypted_c3e85137836d_key -iv $encrypted_c3e85137836d_iv -in .env.enc -out .env -d" failed and exited with 1 during .

[relationship-extraction] Allow developers to choose the return type ('json', 'xml')

This is not an issue, I just wanted to bring this up as an enchancement: If you see the file "relationship_extraction_v1_beta.py", you can see that "'rt': 'xml'" is hardcoded.

This means that this service will ALWAYS return "XML" as its format. However, I prefer using JSON, and other developers have their own preferences, so I propose a solution: Just let the developer choose which Data Type they prefer! We can do this by adding "rt" or "return_type" as one of the parameters passed into the "extract" function of the class.

Add read-the-docs support

We can easily add read-the-docs as our documentation site for the python sdk. I already did some work in conf.py. Our documentation is in markdown so we will have to do some conversions.

Unicode and Language Translation

Not sure if this is an issue or not but when passing in unicode to the language detection needs to be encoded. ie. if data is unicode then it has to be encoded

txt = data.encode("utf-8", "replace")

and the encoded text passed into identify

language_translation.identify(txt)

whereas
language_translation.identify(data)
throws a unicode error.

Generally broken get_news_documents method

def get_news_documents(self, start, end, max_results=10, query_fields=None, return_fields=None, time_slice=None):
    if isinstance(return_fields, list):
        return_fields = ','.join(return_fields)
    params = {'start': start,
              'end': end,
              'maxResults': max_results,
              'return': return_fields,
              'timeSlice': time_slice}
    if isinstance(query_fields, dict):
        for key in query_fields:
            params[key if key.startswith('q.') else 'q.' + key] = query_fields[key]
    return self._alchemy_html_request(method_url='/data/GetNews', method='GET', params=params)

This method incorrectly handles the query_fields parameter by assuming all query_fields are prefixed with the letter 'q'. Query fields like dedup and dedupThreshold cannot be passed into this function since they should not be prefixed with a q. This issue is also responsible for a PR I made with respect to another issue I created around the use of pagination #53

The python-sdk is incompatible with a Permuation of Korean Laptop / Korean Code Page and Python 3

Although it is ok with a Korean Laptop / Korean Code Page and Python 2.
Talking to my Korean colleagues I have learnt that this is quire common for pip packages, which is why they stick to Python 2. The strange thing is that the other packages they installed (django and request), were both OK.
Short term fix is a note in the readme. Long term fix is to modify the code that breaks using the Korean Python 3 permutation.

Improve the error message for 401 responses

Currently if we don't use valid credentials we get:

watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: 
<HTML><HEAD><meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<TITLE>Watson Error</TITLE>
</HEAD>
<BODY>
<HR>
<p>Invalid access to resource - /speech-to-text/api/watson-auth-token</p>
<p>User access not Authorized.</p>
<p>Gateway Error Code : ERCD50-LDAP-NODN-ERR</p>
<p>Unable to communicate with Watson.</p>
<p>Request URL : /speech-to-text/api/watson-auth-token</p>
<p>Error Id : 847403581</p><p>Date-Time : 2015-10-15T12:35:53-05:00</p>
</BODY>
</HTML>, Code: 401

As with the node-sdk and java-sdk we should return
"Unauthorized: Access is denied due to invalid credentials"

Installation should not depend on pypandoc

Attempting to install without the pypandoc module installed results in the error:

FileNotFoundError: [Errno 2] No such file or directory: 'README.md'
warning: pypandoc module not found, could not convert Markdown to RST

Simplify import statement for NLC

change

from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier

to

from watson_developer_cloud import NaturalLanguageClassifierV1

to reduce text clutter in API reference

JSON from get_dialog in Dialog API throws an exception when trying to import back into the dialog

So I faced this issue according to the last comment on #31. I got around it by removing accept_json parameter from the request and extracting raw content from the request object.

def get_dialog(dialog_id, accept='application/wds+json'):
        #accept_json = False
        headers = {'accept' : accept}
        auth = HTTPBasicAuth(config.username, config.password)
        return request(method='GET', url='https://gateway.watsonplatform.net/dialog/api/v1/dialogs/{0}'.format(dialog_id), auth=auth, headers=headers).content

I can submit a pull request if you approve these changes.

Use multiple exception classes

When catching exceptions, users probably want to see the exception type and write code to handle it.

Example:

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

Include optional parameters in AlchemyVision examples

There are a couple optional parameters to some AlchemyVision APIs that would be nice to include in the examples. There's knowledgeGraph=(0|1) for GetRankedImageFaceTags and GetRankedImageKeywords, and forceShowAll=(0|1) for GetRankedImageKeywords.

Add Sample Output to Examples in Comments

Hello,
I was walking through the examples today (i.e. https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/relationship_extraction_v1_beta.py ) and noticed that they don't give a lot of insight into what's going on in the example, since it's just an import/invoke.

Since all of these scripts require login credentials I think it'd be a nice addition if the output from the print statements at the end of the script could be followed by comments showing what the output would be. For example:

print(["Hi!" for i in range(0, 3)])
"""
['Hi!', 'Hi!', 'Hi!']
"""

Version parameter not included in Document Conversion Service

The current version of the python-sdk doesn't add the required version parameter to the URL:
https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2016-02-10

The Exception being thrown looks like the following:

Traceback (most recent call last):
File "document_conversion_v1.py", line 12, in
print(json.dumps(document_conversion.convert_document(document=document, config=config), indent=2))
File "/usr/local/lib/python2.7/dist-packages/watson_developer_cloud/document_conversion_v1.py", line 36, in convert_document
return self.request(method='POST', url='/v1/convert_document', files=files, accept_json=True)
File "/usr/local/lib/python2.7/dist-packages/watson_developer_cloud/watson_developer_cloud_service.py", line 250, in request
raise WatsonException('Error: ' + error_message + ', Code: ' + str(response.status_code))
watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: You must include a version parameter., Code: 400

Document conversion issues with non JSON (ANSWER UNITS) response

If I try with a MWE with a conversion to NORMALIZED_TEXT or NORMALIZED_HTML,

with open('sample.pdf', 'rb') as document:
    watson_config = {'conversion_target': DocumentConversionV1.NORMALIZED_TEXT}
    print(json.dumps(document_conversion.convert_document(document=document, config=watson_config)))

watson_developer_cloud_service.py (line 233):

response_json = response.json()

throws an errorJSONDecodeError: Expecting value: line 1 column 1 (char 0), i.e. the response doesn't conform to JSON, as it's either text or HTML, therefore I believe it should be contemplated, as I think is the original intention of return response in line 243.

Instantiating ToneAnalyzerV3Beta should have default version value

The example code suggests you can instantiate a tone analyzer by passing in just 2 arguments, as follows:

ta = ToneAnalyzerV3Beta(username='yourusername',password='yourpassword')

However, this is not right -- you have to pass in a version argument as well, thusly:

tone_analyzer = ToneAnalyzerV3Beta(version='2016-02-11', username='yourusername', password='yourpassword')

Since it doesnt seem obvious what the right version argument should be, maybe this should default to ToneAnalyzerV3Beta.latest_version?

Language Translation missing methods

The Python SDK is missing methods for the following Language Translation methods:
List identifiable languages
GET /v2/identifiable_languages

Create model
POST /v2/models

Delete model
DELETE /v2/models/{model_id}

Get model details
GET /v2/models/{model_id}

WatsonException should show description text

I have the maximum number of NLC classifiers. When I try to allocate another one using a CURL call I see the following error

{
  "code" : 400,
  "error" : "Entitlement error",
  "description" : "This user or service instance has the maximum number of classifiers."
}

If I do the same thing with the watson_developer_cloud Python sdk, the following exception is displayed.

WatsonException: Error: Entitlement error, Code: 400

It would be really helpful if the Python sdk also displayed the description text, since offhand I don't know what an "Entitlement error" is.

It looks like this information has to be fished out of the response local variable in WatsonDeveloperCloudService.request in watson_developer_cloud_service.py.

WatsonException drops description

The WatsonException doesn't return the description property from the service error message. For example, with not enough training data in the Natural Language Classifier, this is returned:

raise WatsonException('Error: ' + error_message + ', Code: ' + str(response.status_code))
watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: Data too small, Code: 400
  • The description is missing from this.
  • Also might want to put the message, code, and description on separate lines
  • Also, to match service, labels should be lower case. For example,
{
   "description": "No training data is specified. The form field 'training_data' should contain the training CSV and 'training_metadata' should contain a JSON metadata string.",
   "error": "Missing training data",
   "code": 400
}

Can't import alchemy-related classes from sdk

After using 'pip install --upgrade watson-developer-cloud' in my virtualenv

from watson_developer_cloud import AlchemyLanguageV1

results in 'ImportError: cannot import name 'AlchemyLanguageV1'

but

from watson_developer_cloud import SpeechToTextV1 

works fine.

This is the case for both python 2.7 and python 3.5.

AlchemyNewsDataV1 does not support pagination

Will currently throw the following error if you try to add the "next" query parameter to retrieve the next page.

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/watson_developer_cloud/alchemy_data_news_v1.py", line 39, in get_news_documents
    return self._alchemy_html_request(method_url='/data/GetNews', method='GET', params=params)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/watson_developer_cloud/watson_developer_cloud_service.py", line 177, in _alchemy_html_request
    accept_json=True)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/watson_developer_cloud/watson_developer_cloud_service.py", line 245, in request
    raise WatsonException('Error: ' + error_message)
WatsonException: Error: Invalid field = 'next'

I've identified the bug in the code and will place a PR soon. Adding this issue for documentation/tracking purposes.

Dict comprehension incompatible with python 2.6

Import statement results in the following exception:

Traceback (most recent call last): File "/home/chakravr/workspaces/bluegoat-experimental/bluegoat-raas-experimental/chakravr-experiments/src/main/scripts/bluemix_scripts/run_raas_csf_experiment.py", line 15, in <module> from watson_developer_cloud import RetrieveAndRankV1, WatsonException File "/usr/lib/python2.6/site-packages/watson_developer_cloud/__init__.py", line 15, in <module> from .watson_developer_cloud_service import WatsonDeveloperCloudService File "/usr/lib/python2.6/site-packages/watson_developer_cloud/watson_developer_cloud_service.py", line 52 return {k: v for k, v in dictionary.items() if v is not None} ^ SyntaxError: invalid syntax

Syntax appears to be incompatible with python 2.6: http://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python. Works fine with python 2.7

Add Get Dialog File Call in the Dialog API

The Dialog API Supports the call to Download the Dialog File(GET /v1/dialogs/{dialog_id}). Not Sure if this call was not available earlier.

I am talking about the Number 6 in here. I can have this assigned to myself if you guys dont mind!

Add missing services

The first release came with just a few services. We need to add the rest of them.

  • AlchemyVision
  • AlchemyLanguage
  • AlchemyDataNews
  • Retrieve and Rank
  • Document Conversion
  • Concept Insights

Switch Speech to Text to use WebSockets

HI @daniel-bolanos I was thinking we can provide support for WebSockets in the sdk by adding an existing library and handling the authorization using the authorization service.
What do you think?

We should:

  • Find a websocket library
  • Design a listener/observer pattern to model websockets

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.