diff --git a/.bumpversion.cfg b/.bumpversion.cfg index b6567fb01..a12707dfe 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.2.1 +current_version = 4.3.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/.env.enc b/.env.enc index 2ce119a83..09dbc43b4 100644 Binary files a/.env.enc and b/.env.enc differ diff --git a/CHANGELOG.md b/CHANGELOG.md index 05e771fee..a5dd5bb13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,21 @@ +# [4.3.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.2.1...v4.3.0) (2020-02-13) + + +### Features + +* **assistantv1:** New param `include_audi` in `create_synonym` and `update_synonym` and `update_dialog_node ` ([fbe1081](https://github.com/watson-developer-cloud/python-sdk/commit/fbe1081309aaa380d47b3c9016aaedc0a7bb5005)) +* **assistantv1:** New param `include_audit` in `create_example`, `update_example`, `create_counterexample`, `update_counterexample`, `create_entity` ([b1f99ec](https://github.com/watson-developer-cloud/python-sdk/commit/b1f99ec1e4fad3655ff526cab7de5f18e29607a0)) +* **assistantv1:** New param `include_audit` in `create_intent` ([d523706](https://github.com/watson-developer-cloud/python-sdk/commit/d52370646cd9d5aa88bfd67da294dfd5f8ba9800)) +* **assistantv1:** New param `include_audit` in `create_value` ([4d32257](https://github.com/watson-developer-cloud/python-sdk/commit/4d32257464bd87886934c00f5a4e569896a4ac32)) +* **assistantv1:** New param `include_audit` in `create_workspace` and `update_workspace` ([e44cb16](https://github.com/watson-developer-cloud/python-sdk/commit/e44cb16771620f0cbc6f6c03e215c088c5a1beb6)) +* **assistantv1:** New params `append` and `include_audit` in `update_intent` ([3b015f9](https://github.com/watson-developer-cloud/python-sdk/commit/3b015f9b660241c2ab6f6b7f371843edf2c12c59)) +* **assistantv1:** New params `audit` and `include_audit` in `update_value` ([8bac230](https://github.com/watson-developer-cloud/python-sdk/commit/8bac230a824d996f7807f943650c737ca3ae553d)) +* **assistantv1:** New params `include_audit` and `append` in `update_entity` ([e36783d](https://github.com/watson-developer-cloud/python-sdk/commit/e36783d015e7681b626a1cc8c99ee68a9cbf614f)) +* **assistantv1:** New params `interpretation` and `role` in `RuntimeEntity` model ([a44ace8](https://github.com/watson-developer-cloud/python-sdk/commit/a44ace8638db57f17d319932863aa5c5af51dd93)) +* **assistantv2:** `interpretation`, `alternatives` and `role` properties in `RuntimeEntity` ([5ef087f](https://github.com/watson-developer-cloud/python-sdk/commit/5ef087f4b27b0771e098aaec8488e42d94ecd1ce)) +* **assistantv2:** New params `locale` and `reference_time` in `MessageContextGlobalSystem` ([9b7e56e](https://github.com/watson-developer-cloud/python-sdk/commit/9b7e56e85d9fdec8b264c1a2865882c031046998)) +* **vr4:** New objects operations ([cc9eace](https://github.com/watson-developer-cloud/python-sdk/commit/cc9eaced7ac1e693392e0ea2e6eb2ed27c63af9a)) + ## [4.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.2.0...v4.2.1) (2020-01-17) diff --git a/README.md b/README.md index 20c1ecbc3..16b4120fc 100755 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Setting the service url](#setting-the-service-url) * [Sending request headers](#sending-request-headers) * [Parsing HTTP response information](#parsing-http-response-information) + * [Getting the transaction ID](#getting-the-transaction-id) * [Using Websockets](#using-websockets) * [Cloud Pak for Data(CP4D)](#cloud-pak-for-data) * [Logging](#logging) @@ -362,6 +363,30 @@ This would give an output of `DetailedResponse` having the structure: ``` 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. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance. +### Suceess +```python +from ibm_watson import MyService + +service = MyService(authenticator=my_authenticator) +response_headers = service.my_service_call().get_headers() +print(response_headers.get('x-global-transaction-id')) +``` + +### Failure +```python +from ibm_watson import MyService, ApiException + +try: + service = MyService(authenticator=my_authenticators) + service.my_service_call() +except ApiException as e: + print(e.global_transaction_id) + # OR + print(e.http_response.headers.get('x-global-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. diff --git a/examples/__init__.py b/examples/__init__.py index f5b8b65a1..e38a9fff7 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2015, 2016. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/examples/assistant_tone_analyzer_integration/__init__.py b/examples/assistant_tone_analyzer_integration/__init__.py index 4cdaa2645..6183fadf7 100644 --- a/examples/assistant_tone_analyzer_integration/__init__.py +++ b/examples/assistant_tone_analyzer_integration/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2016, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/examples/assistant_tone_analyzer_integration/tone_detection.py b/examples/assistant_tone_analyzer_integration/tone_detection.py index d7b331e6e..dc8e36a01 100644 --- a/examples/assistant_tone_analyzer_integration/tone_detection.py +++ b/examples/assistant_tone_analyzer_integration/tone_detection.py @@ -1,4 +1,4 @@ -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2016, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index 2ba587d79..b2951465a 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -3,12 +3,13 @@ ../resources/personality-v3-expect2.txt """ import json -from os.path import join, dirname +import os +from os.path import join from ibm_watson import PersonalityInsightsV3 import csv from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# Authentication via IAM +# # Authentication via IAM # authenticator = IAMAuthenticator('your_api_key') # service = PersonalityInsightsV3( # version='2017-10-13', @@ -17,7 +18,7 @@ # Authentication via external config like VCAP_SERVICES service = PersonalityInsightsV3(version='2017-10-13') -service.set_service_url('https://gateway.watsonplatform.net/personality-insights/api') +service.set_service_url('https://api.us-east.personality-insights.watson.cloud.ibm.com/instances/4c18b521-3abd-4c7c-bec7-6a3fd03644f1') ############################ # Profile with JSON output # diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index bb690deee..66c76aa03 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -37,6 +37,13 @@ ]).get_result() print(json.dumps(training_data, indent=2)) +# update object metadata +updated_object_metadata = service.update_object_metadata( + collection_id=collection_id, + object='giraffe training data', + new_object='updated giraffe training data').get_result() +print(json.dumps(updated_object_metadata, indent=2)) + # train collection train_result = service.train(collection_id).get_result() print(json.dumps(train_result, indent=2)) diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 4f8afd62c..ae48a10b0 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -1,5 +1,5 @@ # coding: utf-8 -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2016, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 42a0b126c..2020c9bfe 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -27,8 +27,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -98,7 +99,7 @@ def message(self, **Important:** This method has been superseded by the new v2 runtime API. The v2 API offers significant advantages, including ease of deployment, automatic state management, versioning, and search capabilities. For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-api-overview). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-api-overview). There is no rate limit for this operation. :param str workspace_id: Unique identifier of the workspace. @@ -243,6 +244,7 @@ def create_workspace(self, dialog_nodes: List['DialogNode'] = None, counterexamples: List['Counterexample'] = None, webhooks: List['Webhook'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create workspace. @@ -273,6 +275,8 @@ def create_workspace(self, :param List[Counterexample] counterexamples: (optional) An array of objects defining input examples that have been marked as irrelevant input. :param List[Webhook] webhooks: (optional) + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -299,7 +303,7 @@ def create_workspace(self, operation_id='create_workspace') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'name': name, @@ -398,6 +402,7 @@ def update_workspace(self, counterexamples: List['Counterexample'] = None, webhooks: List['Webhook'] = None, append: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update workspace. @@ -430,14 +435,16 @@ def update_workspace(self, defining input examples that have been marked as irrelevant input. :param List[Webhook] webhooks: (optional) :param bool append: (optional) Whether the new data is to be appended to - the existing data in the workspace. If **append**=`false`, elements - included in the new data completely replace the corresponding existing - elements, including all subelements. For example, if the new data includes - **entities** and **append**=`false`, all existing entities in the workspace - are discarded and replaced with the new entities. + the existing data in the object. If **append**=`false`, elements included + in the new data completely replace the corresponding existing elements, + including all subelements. For example, if the new data for a workspace + includes **entities** and **append**=`false`, all existing entities in the + workspace are discarded and replaced with the new entities. If **append**=`true`, existing elements are preserved, and the new elements are added. If any elements in the new data collide with existing elements, the update request fails. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -466,7 +473,11 @@ def update_workspace(self, operation_id='update_workspace') headers.update(sdk_headers) - params = {'version': self.version, 'append': append} + params = { + 'version': self.version, + 'append': append, + 'include_audit': include_audit + } data = { 'name': name, @@ -605,6 +616,7 @@ def create_intent(self, *, description: str = None, examples: List['Example'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create intent. @@ -625,6 +637,8 @@ def create_intent(self, string cannot contain carriage return, newline, or tab characters. :param List[Example] examples: (optional) An array of user input examples for the intent. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -645,7 +659,7 @@ def create_intent(self, operation_id='create_intent') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'intent': intent, @@ -728,6 +742,8 @@ def update_intent(self, new_intent: str = None, new_description: str = None, new_examples: List['Example'] = None, + append: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update intent. @@ -750,6 +766,17 @@ def update_intent(self, string cannot contain carriage return, newline, or tab characters. :param List[Example] new_examples: (optional) An array of user input examples for the intent. + :param bool append: (optional) Whether the new data is to be appended to + the existing data in the object. If **append**=`false`, elements included + in the new data completely replace the corresponding existing elements, + including all subelements. For example, if the new data for the intent + includes **examples** and **append**=`false`, all existing examples for the + intent are discarded and replaced with the new examples. + If **append**=`true`, existing elements are preserved, and the new elements + are added. If any elements in the new data collide with existing elements, + the update request fails. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -770,7 +797,11 @@ def update_intent(self, operation_id='update_intent') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'append': append, + 'include_audit': include_audit + } data = { 'intent': new_intent, @@ -904,6 +935,7 @@ def create_example(self, text: str, *, mentions: List['Mention'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create user input example. @@ -922,6 +954,8 @@ def create_example(self, - It cannot consist of only whitespace characters. :param List[Mention] mentions: (optional) An array of contextual entity mentions. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -944,7 +978,7 @@ def create_example(self, operation_id='create_example') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'text': text, 'mentions': mentions} @@ -1017,6 +1051,7 @@ def update_example(self, *, new_text: str = None, new_mentions: List['Mention'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update user input example. @@ -1036,6 +1071,8 @@ def update_example(self, - It cannot consist of only whitespace characters. :param List[Mention] new_mentions: (optional) An array of contextual entity mentions. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1058,7 +1095,7 @@ def update_example(self, operation_id='update_example') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'text': new_text, 'mentions': new_mentions} @@ -1181,7 +1218,11 @@ def list_counterexamples(self, response = self.send(request) return response - def create_counterexample(self, workspace_id: str, text: str, + def create_counterexample(self, + workspace_id: str, + text: str, + *, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create counterexample. @@ -1198,6 +1239,8 @@ def create_counterexample(self, workspace_id: str, text: str, string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1216,7 +1259,7 @@ def create_counterexample(self, workspace_id: str, text: str, operation_id='create_counterexample') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'text': text} @@ -1285,6 +1328,7 @@ def update_counterexample(self, text: str, *, new_text: str = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update counterexample. @@ -1303,6 +1347,8 @@ def update_counterexample(self, irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1321,7 +1367,7 @@ def update_counterexample(self, operation_id='update_counterexample') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'text': new_text} @@ -1457,6 +1503,7 @@ def create_entity(self, metadata: dict = None, fuzzy_match: bool = None, values: List['CreateValue'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create entity. @@ -1482,6 +1529,8 @@ def create_entity(self, entity. :param List[CreateValue] values: (optional) An array of objects describing the entity values. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1502,7 +1551,7 @@ def create_entity(self, operation_id='create_entity') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'entity': entity, @@ -1589,6 +1638,8 @@ def update_entity(self, new_metadata: dict = None, new_fuzzy_match: bool = None, new_values: List['CreateValue'] = None, + append: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update entity. @@ -1614,6 +1665,17 @@ def update_entity(self, the entity. :param List[CreateValue] new_values: (optional) An array of objects describing the entity values. + :param bool append: (optional) Whether the new data is to be appended to + the existing data in the entity. If **append**=`false`, elements included + in the new data completely replace the corresponding existing elements, + including all subelements. For example, if the new data for the entity + includes **values** and **append**=`false`, all existing values for the + entity are discarded and replaced with the new values. + If **append**=`true`, existing elements are preserved, and the new elements + are added. If any elements in the new data collide with existing elements, + the update request fails. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1634,7 +1696,11 @@ def update_entity(self, operation_id='update_entity') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'append': append, + 'include_audit': include_audit + } data = { 'entity': new_entity, @@ -1839,6 +1905,7 @@ def create_value(self, type: str = None, synonyms: List[str] = None, patterns: List[str] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create entity value. @@ -1867,7 +1934,9 @@ def create_value(self, value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1888,7 +1957,7 @@ def create_value(self, operation_id='create_value') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'value': value, @@ -1979,6 +2048,8 @@ def update_value(self, new_type: str = None, new_synonyms: List[str] = None, new_patterns: List[str] = None, + append: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update entity value. @@ -2010,7 +2081,19 @@ def update_value(self, entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). + :param bool append: (optional) Whether the new data is to be appended to + the existing data in the entity value. If **append**=`false`, elements + included in the new data completely replace the corresponding existing + elements, including all subelements. For example, if the new data for the + entity value includes **synonyms** and **append**=`false`, all existing + synonyms for the entity value are discarded and replaced with the new + synonyms. + If **append**=`true`, existing elements are preserved, and the new elements + are added. If any elements in the new data collide with existing elements, + the update request fails. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2031,7 +2114,11 @@ def update_value(self, operation_id='update_value') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'append': append, + 'include_audit': include_audit + } data = { 'value': new_value, @@ -2167,8 +2254,14 @@ def list_synonyms(self, response = self.send(request) return response - def create_synonym(self, workspace_id: str, entity: str, value: str, - synonym: str, **kwargs) -> 'DetailedResponse': + def create_synonym(self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Create entity value synonym. @@ -2186,6 +2279,8 @@ def create_synonym(self, workspace_id: str, entity: str, value: str, the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2208,7 +2303,7 @@ def create_synonym(self, workspace_id: str, entity: str, value: str, operation_id='create_synonym') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'synonym': synonym} @@ -2285,6 +2380,7 @@ def update_synonym(self, synonym: str, *, new_synonym: str = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update entity value synonym. @@ -2304,6 +2400,8 @@ def update_synonym(self, must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2326,7 +2424,7 @@ def update_synonym(self, operation_id='update_synonym') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = {'synonym': new_synonym} @@ -2473,6 +2571,7 @@ def create_dialog_node(self, digress_out_slots: str = None, user_label: str = None, disambiguation_opt_out: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create dialog node. @@ -2500,7 +2599,7 @@ def create_dialog_node(self, sibling. :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). :param dict context: (optional) The context for the dialog node. :param dict metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute @@ -2525,6 +2624,8 @@ def create_dialog_node(self, to describe the purpose of the node to users. :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2549,7 +2650,7 @@ def create_dialog_node(self, operation_id='create_dialog_node') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'dialog_node': dialog_node, @@ -2654,6 +2755,7 @@ def update_dialog_node(self, new_digress_out_slots: str = None, new_user_label: str = None, new_disambiguation_opt_out: bool = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update dialog node. @@ -2682,7 +2784,7 @@ def update_dialog_node(self, sibling. :param DialogNodeOutput new_output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). :param dict new_context: (optional) The context for the dialog node. :param dict new_metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep new_next_step: (optional) The next step to @@ -2708,6 +2810,8 @@ def update_dialog_node(self, externally to describe the purpose of the node to users. :param bool new_disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2732,7 +2836,7 @@ def update_dialog_node(self, operation_id='update_dialog_node') headers.update(sdk_headers) - params = {'version': self.version} + params = {'version': self.version, 'include_audit': include_audit} data = { 'dialog_node': new_dialog_node, @@ -2834,7 +2938,7 @@ def list_logs(self, parameter value with a minus sign (`-`). :param str filter: (optional) A cacheable parameter that limits the results to those matching the specified filter. For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-filter-reference#filter-reference). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param int page_limit: (optional) The number of records to return in each page of results. :param str cursor: (optional) A token identifying the page of results to @@ -2893,7 +2997,7 @@ def list_all_logs(self, includes a value for `language`, as well as a value for `request.context.system.assistant_id`, `workspace_id`, or `request.context.metadata.deployment`. For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-filter-reference#filter-reference). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param str sort: (optional) How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). @@ -2948,7 +3052,7 @@ def delete_user_data(self, customer_id: str, You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information - security](https://cloud.ibm.com/docs/services/assistant?topic=assistant-information-security#information-security). + security](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security). This operation is limited to 4 requests per minute. For more information, see **Rate limiting**. @@ -3702,7 +3806,7 @@ class CreateValue(): A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to the object. @@ -3736,7 +3840,7 @@ def __init__(self, value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). :param datetime created: (optional) The timestamp for creation of the object. :param datetime updated: (optional) The timestamp for the most recent @@ -3850,7 +3954,7 @@ class DialogNode(): node. This property is omitted if the dialog node has no previous sibling. :attr DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). :attr dict context: (optional) The context for the dialog node. :attr dict metadata: (optional) The metadata for the dialog node. :attr DialogNodeNextStep next_step: (optional) The next step to execute @@ -3924,7 +4028,7 @@ def __init__(self, sibling. :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). :param dict context: (optional) The context for the dialog node. :param dict metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute @@ -4542,7 +4646,7 @@ class DialogNodeOutput(): """ The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. @@ -7811,6 +7915,16 @@ class RuntimeEntity(): :attr dict metadata: (optional) Any metadata for the entity. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. + :attr RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user input. + This property is included only if the new system entities are enabled for the + workspace. + For more information about how the new system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :attr RuntimeEntityRole role: (optional) An object describing the role played by + a system entity that is specifies the beginning or end of a range recognized in + the user input. This property is included only if the new system entities are + enabled for the workspace. """ def __init__(self, @@ -7820,7 +7934,9 @@ def __init__(self, *, confidence: float = None, metadata: dict = None, - groups: List['CaptureGroup'] = None) -> None: + groups: List['CaptureGroup'] = None, + interpretation: 'RuntimeEntityInterpretation' = None, + role: 'RuntimeEntityRole' = None) -> None: """ Initialize a RuntimeEntity object. @@ -7833,6 +7949,17 @@ def __init__(self, :param dict metadata: (optional) Any metadata for the entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user + input. This property is included only if the new system entities are + enabled for the workspace. + For more information about how the new system entities are interpreted, see + the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param RuntimeEntityRole role: (optional) An object describing the role + played by a system entity that is specifies the beginning or end of a range + recognized in the user input. This property is included only if the new + system entities are enabled for the workspace. """ self.entity = entity self.location = location @@ -7840,13 +7967,16 @@ def __init__(self, self.confidence = confidence self.metadata = metadata self.groups = groups + self.interpretation = interpretation + self.role = role @classmethod def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ - 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' + 'entity', 'location', 'value', 'confidence', 'metadata', 'groups', + 'interpretation', 'role' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -7878,6 +8008,11 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['groups'] = [ CaptureGroup._from_dict(x) for x in (_dict.get('groups')) ] + if 'interpretation' in _dict: + args['interpretation'] = RuntimeEntityInterpretation._from_dict( + _dict.get('interpretation')) + if 'role' in _dict: + args['role'] = RuntimeEntityRole._from_dict(_dict.get('role')) return cls(**args) @classmethod @@ -7900,6 +8035,10 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: _dict['groups'] = [x._to_dict() for x in self.groups] + if hasattr(self, 'interpretation') and self.interpretation is not None: + _dict['interpretation'] = self.interpretation._to_dict() + if hasattr(self, 'role') and self.role is not None: + _dict['role'] = self.role._to_dict() return _dict def _to_dict(self): @@ -7921,6 +8060,463 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other +class RuntimeEntityInterpretation(): + """ + RuntimeEntityInterpretation. + + :attr str calendar_type: (optional) The calendar used to represent a recognized + date (for example, `Gregorian`). + :attr str datetime_link: (optional) A unique identifier used to associate a + recognized time and date. If the user input contains a date and time that are + mentioned together (for example, `Today at 5`, the same **datetime_link** value + is returned for both the `@sys-date` and `@sys-time` entities). + :attr str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a `@sys-date` + entity is recognized based on a holiday name in the user input. + :attr str granularity: (optional) The precision or duration of a time range + specified by a recognized `@sys-time` or `@sys-date` entity. + :attr str range_link: (optional) A unique identifier used to associate multiple + recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are + recognized as a range of values in the user's input (for example, `from July 4 + until July 14` or `from 20 to 25`). + :attr str range_modifier: (optional) The word in the user input that indicates + that a `sys-date` or `sys-time` entity is part of an implied range where only + one date or time is specified (for example, `since` or `until`). + :attr float relative_day: (optional) A recognized mention of a relative day, + represented numerically as an offset from the current date (for example, `-1` + for `yesterday` or `10` for `in ten days`). + :attr float relative_month: (optional) A recognized mention of a relative month, + represented numerically as an offset from the current month (for example, `1` + for `next month` or `-3` for `three months ago`). + :attr float relative_week: (optional) A recognized mention of a relative week, + represented numerically as an offset from the current week (for example, `2` for + `in two weeks` or `-1` for `last week). + :attr float relative_weekend: (optional) A recognized mention of a relative date + range for a weekend, represented numerically as an offset from the current + weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). + :attr float relative_year: (optional) A recognized mention of a relative year, + represented numerically as an offset from the current year (for example, `1` for + `next year` or `-5` for `five years ago`). + :attr float specific_day: (optional) A recognized mention of a specific date, + represented numerically as the date within the month (for example, `30` for + `June 30`.). + :attr str specific_day_of_week: (optional) A recognized mention of a specific + day of the week as a lowercase string (for example, `monday`). + :attr float specific_month: (optional) A recognized mention of a specific month, + represented numerically (for example, `7` for `July`). + :attr float specific_quarter: (optional) A recognized mention of a specific + quarter, represented numerically (for example, `3` for `the third quarter`). + :attr float specific_year: (optional) A recognized mention of a specific year + (for example, `2016`). + :attr float numeric_value: (optional) A recognized numeric value, represented as + an integer or double. + :attr str subtype: (optional) The type of numeric value recognized in the user + input (`integer` or `rational`). + :attr str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` or + `afternoon`). + :attr float relative_hour: (optional) A recognized mention of a relative hour, + represented numerically as an offset from the current hour (for example, `3` for + `in three hours` or `-1` for `an hour ago`). + :attr float relative_minute: (optional) A recognized mention of a relative time, + represented numerically as an offset in minutes from the current time (for + example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). + :attr float relative_second: (optional) A recognized mention of a relative time, + represented numerically as an offset in seconds from the current time (for + example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :attr float specific_hour: (optional) A recognized specific hour mentioned as + part of a time value (for example, `10` for `10:15 AM`.). + :attr float specific_minute: (optional) A recognized specific minute mentioned + as part of a time value (for example, `15` for `10:15 AM`.). + :attr float specific_second: (optional) A recognized specific second mentioned + as part of a time value (for example, `30` for `10:15:30 AM`.). + :attr str timezone: (optional) A recognized time zone mentioned as part of a + time value (for example, `EST`). + """ + + def __init__(self, + *, + calendar_type: str = None, + datetime_link: str = None, + festival: str = None, + granularity: str = None, + range_link: str = None, + range_modifier: str = None, + relative_day: float = None, + relative_month: float = None, + relative_week: float = None, + relative_weekend: float = None, + relative_year: float = None, + specific_day: float = None, + specific_day_of_week: str = None, + specific_month: float = None, + specific_quarter: float = None, + specific_year: float = None, + numeric_value: float = None, + subtype: str = None, + part_of_day: str = None, + relative_hour: float = None, + relative_minute: float = None, + relative_second: float = None, + specific_hour: float = None, + specific_minute: float = None, + specific_second: float = None, + timezone: str = None) -> None: + """ + Initialize a RuntimeEntityInterpretation object. + + :param str calendar_type: (optional) The calendar used to represent a + recognized date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate + a recognized time and date. If the user input contains a date and time that + are mentioned together (for example, `Today at 5`, the same + **datetime_link** value is returned for both the `@sys-date` and + `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a + `@sys-date` entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time + range specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate + multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities + that are recognized as a range of values in the user's input (for example, + `from July 4 until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that + indicates that a `sys-date` or `sys-time` entity is part of an implied + range where only one date or time is specified (for example, `since` or + `until`). + :param float relative_day: (optional) A recognized mention of a relative + day, represented numerically as an offset from the current date (for + example, `-1` for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for + example, `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative + week, represented numerically as an offset from the current week (for + example, `2` for `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a + relative date range for a weekend, represented numerically as an offset + from the current weekend (for example, `0` for `this weekend` or `-1` for + `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative + year, represented numerically as an offset from the current year (for + example, `1` for `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific + date, represented numerically as the date within the month (for example, + `30` for `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a + specific day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a + specific quarter, represented numerically (for example, `3` for `the third + quarter`). + :param float specific_year: (optional) A recognized mention of a specific + year (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, + represented as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the + user input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` + or `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative + hour, represented numerically as an offset from the current hour (for + example, `3` for `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time + (for example, `5` for `in five minutes` or `-15` for `fifteen minutes + ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time + (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned + as part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute + mentioned as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second + mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of + a time value (for example, `EST`). + """ + self.calendar_type = calendar_type + self.datetime_link = datetime_link + self.festival = festival + self.granularity = granularity + self.range_link = range_link + self.range_modifier = range_modifier + self.relative_day = relative_day + self.relative_month = relative_month + self.relative_week = relative_week + self.relative_weekend = relative_weekend + self.relative_year = relative_year + self.specific_day = specific_day + self.specific_day_of_week = specific_day_of_week + self.specific_month = specific_month + self.specific_quarter = specific_quarter + self.specific_year = specific_year + self.numeric_value = numeric_value + self.subtype = subtype + self.part_of_day = part_of_day + self.relative_hour = relative_hour + self.relative_minute = relative_minute + self.relative_second = relative_second + self.specific_hour = specific_hour + self.specific_minute = specific_minute + self.specific_second = specific_second + self.timezone = timezone + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + valid_keys = [ + 'calendar_type', 'datetime_link', 'festival', 'granularity', + 'range_link', 'range_modifier', 'relative_day', 'relative_month', + 'relative_week', 'relative_weekend', 'relative_year', + 'specific_day', 'specific_day_of_week', 'specific_month', + 'specific_quarter', 'specific_year', 'numeric_value', 'subtype', + 'part_of_day', 'relative_hour', 'relative_minute', + 'relative_second', 'specific_hour', 'specific_minute', + 'specific_second', 'timezone' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntityInterpretation: ' + + ', '.join(bad_keys)) + if 'calendar_type' in _dict: + args['calendar_type'] = _dict.get('calendar_type') + if 'datetime_link' in _dict: + args['datetime_link'] = _dict.get('datetime_link') + if 'festival' in _dict: + args['festival'] = _dict.get('festival') + if 'granularity' in _dict: + args['granularity'] = _dict.get('granularity') + if 'range_link' in _dict: + args['range_link'] = _dict.get('range_link') + if 'range_modifier' in _dict: + args['range_modifier'] = _dict.get('range_modifier') + if 'relative_day' in _dict: + args['relative_day'] = _dict.get('relative_day') + if 'relative_month' in _dict: + args['relative_month'] = _dict.get('relative_month') + if 'relative_week' in _dict: + args['relative_week'] = _dict.get('relative_week') + if 'relative_weekend' in _dict: + args['relative_weekend'] = _dict.get('relative_weekend') + if 'relative_year' in _dict: + args['relative_year'] = _dict.get('relative_year') + if 'specific_day' in _dict: + args['specific_day'] = _dict.get('specific_day') + if 'specific_day_of_week' in _dict: + args['specific_day_of_week'] = _dict.get('specific_day_of_week') + if 'specific_month' in _dict: + args['specific_month'] = _dict.get('specific_month') + if 'specific_quarter' in _dict: + args['specific_quarter'] = _dict.get('specific_quarter') + if 'specific_year' in _dict: + args['specific_year'] = _dict.get('specific_year') + if 'numeric_value' in _dict: + args['numeric_value'] = _dict.get('numeric_value') + if 'subtype' in _dict: + args['subtype'] = _dict.get('subtype') + if 'part_of_day' in _dict: + args['part_of_day'] = _dict.get('part_of_day') + if 'relative_hour' in _dict: + args['relative_hour'] = _dict.get('relative_hour') + if 'relative_minute' in _dict: + args['relative_minute'] = _dict.get('relative_minute') + if 'relative_second' in _dict: + args['relative_second'] = _dict.get('relative_second') + if 'specific_hour' in _dict: + args['specific_hour'] = _dict.get('specific_hour') + if 'specific_minute' in _dict: + args['specific_minute'] = _dict.get('specific_minute') + if 'specific_second' in _dict: + args['specific_second'] = _dict.get('specific_second') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'calendar_type') and self.calendar_type is not None: + _dict['calendar_type'] = self.calendar_type + if hasattr(self, 'datetime_link') and self.datetime_link is not None: + _dict['datetime_link'] = self.datetime_link + if hasattr(self, 'festival') and self.festival is not None: + _dict['festival'] = self.festival + if hasattr(self, 'granularity') and self.granularity is not None: + _dict['granularity'] = self.granularity + if hasattr(self, 'range_link') and self.range_link is not None: + _dict['range_link'] = self.range_link + if hasattr(self, 'range_modifier') and self.range_modifier is not None: + _dict['range_modifier'] = self.range_modifier + if hasattr(self, 'relative_day') and self.relative_day is not None: + _dict['relative_day'] = self.relative_day + if hasattr(self, 'relative_month') and self.relative_month is not None: + _dict['relative_month'] = self.relative_month + if hasattr(self, 'relative_week') and self.relative_week is not None: + _dict['relative_week'] = self.relative_week + if hasattr(self, + 'relative_weekend') and self.relative_weekend is not None: + _dict['relative_weekend'] = self.relative_weekend + if hasattr(self, 'relative_year') and self.relative_year is not None: + _dict['relative_year'] = self.relative_year + if hasattr(self, 'specific_day') and self.specific_day is not None: + _dict['specific_day'] = self.specific_day + if hasattr(self, 'specific_day_of_week' + ) and self.specific_day_of_week is not None: + _dict['specific_day_of_week'] = self.specific_day_of_week + if hasattr(self, 'specific_month') and self.specific_month is not None: + _dict['specific_month'] = self.specific_month + if hasattr(self, + 'specific_quarter') and self.specific_quarter is not None: + _dict['specific_quarter'] = self.specific_quarter + if hasattr(self, 'specific_year') and self.specific_year is not None: + _dict['specific_year'] = self.specific_year + if hasattr(self, 'numeric_value') and self.numeric_value is not None: + _dict['numeric_value'] = self.numeric_value + if hasattr(self, 'subtype') and self.subtype is not None: + _dict['subtype'] = self.subtype + if hasattr(self, 'part_of_day') and self.part_of_day is not None: + _dict['part_of_day'] = self.part_of_day + if hasattr(self, 'relative_hour') and self.relative_hour is not None: + _dict['relative_hour'] = self.relative_hour + if hasattr(self, + 'relative_minute') and self.relative_minute is not None: + _dict['relative_minute'] = self.relative_minute + if hasattr(self, + 'relative_second') and self.relative_second is not None: + _dict['relative_second'] = self.relative_second + if hasattr(self, 'specific_hour') and self.specific_hour is not None: + _dict['specific_hour'] = self.specific_hour + if hasattr(self, + 'specific_minute') and self.specific_minute is not None: + _dict['specific_minute'] = self.specific_minute + if hasattr(self, + 'specific_second') and self.specific_second is not None: + _dict['specific_second'] = self.specific_second + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityInterpretation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class GranularityEnum(Enum): + """ + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. + """ + DAY = "day" + FORTNIGHT = "fortnight" + HOUR = "hour" + INSTANT = "instant" + MINUTE = "minute" + MONTH = "month" + QUARTER = "quarter" + SECOND = "second" + WEEK = "week" + WEEKEND = "weekend" + YEAR = "year" + + +class RuntimeEntityRole(): + """ + An object describing the role played by a system entity that is specifies the + beginning or end of a range recognized in the user input. This property is included + only if the new system entities are enabled for the workspace. + + :attr str type: (optional) The relationship of the entity to the range. + """ + + def __init__(self, *, type: str = None) -> None: + """ + Initialize a RuntimeEntityRole object. + + :param str type: (optional) The relationship of the entity to the range. + """ + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" + args = {} + valid_keys = ['type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntityRole: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityRole object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityRole object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The relationship of the entity to the range. + """ + DATE_FROM = "date_from" + DATE_TO = "date_to" + NUMBER_FROM = "number_from" + NUMBER_TO = "number_to" + TIME_FROM = "time_from" + TIME_TO = "time_to" + + class RuntimeIntent(): """ An intent identified in the user input. @@ -8475,7 +9071,7 @@ class Value(): A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to the object. @@ -8509,7 +9105,7 @@ def __init__(self, value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). :param datetime created: (optional) The timestamp for creation of the object. :param datetime updated: (optional) The timestamp for the most recent @@ -9181,16 +9777,20 @@ class WorkspaceSystemSettings(): settings related to the disambiguation feature. **Note:** This feature is available only to Plus and Premium users. :attr dict human_agent_assist: (optional) For internal use only. + :attr WorkspaceSystemSettingsSystemEntities system_entities: (optional) + Workspace settings related to the behavior of system entities. :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. """ - def __init__(self, - *, - tooling: 'WorkspaceSystemSettingsTooling' = None, - disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, - human_agent_assist: dict = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: + def __init__( + self, + *, + tooling: 'WorkspaceSystemSettingsTooling' = None, + disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, + human_agent_assist: dict = None, + system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, + off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -9200,12 +9800,15 @@ def __init__(self, Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Plus and Premium users. :param dict human_agent_assist: (optional) For internal use only. + :param WorkspaceSystemSettingsSystemEntities system_entities: (optional) + Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. """ self.tooling = tooling self.disambiguation = disambiguation self.human_agent_assist = human_agent_assist + self.system_entities = system_entities self.off_topic = off_topic @classmethod @@ -9213,7 +9816,8 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} valid_keys = [ - 'tooling', 'disambiguation', 'human_agent_assist', 'off_topic' + 'tooling', 'disambiguation', 'human_agent_assist', + 'system_entities', 'off_topic' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -9229,6 +9833,10 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': _dict.get('disambiguation')) if 'human_agent_assist' in _dict: args['human_agent_assist'] = _dict.get('human_agent_assist') + if 'system_entities' in _dict: + args[ + 'system_entities'] = WorkspaceSystemSettingsSystemEntities._from_dict( + _dict.get('system_entities')) if 'off_topic' in _dict: args['off_topic'] = WorkspaceSystemSettingsOffTopic._from_dict( _dict.get('off_topic')) @@ -9250,6 +9858,9 @@ def to_dict(self) -> Dict: self, 'human_agent_assist') and self.human_agent_assist is not None: _dict['human_agent_assist'] = self.human_agent_assist + if hasattr(self, + 'system_entities') and self.system_entities is not None: + _dict['system_entities'] = self.system_entities._to_dict() if hasattr(self, 'off_topic') and self.off_topic is not None: _dict['off_topic'] = self.off_topic._to_dict() return _dict @@ -9482,6 +10093,68 @@ def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: return not self == other +class WorkspaceSystemSettingsSystemEntities(): + """ + Workspace settings related to the behavior of system entities. + + :attr bool enabled: (optional) Whether the new system entities are enabled for + the workspace. + """ + + def __init__(self, *, enabled: bool = None) -> None: + """ + Initialize a WorkspaceSystemSettingsSystemEntities object. + + :param bool enabled: (optional) Whether the new system entities are enabled + for the workspace. + """ + self.enabled = enabled + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': + """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" + args = {} + valid_keys = ['enabled'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsSystemEntities: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WorkspaceSystemSettingsSystemEntities object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class WorkspaceSystemSettingsTooling(): """ Workspace settings related to the Watson Assistant user interface. diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 11157bbac..4d95d4fa0 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -26,7 +26,8 @@ from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core import DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -86,13 +87,13 @@ def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': responses. It also maintains the state of the conversation. A session persists until it is deleted, or until it times out because of inactivity. (For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings). :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant settings and click **API Details**. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-add#assistant-add-task). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -129,13 +130,13 @@ def delete_session(self, assistant_id: str, session_id: str, Deletes a session explicitly before it times out. (For more information about the session inactivity timeout, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings)). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant settings and click **API Details**. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-add#assistant-add-task). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers @@ -189,7 +190,7 @@ def message(self, assistant ID in the Watson Assistant user interface, open the assistant settings and click **API Details**. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-add#assistant-add-task). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the @@ -1059,13 +1060,31 @@ class MessageContextGlobalSystem(): with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some skills (for example, triggering the start node of a dialog). + :attr str locale: (optional) The language code for localization in the user + input. The specified locale overrides the default for the assistant, and is used + for interpreting entity values in user input such as date values. For example, + `04/03/2018` might be interpreted either as April 3 or March 4, depending on the + locale. + This property is included only if the new system entities are enabled for the + skill. + :attr str reference_time: (optional) The base time for interpreting any relative + time mentions in the user input. The specified time overrides the current server + time, and is used to calculate times mentioned in relative terms such as `now` + or `tomorrow`. This can be useful for simulating past or future times for + testing purposes, or when analyzing documents such as news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2019-06-26T12:00:00Z` for noon on 26 June 2019. + This property is included only if the new system entities are enabled for the + skill. """ def __init__(self, *, timezone: str = None, user_id: str = None, - turn_count: int = None) -> None: + turn_count: int = None, + locale: str = None, + reference_time: str = None) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -1082,16 +1101,37 @@ def __init__(self, this is the the first turn of a new conversation, which can affect the behavior of some skills (for example, triggering the start node of a dialog). + :param str locale: (optional) The language code for localization in the + user input. The specified locale overrides the default for the assistant, + and is used for interpreting entity values in user input such as date + values. For example, `04/03/2018` might be interpreted either as April 3 or + March 4, depending on the locale. + This property is included only if the new system entities are enabled for + the skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative + terms such as `now` or `tomorrow`. This can be useful for simulating past + or future times for testing purposes, or when analyzing documents such as + news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2019-06-26T12:00:00Z` for noon on 26 June 2019. + This property is included only if the new system entities are enabled for + the skill. """ self.timezone = timezone self.user_id = user_id self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - valid_keys = ['timezone', 'user_id', 'turn_count'] + valid_keys = [ + 'timezone', 'user_id', 'turn_count', 'locale', 'reference_time' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1103,6 +1143,10 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': args['user_id'] = _dict.get('user_id') if 'turn_count' in _dict: args['turn_count'] = _dict.get('turn_count') + if 'locale' in _dict: + args['locale'] = _dict.get('locale') + if 'reference_time' in _dict: + args['reference_time'] = _dict.get('reference_time') return cls(**args) @classmethod @@ -1119,6 +1163,10 @@ def to_dict(self) -> Dict: _dict['user_id'] = self.user_id if hasattr(self, 'turn_count') and self.turn_count is not None: _dict['turn_count'] = self.turn_count + if hasattr(self, 'locale') and self.locale is not None: + _dict['locale'] = self.locale + if hasattr(self, 'reference_time') and self.reference_time is not None: + _dict['reference_time'] = self.reference_time return _dict def _to_dict(self): @@ -1139,6 +1187,31 @@ def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(Enum): + """ + The language code for localization in the user input. The specified locale + overrides the default for the assistant, and is used for interpreting entity + values in user input such as date values. For example, `04/03/2018` might be + interpreted either as April 3 or March 4, depending on the locale. + This property is included only if the new system entities are enabled for the + skill. + """ + EN_US = "en-us" + EN_CA = "en-ca" + EN_GB = "en-gb" + AR_AR = "ar-ar" + CS_CZ = "cs-cz" + DE_DE = "de-de" + ES_ES = "es-es" + FR_FR = "fr-fr" + IT_IT = "it-it" + JA_JP = "ja-jp" + KO_KR = "ko-kr" + NL_NL = "nl-nl" + PT_BR = "pt-br" + ZH_CN = "zh-cn" + ZH_TW = "zh-tw" + class MessageContextSkill(): """ @@ -1855,6 +1928,22 @@ class RuntimeEntity(): :attr dict metadata: (optional) Any metadata for the entity. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. + :attr RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user input. + This property is included only if the new system entities are enabled for the + skill. + For more information about how the new system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of the + value returned in the **value** property. This property is returned only for + `@sys-time` and `@sys-date` entities when the user's input is ambiguous. + This property is included only if the new system entities are enabled for the + skill. + :attr RuntimeEntityRole role: (optional) An object describing the role played by + a system entity that is specifies the beginning or end of a range recognized in + the user input. This property is included only if the new system entities are + enabled for the skill. """ def __init__(self, @@ -1864,7 +1953,10 @@ def __init__(self, *, confidence: float = None, metadata: dict = None, - groups: List['CaptureGroup'] = None) -> None: + groups: List['CaptureGroup'] = None, + interpretation: 'RuntimeEntityInterpretation' = None, + alternatives: List['RuntimeEntityAlternative'] = None, + role: 'RuntimeEntityRole' = None) -> None: """ Initialize a RuntimeEntity object. @@ -1878,6 +1970,24 @@ def __init__(self, :param dict metadata: (optional) Any metadata for the entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user + input. This property is included only if the new system entities are + enabled for the skill. + For more information about how the new system entities are interpreted, see + the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of + the value returned in the **value** property. This property is returned + only for `@sys-time` and `@sys-date` entities when the user's input is + ambiguous. + This property is included only if the new system entities are enabled for + the skill. + :param RuntimeEntityRole role: (optional) An object describing the role + played by a system entity that is specifies the beginning or end of a range + recognized in the user input. This property is included only if the new + system entities are enabled for the skill. """ self.entity = entity self.location = location @@ -1885,13 +1995,17 @@ def __init__(self, self.confidence = confidence self.metadata = metadata self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role @classmethod def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ - 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' + 'entity', 'location', 'value', 'confidence', 'metadata', 'groups', + 'interpretation', 'alternatives', 'role' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -1923,6 +2037,16 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['groups'] = [ CaptureGroup._from_dict(x) for x in (_dict.get('groups')) ] + if 'interpretation' in _dict: + args['interpretation'] = RuntimeEntityInterpretation._from_dict( + _dict.get('interpretation')) + if 'alternatives' in _dict: + args['alternatives'] = [ + RuntimeEntityAlternative._from_dict(x) + for x in (_dict.get('alternatives')) + ] + if 'role' in _dict: + args['role'] = RuntimeEntityRole._from_dict(_dict.get('role')) return cls(**args) @classmethod @@ -1945,6 +2069,12 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: _dict['groups'] = [x._to_dict() for x in self.groups] + if hasattr(self, 'interpretation') and self.interpretation is not None: + _dict['interpretation'] = self.interpretation._to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + _dict['alternatives'] = [x._to_dict() for x in self.alternatives] + if hasattr(self, 'role') and self.role is not None: + _dict['role'] = self.role._to_dict() return _dict def _to_dict(self): @@ -1966,6 +2096,534 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other +class RuntimeEntityAlternative(): + """ + An alternative value for the recognized entity. + + :attr str value: (optional) The entity value that was recognized in the user + input. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the recognized entity. + """ + + def __init__(self, *, value: str = None, confidence: float = None) -> None: + """ + Initialize a RuntimeEntityAlternative object. + + :param str value: (optional) The entity value that was recognized in the + user input. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. + """ + self.value = value + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + args = {} + valid_keys = ['value', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntityAlternative: ' + + ', '.join(bad_keys)) + if 'value' in _dict: + args['value'] = _dict.get('value') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityAlternative object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityInterpretation(): + """ + RuntimeEntityInterpretation. + + :attr str calendar_type: (optional) The calendar used to represent a recognized + date (for example, `Gregorian`). + :attr str datetime_link: (optional) A unique identifier used to associate a + recognized time and date. If the user input contains a date and time that are + mentioned together (for example, `Today at 5`, the same **datetime_link** value + is returned for both the `@sys-date` and `@sys-time` entities). + :attr str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a `@sys-date` + entity is recognized based on a holiday name in the user input. + :attr str granularity: (optional) The precision or duration of a time range + specified by a recognized `@sys-time` or `@sys-date` entity. + :attr str range_link: (optional) A unique identifier used to associate multiple + recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are + recognized as a range of values in the user's input (for example, `from July 4 + until July 14` or `from 20 to 25`). + :attr str range_modifier: (optional) The word in the user input that indicates + that a `sys-date` or `sys-time` entity is part of an implied range where only + one date or time is specified (for example, `since` or `until`). + :attr float relative_day: (optional) A recognized mention of a relative day, + represented numerically as an offset from the current date (for example, `-1` + for `yesterday` or `10` for `in ten days`). + :attr float relative_month: (optional) A recognized mention of a relative month, + represented numerically as an offset from the current month (for example, `1` + for `next month` or `-3` for `three months ago`). + :attr float relative_week: (optional) A recognized mention of a relative week, + represented numerically as an offset from the current week (for example, `2` for + `in two weeks` or `-1` for `last week). + :attr float relative_weekend: (optional) A recognized mention of a relative date + range for a weekend, represented numerically as an offset from the current + weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). + :attr float relative_year: (optional) A recognized mention of a relative year, + represented numerically as an offset from the current year (for example, `1` for + `next year` or `-5` for `five years ago`). + :attr float specific_day: (optional) A recognized mention of a specific date, + represented numerically as the date within the month (for example, `30` for + `June 30`.). + :attr str specific_day_of_week: (optional) A recognized mention of a specific + day of the week as a lowercase string (for example, `monday`). + :attr float specific_month: (optional) A recognized mention of a specific month, + represented numerically (for example, `7` for `July`). + :attr float specific_quarter: (optional) A recognized mention of a specific + quarter, represented numerically (for example, `3` for `the third quarter`). + :attr float specific_year: (optional) A recognized mention of a specific year + (for example, `2016`). + :attr float numeric_value: (optional) A recognized numeric value, represented as + an integer or double. + :attr str subtype: (optional) The type of numeric value recognized in the user + input (`integer` or `rational`). + :attr str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` or + `afternoon`). + :attr float relative_hour: (optional) A recognized mention of a relative hour, + represented numerically as an offset from the current hour (for example, `3` for + `in three hours` or `-1` for `an hour ago`). + :attr float relative_minute: (optional) A recognized mention of a relative time, + represented numerically as an offset in minutes from the current time (for + example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). + :attr float relative_second: (optional) A recognized mention of a relative time, + represented numerically as an offset in seconds from the current time (for + example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :attr float specific_hour: (optional) A recognized specific hour mentioned as + part of a time value (for example, `10` for `10:15 AM`.). + :attr float specific_minute: (optional) A recognized specific minute mentioned + as part of a time value (for example, `15` for `10:15 AM`.). + :attr float specific_second: (optional) A recognized specific second mentioned + as part of a time value (for example, `30` for `10:15:30 AM`.). + :attr str timezone: (optional) A recognized time zone mentioned as part of a + time value (for example, `EST`). + """ + + def __init__(self, + *, + calendar_type: str = None, + datetime_link: str = None, + festival: str = None, + granularity: str = None, + range_link: str = None, + range_modifier: str = None, + relative_day: float = None, + relative_month: float = None, + relative_week: float = None, + relative_weekend: float = None, + relative_year: float = None, + specific_day: float = None, + specific_day_of_week: str = None, + specific_month: float = None, + specific_quarter: float = None, + specific_year: float = None, + numeric_value: float = None, + subtype: str = None, + part_of_day: str = None, + relative_hour: float = None, + relative_minute: float = None, + relative_second: float = None, + specific_hour: float = None, + specific_minute: float = None, + specific_second: float = None, + timezone: str = None) -> None: + """ + Initialize a RuntimeEntityInterpretation object. + + :param str calendar_type: (optional) The calendar used to represent a + recognized date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate + a recognized time and date. If the user input contains a date and time that + are mentioned together (for example, `Today at 5`, the same + **datetime_link** value is returned for both the `@sys-date` and + `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a + `@sys-date` entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time + range specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate + multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities + that are recognized as a range of values in the user's input (for example, + `from July 4 until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that + indicates that a `sys-date` or `sys-time` entity is part of an implied + range where only one date or time is specified (for example, `since` or + `until`). + :param float relative_day: (optional) A recognized mention of a relative + day, represented numerically as an offset from the current date (for + example, `-1` for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for + example, `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative + week, represented numerically as an offset from the current week (for + example, `2` for `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a + relative date range for a weekend, represented numerically as an offset + from the current weekend (for example, `0` for `this weekend` or `-1` for + `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative + year, represented numerically as an offset from the current year (for + example, `1` for `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific + date, represented numerically as the date within the month (for example, + `30` for `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a + specific day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a + specific quarter, represented numerically (for example, `3` for `the third + quarter`). + :param float specific_year: (optional) A recognized mention of a specific + year (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, + represented as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the + user input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` + or `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative + hour, represented numerically as an offset from the current hour (for + example, `3` for `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time + (for example, `5` for `in five minutes` or `-15` for `fifteen minutes + ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time + (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned + as part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute + mentioned as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second + mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of + a time value (for example, `EST`). + """ + self.calendar_type = calendar_type + self.datetime_link = datetime_link + self.festival = festival + self.granularity = granularity + self.range_link = range_link + self.range_modifier = range_modifier + self.relative_day = relative_day + self.relative_month = relative_month + self.relative_week = relative_week + self.relative_weekend = relative_weekend + self.relative_year = relative_year + self.specific_day = specific_day + self.specific_day_of_week = specific_day_of_week + self.specific_month = specific_month + self.specific_quarter = specific_quarter + self.specific_year = specific_year + self.numeric_value = numeric_value + self.subtype = subtype + self.part_of_day = part_of_day + self.relative_hour = relative_hour + self.relative_minute = relative_minute + self.relative_second = relative_second + self.specific_hour = specific_hour + self.specific_minute = specific_minute + self.specific_second = specific_second + self.timezone = timezone + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + valid_keys = [ + 'calendar_type', 'datetime_link', 'festival', 'granularity', + 'range_link', 'range_modifier', 'relative_day', 'relative_month', + 'relative_week', 'relative_weekend', 'relative_year', + 'specific_day', 'specific_day_of_week', 'specific_month', + 'specific_quarter', 'specific_year', 'numeric_value', 'subtype', + 'part_of_day', 'relative_hour', 'relative_minute', + 'relative_second', 'specific_hour', 'specific_minute', + 'specific_second', 'timezone' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntityInterpretation: ' + + ', '.join(bad_keys)) + if 'calendar_type' in _dict: + args['calendar_type'] = _dict.get('calendar_type') + if 'datetime_link' in _dict: + args['datetime_link'] = _dict.get('datetime_link') + if 'festival' in _dict: + args['festival'] = _dict.get('festival') + if 'granularity' in _dict: + args['granularity'] = _dict.get('granularity') + if 'range_link' in _dict: + args['range_link'] = _dict.get('range_link') + if 'range_modifier' in _dict: + args['range_modifier'] = _dict.get('range_modifier') + if 'relative_day' in _dict: + args['relative_day'] = _dict.get('relative_day') + if 'relative_month' in _dict: + args['relative_month'] = _dict.get('relative_month') + if 'relative_week' in _dict: + args['relative_week'] = _dict.get('relative_week') + if 'relative_weekend' in _dict: + args['relative_weekend'] = _dict.get('relative_weekend') + if 'relative_year' in _dict: + args['relative_year'] = _dict.get('relative_year') + if 'specific_day' in _dict: + args['specific_day'] = _dict.get('specific_day') + if 'specific_day_of_week' in _dict: + args['specific_day_of_week'] = _dict.get('specific_day_of_week') + if 'specific_month' in _dict: + args['specific_month'] = _dict.get('specific_month') + if 'specific_quarter' in _dict: + args['specific_quarter'] = _dict.get('specific_quarter') + if 'specific_year' in _dict: + args['specific_year'] = _dict.get('specific_year') + if 'numeric_value' in _dict: + args['numeric_value'] = _dict.get('numeric_value') + if 'subtype' in _dict: + args['subtype'] = _dict.get('subtype') + if 'part_of_day' in _dict: + args['part_of_day'] = _dict.get('part_of_day') + if 'relative_hour' in _dict: + args['relative_hour'] = _dict.get('relative_hour') + if 'relative_minute' in _dict: + args['relative_minute'] = _dict.get('relative_minute') + if 'relative_second' in _dict: + args['relative_second'] = _dict.get('relative_second') + if 'specific_hour' in _dict: + args['specific_hour'] = _dict.get('specific_hour') + if 'specific_minute' in _dict: + args['specific_minute'] = _dict.get('specific_minute') + if 'specific_second' in _dict: + args['specific_second'] = _dict.get('specific_second') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'calendar_type') and self.calendar_type is not None: + _dict['calendar_type'] = self.calendar_type + if hasattr(self, 'datetime_link') and self.datetime_link is not None: + _dict['datetime_link'] = self.datetime_link + if hasattr(self, 'festival') and self.festival is not None: + _dict['festival'] = self.festival + if hasattr(self, 'granularity') and self.granularity is not None: + _dict['granularity'] = self.granularity + if hasattr(self, 'range_link') and self.range_link is not None: + _dict['range_link'] = self.range_link + if hasattr(self, 'range_modifier') and self.range_modifier is not None: + _dict['range_modifier'] = self.range_modifier + if hasattr(self, 'relative_day') and self.relative_day is not None: + _dict['relative_day'] = self.relative_day + if hasattr(self, 'relative_month') and self.relative_month is not None: + _dict['relative_month'] = self.relative_month + if hasattr(self, 'relative_week') and self.relative_week is not None: + _dict['relative_week'] = self.relative_week + if hasattr(self, + 'relative_weekend') and self.relative_weekend is not None: + _dict['relative_weekend'] = self.relative_weekend + if hasattr(self, 'relative_year') and self.relative_year is not None: + _dict['relative_year'] = self.relative_year + if hasattr(self, 'specific_day') and self.specific_day is not None: + _dict['specific_day'] = self.specific_day + if hasattr(self, 'specific_day_of_week' + ) and self.specific_day_of_week is not None: + _dict['specific_day_of_week'] = self.specific_day_of_week + if hasattr(self, 'specific_month') and self.specific_month is not None: + _dict['specific_month'] = self.specific_month + if hasattr(self, + 'specific_quarter') and self.specific_quarter is not None: + _dict['specific_quarter'] = self.specific_quarter + if hasattr(self, 'specific_year') and self.specific_year is not None: + _dict['specific_year'] = self.specific_year + if hasattr(self, 'numeric_value') and self.numeric_value is not None: + _dict['numeric_value'] = self.numeric_value + if hasattr(self, 'subtype') and self.subtype is not None: + _dict['subtype'] = self.subtype + if hasattr(self, 'part_of_day') and self.part_of_day is not None: + _dict['part_of_day'] = self.part_of_day + if hasattr(self, 'relative_hour') and self.relative_hour is not None: + _dict['relative_hour'] = self.relative_hour + if hasattr(self, + 'relative_minute') and self.relative_minute is not None: + _dict['relative_minute'] = self.relative_minute + if hasattr(self, + 'relative_second') and self.relative_second is not None: + _dict['relative_second'] = self.relative_second + if hasattr(self, 'specific_hour') and self.specific_hour is not None: + _dict['specific_hour'] = self.specific_hour + if hasattr(self, + 'specific_minute') and self.specific_minute is not None: + _dict['specific_minute'] = self.specific_minute + if hasattr(self, + 'specific_second') and self.specific_second is not None: + _dict['specific_second'] = self.specific_second + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityInterpretation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class GranularityEnum(Enum): + """ + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. + """ + DAY = "day" + FORTNIGHT = "fortnight" + HOUR = "hour" + INSTANT = "instant" + MINUTE = "minute" + MONTH = "month" + QUARTER = "quarter" + SECOND = "second" + WEEK = "week" + WEEKEND = "weekend" + YEAR = "year" + + +class RuntimeEntityRole(): + """ + An object describing the role played by a system entity that is specifies the + beginning or end of a range recognized in the user input. This property is included + only if the new system entities are enabled for the skill. + + :attr str type: (optional) The relationship of the entity to the range. + """ + + def __init__(self, *, type: str = None) -> None: + """ + Initialize a RuntimeEntityRole object. + + :param str type: (optional) The relationship of the entity to the range. + """ + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" + args = {} + valid_keys = ['type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntityRole: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityRole object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityRole object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The relationship of the entity to the range. + """ + DATE_FROM = "date_from" + DATE_TO = "date_to" + NUMBER_FROM = "number_from" + NUMBER_TO = "number_to" + TIME_FROM = "time_from" + TIME_TO = "time_to" + + class RuntimeIntent(): """ An intent identified in the user input. diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 01339bdbd..f701adc77 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -25,8 +25,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import BinaryIO from typing import Dict from typing import List diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index c06230534..15717d031 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -28,8 +28,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 4b23c8d5b..4578d4d8e 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -27,8 +27,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index d899c478e..047af98cb 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -27,8 +27,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 632f2a28a..282fecef8 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -26,8 +26,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import BinaryIO from typing import Dict from typing import List @@ -174,7 +175,7 @@ def create_classifier(self, training_metadata: BinaryIO, :param TextIO training_data: Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see [Data - preparation](https://cloud.ibm.com/docs/services/natural-language-classifier?topic=natural-language-classifier-using-your-data). + preparation](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-using-your-data). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index abe046a73..961999177 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -30,8 +30,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -716,15 +717,21 @@ class CategoriesOptions(): :attr bool explanation: (optional) Set this to `true` to return explanations for each categorization. **This is available only for English categories.**. :attr int limit: (optional) Maximum number of categories to return. - :attr str model: (optional) Deprecated: Enter a [custom model] - (https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard categories model. The custom categories experimental feature will be retired on - 19 December 2019. On that date, deployed custom categories models will no longer be accessible in Natural Language - Understanding. The feature will be removed from Knowledge Studio on an earlier date. Custom categories models will - no longer be accessible in Knowledge Studio on 17 December 2019. + :attr str model: (optional) Enter a [custom + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. + The custom categories experimental feature will be retired on 19 December 2019. + On that date, deployed custom categories models will no longer be accessible in + Natural Language Understanding. The feature will be removed from Knowledge + Studio on an earlier date. Custom categories models will no longer be accessible + in Knowledge Studio on 17 December 2019. """ - def __init__(self, *, explanation: bool = None, limit: int = None, model: str = None) -> None: + def __init__(self, + *, + explanation: bool = None, + limit: int = None, + model: str = None) -> None: """ Initialize a CategoriesOptions object. @@ -732,21 +739,24 @@ def __init__(self, *, explanation: bool = None, limit: int = None, model: str = explanations for each categorization. **This is available only for English categories.**. :param int limit: (optional) Maximum number of categories to return. - :attr str model: (optional) Deprecated: Enter a [custom model] - (https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard categories model. The custom categories experimental feature will be retired on - 19 December 2019. On that date, deployed custom categories models will no longer be accessible in Natural Language - Understanding. The feature will be removed from Knowledge Studio on an earlier date. Custom categories models will - no longer be accessible in Knowledge Studio on 17 December 2019. + :param str model: (optional) Enter a [custom + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. + The custom categories experimental feature will be retired on 19 December + 2019. On that date, deployed custom categories models will no longer be + accessible in Natural Language Understanding. The feature will be removed + from Knowledge Studio on an earlier date. Custom categories models will no + longer be accessible in Knowledge Studio on 17 December 2019. """ self.explanation = explanation self.limit = limit + self.model = model @classmethod def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - valid_keys = ['explanation', 'limit'] + valid_keys = ['explanation', 'limit', 'model'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -756,6 +766,8 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': args['explanation'] = _dict.get('explanation') if 'limit' in _dict: args['limit'] = _dict.get('limit') + if 'model' in _dict: + args['model'] = _dict.get('model') return cls(**args) @classmethod @@ -770,6 +782,8 @@ def to_dict(self) -> Dict: _dict['explanation'] = self.explanation if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model return _dict def _to_dict(self): diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 37c29ba51..f04105bc4 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -25,9 +25,9 @@ timestamped, can report temporal behavior. * For information about the meaning of the models that the service uses to describe personality characteristics, see [Personality -models](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-models#models). +models](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-models#models). * For information about the meaning of the consumption preferences, see [Consumption -preferences](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-preferences#preferences). +preferences](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-preferences#preferences). **Note:** Request logging is disabled for the Personality Insights service. Regardless of whether you set the `X-Watson-Learning-Opt-Out` request header, the service does not log or retain data from requests and responses. @@ -38,7 +38,8 @@ from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core import DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -110,9 +111,9 @@ def profile(self, Japanese, Korean, or Spanish. It can return its results in a variety of languages. **See also:** * [Requesting a - profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#input) + profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#input) * [Providing sufficient - input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient) + input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient) ### Content types You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON (`application/json`) by specifying the **Content-Type** parameter. The @@ -125,7 +126,7 @@ def profile(self, parameter to indicate the character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`. **See also:** [Specifying request and response - formats](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#formats) + formats](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#formats) ### Accept types You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by specifying the **Accept** parameter. CSV output includes a @@ -133,14 +134,14 @@ def profile(self, optional column headers for CSV output. **See also:** * [Understanding a JSON - profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-output#output) + profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-output#output) * [Understanding a CSV - profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-outputCSV#outputCSV). + profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-outputCSV#outputCSV). :param Content content: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see [Providing sufficient - input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient). + input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient). For JSON input, provide an object of type `Content`. :param str accept: The type of the response. For more information, see **Accept types** in the method description. diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 70b37757e..50c30446e 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -39,7 +39,8 @@ from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core import DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import BinaryIO from typing import Dict from typing import List @@ -87,7 +88,7 @@ def list_models(self, **kwargs) -> 'DetailedResponse': information includes the name of the model and its minimum sampling rate in Hertz, among other things. **See also:** [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -116,7 +117,7 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': with the service. The information includes the name of the model and its minimum sampling rate in Hertz, among other things. **See also:** [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). :param str model_id: The identifier of the model in the form of its name from the output of the **Get a model** method. @@ -183,7 +184,7 @@ def recognize(self, the WebSocket API. (With the `curl` command, use the `--data-binary` option to upload the file for the request.) **See also:** [Making a basic HTTP - request](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-http#HTTP-basic). + request](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-http#HTTP-basic). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to `chunked` to use streaming mode. In streaming mode, @@ -194,9 +195,9 @@ def recognize(self, parameter to change the default of 30 seconds. **See also:** * [Audio - transmission](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#transmission) + transmission](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#transmission) * - [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts) + [Timeouts](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts) ### Audio formats (content types) The service accepts audio in the following formats (MIME types). * For formats that are labeled **Required**, you must use the `Content-Type` @@ -230,7 +231,7 @@ def recognize(self, sampling rate of the audio is lower than the minimum required rate, the request fails. **See also:** [Audio - formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). ### Multipart speech recognition **Note:** The Watson SDKs do not support multipart speech recognition. The HTTP `POST` method of the service also supports multipart speech recognition. @@ -243,7 +244,7 @@ def recognize(self, most HTTP servers and proxies. You can encounter this limit, for example, if you want to spot a very large number of keywords. **See also:** [Making a multipart HTTP - request](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-http#HTTP-multi). + request](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-http#HTTP-multi). :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. @@ -251,14 +252,14 @@ def recognize(self, (content types)** in the method description. :param str model: (optional) The identifier of the model that is to be used for the recognition request. See [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: (optional) The customization ID @@ -267,14 +268,14 @@ def recognize(self, the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). :param str base_model_version: (optional) The version of the specified base model that is to be used with the recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. See [Base model - version](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#version). + version](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#version). :param float customization_weight: (optional) If you specify the customization ID (GUID) of a custom language model with the recognition request, the customization weight tells the service how much weight to give @@ -290,52 +291,52 @@ def recognize(self, accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). :param int inactivity_timeout: (optional) The time in seconds after which, if only silence (no speech) is detected in streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity - timeout](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). + timeout](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). :param List[str] keywords: (optional) An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do not need to spot keywords. See [Keyword - spotting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). :param float keywords_threshold: (optional) A confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs no keyword spotting if you omit either parameter. See [Keyword - spotting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). :param int max_alternatives: (optional) The maximum number of alternative transcripts that the service is to return. By default, the service returns a single transcript. If you specify a value of `0`, the service uses the default value, `1`. See [Maximum - alternatives](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#max_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#max_alternatives). :param float word_alternatives_threshold: (optional) A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as "Confusion Networks"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the service computes no alternative words. See [Word - alternatives](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_alternatives). :param bool word_confidence: (optional) If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for each word. By default, the service returns no word confidence scores. See [Word - confidence](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_confidence). + confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_confidence). :param bool timestamps: (optional) If `true`, the service returns time alignment for each word. By default, no timestamps are returned. See [Word - timestamps](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_timestamps). + timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_timestamps). :param bool profanity_filter: (optional) If `true`, the service filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. See [Profanity - filtering](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#profanity_filter). + filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#profanity_filter). :param bool smart_formatting: (optional) If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, and internet addresses into more readable, conventional representations in @@ -344,7 +345,7 @@ def recognize(self, the service performs no smart formatting. **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart - formatting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#smart_formatting). + formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#smart_formatting). :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -356,7 +357,7 @@ def recognize(self, use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker - labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). + labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID (GUID) of a custom language model that is to be used with the recognition @@ -367,7 +368,7 @@ def recognize(self, custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See - [Grammars](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#grammars-input). + [Grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#grammars-input). :param bool redaction: (optional) If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` @@ -381,13 +382,13 @@ def recognize(self, be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric - redaction](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#redaction). :param bool audio_metrics: (optional) If `true`, requests detailed information about the signal characteristics of the input audio. The service returns audio metrics with the final transcription results. By default, the service returns no audio metrics. See [Audio - metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#audio_metrics). + metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio_metrics). :param float end_of_phrase_silence_time: (optional) If `true`, specifies the duration of the pause interval at which the service splits a transcript into multiple final results. If the service detects pauses or extended @@ -402,7 +403,7 @@ def recognize(self, The default pause interval for most languages is 0.8 seconds; the default for Chinese is 0.6 seconds. See [End of phrase silence - time](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#silence_time). + time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#silence_time). :param bool split_transcript_at_phrase_end: (optional) If `true`, directs the service to split the transcript into multiple final results based on semantic features of the input, for example, at the conclusion of @@ -412,7 +413,7 @@ def recognize(self, where the service splits a transcript. By default, the service splits transcripts based solely on the pause interval. See [Split transcript at phrase - end](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#split_transcript). + end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#split_transcript). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -505,7 +506,7 @@ def register_callback(self, number of recognition requests. You can register a maximum of 20 callback URLS in a one-hour span of time. **See also:** [Registering a callback - URL](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#register). + URL](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#register). :param str callback_url: An HTTP or HTTPS URL to which callback notifications are to be sent. To be white-listed, the URL must successfully @@ -554,7 +555,7 @@ def unregister_callback(self, callback_url: str, callback** request for use with the asynchronous interface. Once unregistered, the URL can no longer be used with asynchronous recognition requests. **See also:** [Unregistering a callback - URL](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#unregister). + URL](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#unregister). :param str callback_url: The callback URL that is to be unregistered. :param dict headers: A `dict` containing the request headers @@ -653,7 +654,7 @@ def create_job(self, results, use the WebSocket API. (With the `curl` command, use the `--data-binary` option to upload the file for the request.) **See also:** [Creating a - job](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#create). + job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#create). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to `chunked` to use streaming mode. In streaming mode, @@ -664,9 +665,9 @@ def create_job(self, parameter to change the default of 30 seconds. **See also:** * [Audio - transmission](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#transmission) + transmission](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#transmission) * - [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts) + [Timeouts](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts) ### Audio formats (content types) The service accepts audio in the following formats (MIME types). * For formats that are labeled **Required**, you must use the `Content-Type` @@ -700,7 +701,7 @@ def create_job(self, sampling rate of the audio is lower than the minimum required rate, the request fails. **See also:** [Audio - formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. @@ -708,7 +709,7 @@ def create_job(self, (content types)** in the method description. :param str model: (optional) The identifier of the model that is to be used for the recognition request. See [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully white-listed by using the **Register a callback** method. You can include the same callback URL @@ -751,7 +752,7 @@ def create_job(self, the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: (optional) The customization ID @@ -760,14 +761,14 @@ def create_job(self, the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). :param str base_model_version: (optional) The version of the specified base model that is to be used with the recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. See [Base model - version](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#version). + version](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#version). :param float customization_weight: (optional) If you specify the customization ID (GUID) of a custom language model with the recognition request, the customization weight tells the service how much weight to give @@ -783,52 +784,52 @@ def create_job(self, accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). :param int inactivity_timeout: (optional) The time in seconds after which, if only silence (no speech) is detected in streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity - timeout](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). + timeout](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts-inactivity). :param List[str] keywords: (optional) An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do not need to spot keywords. See [Keyword - spotting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). :param float keywords_threshold: (optional) A confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs no keyword spotting if you omit either parameter. See [Keyword - spotting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). :param int max_alternatives: (optional) The maximum number of alternative transcripts that the service is to return. By default, the service returns a single transcript. If you specify a value of `0`, the service uses the default value, `1`. See [Maximum - alternatives](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#max_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#max_alternatives). :param float word_alternatives_threshold: (optional) A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as "Confusion Networks"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the service computes no alternative words. See [Word - alternatives](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_alternatives). :param bool word_confidence: (optional) If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for each word. By default, the service returns no word confidence scores. See [Word - confidence](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_confidence). + confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_confidence). :param bool timestamps: (optional) If `true`, the service returns time alignment for each word. By default, no timestamps are returned. See [Word - timestamps](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#word_timestamps). + timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_timestamps). :param bool profanity_filter: (optional) If `true`, the service filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. See [Profanity - filtering](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#profanity_filter). + filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#profanity_filter). :param bool smart_formatting: (optional) If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, and internet addresses into more readable, conventional representations in @@ -837,7 +838,7 @@ def create_job(self, the service performs no smart formatting. **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart - formatting](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#smart_formatting). + formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#smart_formatting). :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -849,7 +850,7 @@ def create_job(self, use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker - labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). + labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID (GUID) of a custom language model that is to be used with the recognition @@ -860,7 +861,7 @@ def create_job(self, custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See - [Grammars](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#grammars-input). + [Grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#grammars-input). :param bool redaction: (optional) If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` @@ -874,7 +875,7 @@ def create_job(self, be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric - redaction](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#redaction). :param bool processing_metrics: (optional) If `true`, requests processing metrics about the service's transcription of the input audio. The service returns processing metrics at the interval specified by the @@ -882,7 +883,7 @@ def create_job(self, for transcription events, for example, for final and interim results. By default, the service returns no processing metrics. See [Processing - metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#processing_metrics). + metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#processing_metrics). :param float processing_metrics_interval: (optional) Specifies the interval in real wall-clock seconds at which the service is to return processing metrics. The parameter is ignored unless the `processing_metrics` parameter @@ -896,13 +897,13 @@ def create_job(self, duration of the audio, the service returns processing metrics only for transcription events. See [Processing - metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#processing_metrics). + metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#processing_metrics). :param bool audio_metrics: (optional) If `true`, requests detailed information about the signal characteristics of the input audio. The service returns audio metrics with the final transcription results. By default, the service returns no audio metrics. See [Audio - metrics](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-metrics#audio_metrics). + metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio_metrics). :param float end_of_phrase_silence_time: (optional) If `true`, specifies the duration of the pause interval at which the service splits a transcript into multiple final results. If the service detects pauses or extended @@ -917,7 +918,7 @@ def create_job(self, The default pause interval for most languages is 0.8 seconds; the default for Chinese is 0.6 seconds. See [End of phrase silence - time](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#silence_time). + time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#silence_time). :param bool split_transcript_at_phrase_end: (optional) If `true`, directs the service to split the transcript into multiple final results based on semantic features of the input, for example, at the conclusion of @@ -927,7 +928,7 @@ def create_job(self, where the service splits a transcript. By default, the service splits transcripts based solely on the pause interval. See [Split transcript at phrase - end](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#split_transcript). + end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#split_transcript). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -999,7 +1000,7 @@ def check_jobs(self, **kwargs) -> 'DetailedResponse': **Delete a job** method or until the job's time to live expires, whichever comes first. **See also:** [Checking the status of the latest - jobs](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#jobs). + jobs](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#jobs). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1035,7 +1036,7 @@ def check_job(self, id: str, **kwargs) -> 'DetailedResponse': available. Use the **Check jobs** method to request information about the most recent jobs associated with the calling credentials. **See also:** [Checking the status and retrieving the results of a - job](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#job). + job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#job). :param str id: The identifier of the asynchronous job that is to be used for the request. You must make the request with credentials for the @@ -1072,7 +1073,7 @@ def delete_job(self, id: str, **kwargs) -> 'DetailedResponse': results expires. You must use credentials for the instance of the service that owns a job to delete it. **See also:** [Deleting a - job](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-async#delete-async). + job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#delete-async). :param str id: The identifier of the asynchronous job that is to be used for the request. You must make the request with credentials for the @@ -1124,7 +1125,7 @@ def create_language_model(self, do not lose any models, but you cannot create any more until your model count is below the limit. **See also:** [Create a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#createModel-language). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#createModel-language). :param str name: A user-defined name for the new custom language model. Use a name that is unique among all custom language models that you own. Use a @@ -1138,7 +1139,7 @@ def create_language_model(self, use the **Get a model** method and check that the attribute `custom_language_model` is set to `true`. You can also refer to [Language support for - customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param str dialect: (optional) The dialect of the specified language that is to be used with the custom language model. For most languages, the dialect matches the language of the base model by default. For example, @@ -1205,7 +1206,7 @@ def list_language_models(self, *, language: str = None, all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned (for example, @@ -1243,7 +1244,7 @@ def get_language_model(self, customization_id: str, Gets information about a specified custom language model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1282,7 +1283,7 @@ def delete_language_model(self, customization_id: str, being processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageLanguageModels#deleteModel-language). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#deleteModel-language). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1340,7 +1341,7 @@ def train_language_model(self, and ready to use. The service cannot accept subsequent training requests or requests to add new resources until the existing request completes. **See also:** [Train the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language). ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -1420,7 +1421,7 @@ def reset_language_model(self, customization_id: str, must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageLanguageModels#resetModel-language). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#resetModel-language). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1469,7 +1470,7 @@ def upgrade_language_model(self, customization_id: str, resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. **See also:** [Upgrading a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customUpgrade#upgradeLanguage). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customUpgrade#upgradeLanguage). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1512,7 +1513,7 @@ def list_corpora(self, customization_id: str, status of each corpus. You must use credentials for the instance of the service that owns a model to list its corpora. **See also:** [Listing corpora for a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1587,9 +1588,9 @@ def add_corpus(self, directly. **See also:** * [Working with - corpora](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) + corpora](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) * [Add a corpus to the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#addCorpus). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1617,7 +1618,7 @@ def add_corpus(self, Make sure that you know the character encoding of the file. You must use that encoding when working with the words in the custom language model. For more information, see [Character - encoding](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). + encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). With the `curl` command, use the `--data-binary` option to upload the file for the request. :param bool allow_overwrite: (optional) If `true`, the specified corpus @@ -1670,7 +1671,7 @@ def get_corpus(self, customization_id: str, corpus_name: str, status of the corpus. You must use credentials for the instance of the service that owns a model to list its corpora. **See also:** [Listing corpora for a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1717,7 +1718,7 @@ def delete_corpus(self, customization_id: str, corpus_name: str, credentials for the instance of the service that owns a model to delete its corpora. **See also:** [Deleting a corpus from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageCorpora#deleteCorpus). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#deleteCorpus). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1773,7 +1774,7 @@ def list_words(self, in ascending alphabetical order. You must use credentials for the instance of the service that owns a model to list information about its words. **See also:** [Listing words from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageWords#listWords). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1872,9 +1873,9 @@ def add_words(self, customization_id: str, words: List['CustomWord'], to correct errors, eliminate typos, and modify how words are pronounced as needed. **See also:** * [Working with custom - words](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#workingWords) + words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) * [Add words to the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#addWords). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1954,9 +1955,9 @@ def add_word(self, the **List a custom word** method to review the word that you add. **See also:** * [Working with custom - words](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#workingWords) + words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) * [Add words to the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-languageCreate#addWords). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1967,7 +1968,7 @@ def add_word(self, (dash) or `_` (underscore) to connect the tokens of compound words. URL-encode the word if it includes non-ASCII characters. For more information, see [Character - encoding](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). + encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param str word: (optional) For the **Add custom words** method, you must specify the custom word that is to be added to or updated in the custom model. Do not include spaces in the word. Use a `-` (dash) or `_` @@ -2032,7 +2033,7 @@ def get_word(self, customization_id: str, word_name: str, credentials for the instance of the service that owns a model to list information about its words. **See also:** [Listing words from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageWords#listWords). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2041,7 +2042,7 @@ def get_word(self, customization_id: str, word_name: str, :param str word_name: The custom word that is to be read from the custom language model. URL-encode the word if it includes non-ASCII characters. For more information, see [Character - encoding](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). + encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2080,7 +2081,7 @@ def delete_word(self, customization_id: str, word_name: str, **Train a custom language model** method. You must use credentials for the instance of the service that owns a model to delete its words. **See also:** [Deleting a word from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageWords#deleteWord). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#deleteWord). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2089,7 +2090,7 @@ def delete_word(self, customization_id: str, word_name: str, :param str word_name: The custom word that is to be deleted from the custom language model. URL-encode the word if it includes non-ASCII characters. For more information, see [Character - encoding](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). + encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2131,7 +2132,7 @@ def list_grammars(self, customization_id: str, each grammar. You must use credentials for the instance of the service that owns a model to list its grammars. **See also:** [Listing grammars from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2203,9 +2204,9 @@ def add_grammar(self, service extracts from corpora and grammars and words that you add directly. **See also:** * [Understanding - grammars](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-grammarUnderstand#grammarUnderstand) + grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUnderstand#grammarUnderstand) * [Add a grammar to the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-grammarAdd#addGrammar). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarAdd#addGrammar). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2289,7 +2290,7 @@ def get_grammar(self, customization_id: str, grammar_name: str, the grammar. You must use credentials for the instance of the service that owns a model to list its grammars. **See also:** [Listing grammars from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2335,7 +2336,7 @@ def delete_grammar(self, customization_id: str, grammar_name: str, model with the **Train a custom language model** method. You must use credentials for the instance of the service that owns a model to delete its grammar. **See also:** [Deleting a grammar from a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -2392,7 +2393,7 @@ def create_acoustic_model(self, do not lose any models, but you cannot create any more until your model count is below the limit. **See also:** [Create a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). :param str name: A user-defined name for the new custom acoustic model. Use a name that is unique among all custom acoustic models that you own. Use a @@ -2404,7 +2405,7 @@ def create_acoustic_model(self, used only with the base model that it customizes. To determine whether a base model supports acoustic model customization, refer to [Language support for - customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param str description: (optional) A description of the new custom acoustic model. Use a localized description that matches the language of the custom model. @@ -2452,7 +2453,7 @@ def list_acoustic_models(self, *, language: str = None, all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned (for example, @@ -2490,7 +2491,7 @@ def get_acoustic_model(self, customization_id: str, Gets information about a specified custom acoustic model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -2529,7 +2530,7 @@ def delete_acoustic_model(self, customization_id: str, processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -2598,9 +2599,9 @@ def train_acoustic_model(self, base model for training to succeed. **See also:** * [Train the custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) * [Using custom acoustic and custom language models - together](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-useBoth#useBoth) + together](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-useBoth#useBoth) ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -2669,7 +2670,7 @@ def reset_acoustic_model(self, customization_id: str, request completes. You must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -2730,7 +2731,7 @@ def upgrade_acoustic_model(self, the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model was not trained with a custom language model. **See also:** [Upgrading a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -2747,7 +2748,7 @@ def upgrade_acoustic_model(self, model that is trained with a custom language model, and only if you receive a 400 response code and the message `No input data modified since last training`. See [Upgrading a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2794,7 +2795,7 @@ def list_audio(self, customization_id: str, **kwargs) -> 'DetailedResponse': to a request to add it to the custom acoustic model. You must use credentials for the instance of the service that owns a model to list its audio resources. **See also:** [Listing audio resources for a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAudio#listAudio). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -2867,7 +2868,7 @@ def add_audio(self, returns the status of the resource. Use a loop to check the status of the audio every few seconds until it becomes `ok`. **See also:** [Add audio to the custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-acoustic#addAudio). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#addAudio). ### Content types for audio-type resources You can add an individual audio file in any format that the service supports for speech recognition. For an audio-type resource, use the `Content-Type` parameter @@ -2896,7 +2897,7 @@ def add_audio(self, If the sampling rate of the audio is lower than the minimum required rate, the service labels the audio file as `invalid`. **See also:** [Audio - formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). ### Content types for archive-type resources You can add an archive file (**.zip** or **.tar.gz** file) that contains audio files in any format that the service supports for speech recognition. For an @@ -3026,7 +3027,7 @@ def get_audio(self, customization_id: str, audio_name: str, You must use credentials for the instance of the service that owns a model to list its audio resources. **See also:** [Listing audio resources for a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAudio#listAudio). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -3073,7 +3074,7 @@ def delete_audio(self, customization_id: str, audio_name: str, is being added to the model. You must use credentials for the instance of the service that owns a model to delete its audio resources. **See also:** [Deleting an audio resource from a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the @@ -3125,7 +3126,7 @@ def delete_user_data(self, customer_id: str, You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes the data. **See also:** [Information - security](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-information-security#information-security). + security](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-information-security#information-security). :param str customer_id: The customer ID for which all data is to be deleted. @@ -3228,7 +3229,7 @@ class Model(Enum): """ The identifier of the model that is to be used for the recognition request. See [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' @@ -3294,7 +3295,7 @@ class Model(Enum): """ The identifier of the model that is to be used for the recognition request. See [Languages and - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 0c2f92229..4deab9ab9 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 08edf24c8..616918c3e 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -35,7 +35,8 @@ from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core import DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -82,7 +83,7 @@ def list_voices(self, **kwargs) -> 'DetailedResponse': name, language, gender, and other details about the voice. To see information about a specific voice, use the **Get a voice** method. **See also:** [Listing all available - voices](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-voices#listVoices). + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -114,7 +115,7 @@ def get_voice(self, voice: str, *, customization_id: str = None, the specified voice. To list information about all available voices, use the **List voices** method. **See also:** [Listing a specific - voice](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-voices#listVoice). + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -170,7 +171,7 @@ def synthesize(self, 8 KB for the URL and headers. The 5 KB limit includes any SSML tags that you specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP - interface](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). + interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the @@ -213,7 +214,7 @@ def synthesize(self, The default sampling rate is 22,050 Hz. For more information about specifying an audio format, including additional details about some of the formats, see [Audio - formats](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-audioFormats#audioFormats). + formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audioFormats#audioFormats). ### Warning messages If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning @@ -285,7 +286,7 @@ def get_pronunciation(self, **Note:** This method is currently a beta release. The method does not support the Arabic, Chinese, and Dutch languages. **See also:** [Querying a word from a - language](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). + language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which @@ -354,7 +355,7 @@ def create_voice_model(self, **Note:** This method is currently a beta release. The service does not support voice model customization for the Arabic, Chinese, and Dutch languages. **See also:** [Creating a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). :param str name: The name of the new custom voice model. :param str language: (optional) The language of the new custom voice model. @@ -401,7 +402,7 @@ def list_voice_models(self, *, language: str = None, about it. **Note:** This method is currently a beta release. **See also:** [Querying all custom - models](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll). + models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll). :param str language: (optional) The language for which custom voice models that are owned by the requesting credentials are to be returned. Omit the @@ -459,11 +460,11 @@ def update_voice_model(self, **Note:** This method is currently a beta release. **See also:** * [Updating a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsUpdate) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsUpdate) * [Adding words to a Japanese custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) * [Understanding - customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro). + customization](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -516,7 +517,7 @@ def get_voice_model(self, customization_id: str, voice model, use the **List custom models** method. **Note:** This method is currently a beta release. **See also:** [Querying a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -553,7 +554,7 @@ def delete_voice_model(self, customization_id: str, instance of the service that owns a model to delete it. **Note:** This method is currently a beta release. **See also:** [Deleting a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsDelete). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsDelete). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -610,11 +611,11 @@ def add_words(self, customization_id: str, words: List['Word'], **Note:** This method is currently a beta release. **See also:** * [Adding multiple words to a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsAdd) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsAdd) * [Adding words to a Japanese custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) * [Understanding - customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro). + customization](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -668,7 +669,7 @@ def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': words. **Note:** This method is currently a beta release. **See also:** [Querying all words from a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryModel). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryModel). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -724,11 +725,11 @@ def add_word(self, **Note:** This method is currently a beta release. **See also:** * [Adding a single word to a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordAdd) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordAdd) * [Adding words to a Japanese custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd) * [Understanding - customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro). + customization](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -746,7 +747,7 @@ def add_word(self, part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -789,7 +790,7 @@ def get_word(self, customization_id: str, word: str, the instance of the service that owns a model to list its words. **Note:** This method is currently a beta release. **See also:** [Querying a single word from a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordQueryModel). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordQueryModel). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -830,7 +831,7 @@ def delete_word(self, customization_id: str, word: str, credentials for the instance of the service that owns a model to delete its words. **Note:** This method is currently a beta release. **See also:** [Deleting a word from a custom - model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordDelete). + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordDelete). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of @@ -881,7 +882,7 @@ def delete_user_data(self, customer_id: str, You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes the data. **See also:** [Information - security](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-information-security#information-security). + security](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-information-security#information-security). :param str customer_id: The customer ID for which all data is to be deleted. @@ -1248,7 +1249,7 @@ class Translation(): word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: @@ -1266,7 +1267,7 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ self.translation = translation self.part_of_speech = part_of_speech @@ -1330,7 +1331,7 @@ class PartOfSpeechEnum(Enum): with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ DOSI = "Dosi" FUKU = "Fuku" @@ -1824,7 +1825,7 @@ class Word(): word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ def __init__(self, @@ -1847,7 +1848,7 @@ def __init__(self, part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ self.word = word self.translation = translation @@ -1918,7 +1919,7 @@ class PartOfSpeechEnum(Enum): with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese - entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). + entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ DOSI = "Dosi" FUKU = "Fuku" diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 0aed13498..88ec65e8d 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -30,7 +30,8 @@ from .common import get_sdk_headers from enum import Enum from ibm_cloud_sdk_core import BaseService -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core import DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List @@ -110,7 +111,7 @@ def tone(self, text/plain;charset=utf-8`. For `text/html`, the service removes HTML tags and analyzes only the textual content. **See also:** [Using the general-purpose - endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utgpe#utgpe). + endpoint](https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utgpe#utgpe). :param ToneInput tone_input: JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type @@ -205,7 +206,7 @@ def tone_chat(self, utterances have more than 500 characters. Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8. **See also:** [Using the customer-engagement - endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utco#utco). + endpoint](https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utco#utco). :param List[Utterance] utterances: An array of `Utterance` objects that provides the input content that the service is to analyze. diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 0d6a4f2bf..5ee6158c5 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.2.1' +__version__ = '4.3.0' diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 9428e5ab8..84f904a69 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -25,8 +25,9 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from os.path import basename from typing import BinaryIO from typing import Dict @@ -358,7 +359,7 @@ def update_classifier(self, Update a custom classifier by adding new positive or negative classes or by adding new images to existing classes. You must supply at least one set of positive or negative examples. For details, see [Updating custom - classifiers](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-customizing#updating-custom-classifiers). + classifiers](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-customizing#updating-custom-classifiers). Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. @@ -528,7 +529,7 @@ def delete_user_data(self, customer_id: str, You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information - security](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-information-security). + security](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-information-security). :param str customer_id: The customer ID for which all data is to be deleted. diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index cdabfac4c..8c320eddd 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -24,11 +24,13 @@ from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService +from ibm_cloud_sdk_core import DetailedResponse from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime -from ibm_cloud_sdk_core import get_authenticator_from_environment +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import BinaryIO from typing import Dict from typing import List +from typing import TextIO ############################################################################## # Service @@ -604,6 +606,173 @@ def get_jpeg_image(self, response = self.send(request) return response + ######################### + # Objects + ######################### + + def list_object_metadata(self, collection_id: str, + **kwargs) -> 'DetailedResponse': + """ + List object metadata. + + Retrieves a list of object names in a collection. + + :param str collection_id: The identifier of the collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if collection_id is None: + raise ValueError('collection_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='list_object_metadata') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/objects'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_object_metadata(self, collection_id: str, object: str, + new_object: str, **kwargs) -> 'DetailedResponse': + """ + Update an object name. + + Update the name of an object. A successful request updates the training data for + all images that use the object. + + :param str collection_id: The identifier of the collection. + :param str object: The name of the object. + :param str new_object: The updated name of the object. The name can contain + alphanumeric, underscore, hyphen, space, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if collection_id is None: + raise ValueError('collection_id must be provided') + if object is None: + raise ValueError('object must be provided') + if new_object is None: + raise ValueError('new_object must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='update_object_metadata') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'object': new_object} + + url = '/v4/collections/{0}/objects/{1}'.format( + *self._encode_path_vars(collection_id, object)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_object_metadata(self, collection_id: str, object: str, + **kwargs) -> 'DetailedResponse': + """ + Get object metadata. + + Get the number of bounding boxes for a single object in a collection. + + :param str collection_id: The identifier of the collection. + :param str object: The name of the object. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if collection_id is None: + raise ValueError('collection_id must be provided') + if object is None: + raise ValueError('object must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_object_metadata') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/objects/{1}'.format( + *self._encode_path_vars(collection_id, object)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def delete_object(self, collection_id: str, object: str, + **kwargs) -> 'DetailedResponse': + """ + Delete an object. + + Delete one object from a collection. A successful request deletes the training + data from all images that use the object. + + :param str collection_id: The identifier of the collection. + :param str object: The name of the object. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if collection_id is None: + raise ValueError('collection_id must be provided') + if object is None: + raise ValueError('object must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_object') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/objects/{1}'.format( + *self._encode_path_vars(collection_id, object)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # Training ######################### @@ -761,7 +930,7 @@ def delete_user_data(self, customer_id: str, You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information - security](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-information-security). + security](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-information-security). :param str customer_id: The customer ID for which all data is to be deleted. @@ -2262,6 +2431,152 @@ def __ne__(self, other: 'ObjectDetail') -> bool: return not self == other +class ObjectMetadata(): + """ + Basic information about an object. + + :attr str object: (optional) The name of the object. + :attr int count: (optional) Number of bounding boxes with this object name in + the collection. + """ + + def __init__(self, *, object: str = None, count: int = None) -> None: + """ + Initialize a ObjectMetadata object. + + :param str object: (optional) The name of the object. + :param int count: (optional) Number of bounding boxes with this object name + in the collection. + """ + self.object = object + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ObjectMetadata': + """Initialize a ObjectMetadata object from a json dictionary.""" + args = {} + valid_keys = ['object', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ObjectMetadata: ' + + ', '.join(bad_keys)) + if 'object' in _dict: + args['object'] = _dict.get('object') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'object') and self.object is not None: + _dict['object'] = self.object + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ObjectMetadata object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ObjectMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ObjectMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ObjectMetadataList(): + """ + List of objects. + + :attr int object_count: Number of unique named objects in the collection. + :attr List[ObjectMetadata] objects: (optional) The objects in the collection. + """ + + def __init__(self, + object_count: int, + *, + objects: List['ObjectMetadata'] = None) -> None: + """ + Initialize a ObjectMetadataList object. + + :param int object_count: Number of unique named objects in the collection. + :param List[ObjectMetadata] objects: (optional) The objects in the + collection. + """ + self.object_count = object_count + self.objects = objects + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ObjectMetadataList': + """Initialize a ObjectMetadataList object from a json dictionary.""" + args = {} + valid_keys = ['object_count', 'objects'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ObjectMetadataList: ' + + ', '.join(bad_keys)) + if 'object_count' in _dict: + args['object_count'] = _dict.get('object_count') + else: + raise ValueError( + 'Required property \'object_count\' not present in ObjectMetadataList JSON' + ) + if 'objects' in _dict: + args['objects'] = [ + ObjectMetadata._from_dict(x) for x in (_dict.get('objects')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectMetadataList object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'object_count') and self.object_count is not None: + _dict['object_count'] = self.object_count + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = [x._to_dict() for x in self.objects] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ObjectMetadataList object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ObjectMetadataList') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ObjectMetadataList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ObjectTrainingStatus(): """ Training status for the objects in the collection. @@ -2815,6 +3130,87 @@ def __ne__(self, other: 'TrainingStatus') -> bool: return not self == other +class UpdateObjectMetadata(): + """ + Basic information about an updated object. + + :attr str object: The updated name of the object. The name can contain + alphanumeric, underscore, hyphen, space, and dot characters. It cannot begin + with the reserved prefix `sys-`. + :attr int count: Number of bounding boxes in the collection with the updated + object name. + """ + + def __init__(self, object: str, count: int) -> None: + """ + Initialize a UpdateObjectMetadata object. + + :param str object: The updated name of the object. The name can contain + alphanumeric, underscore, hyphen, space, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param int count: Number of bounding boxes in the collection with the + updated object name. + """ + self.object = object + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'UpdateObjectMetadata': + """Initialize a UpdateObjectMetadata object from a json dictionary.""" + args = {} + valid_keys = ['object', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class UpdateObjectMetadata: ' + + ', '.join(bad_keys)) + if 'object' in _dict: + args['object'] = _dict.get('object') + else: + raise ValueError( + 'Required property \'object\' not present in UpdateObjectMetadata JSON' + ) + if 'count' in _dict: + args['count'] = _dict.get('count') + else: + raise ValueError( + 'Required property \'count\' not present in UpdateObjectMetadata JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateObjectMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'object') and self.object is not None: + _dict['object'] = self.object + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this UpdateObjectMetadata object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'UpdateObjectMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'UpdateObjectMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Warning(): """ Details about a problem. diff --git a/ibm_watson/websocket/__init__.py b/ibm_watson/websocket/__init__.py index ed6564545..391670869 100644 --- a/ibm_watson/websocket/__init__.py +++ b/ibm_watson/websocket/__init__.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/websocket/audio_source.py b/ibm_watson/websocket/audio_source.py index dfeb44b8e..68f48e9ff 100644 --- a/ibm_watson/websocket/audio_source.py +++ b/ibm_watson/websocket/audio_source.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/websocket/recognize_abstract_callback.py b/ibm_watson/websocket/recognize_abstract_callback.py index 1c8ab5220..87824bc19 100644 --- a/ibm_watson/websocket/recognize_abstract_callback.py +++ b/ibm_watson/websocket/recognize_abstract_callback.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 09f2f1276..e3432ce10 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/websocket/synthesize_callback.py b/ibm_watson/websocket/synthesize_callback.py index c8ee34c3c..86bb41a16 100644 --- a/ibm_watson/websocket/synthesize_callback.py +++ b/ibm_watson/websocket/synthesize_callback.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index 9c110daea..73035257d 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/package-lock.json b/package-lock.json index 845b68c01..ee51a62e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43,16 +43,46 @@ "fastq": "^1.6.0" } }, + "@octokit/auth-token": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.0.tgz", + "integrity": "sha512-eoOVMjILna7FVQf96iWc3+ZtE/ZT6y8ob8ZzcqKY1ibSQCnu4O/B7pJvzMx5cyZ/RjAff6DAdEb0O0Cjcxidkg==", + "requires": { + "@octokit/types": "^2.0.0" + } + }, "@octokit/endpoint": { - "version": "5.5.1", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.5.1.tgz", - "integrity": "sha512-nBFhRUb5YzVTCX/iAK1MgQ4uWo89Gu0TH00qQHoYRCsE12dWcG1OiLd7v2EIo2+tpUKPMOQ62QFy9hy9Vg2ULg==", + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.5.2.tgz", + "integrity": "sha512-ICDcRA0C2vtTZZGud1nXRrBLXZqFayodXAKZfo3dkdcLNqcHsgaz3YSTupbURusYeucSVRjjG+RTcQhx6HPPcg==", "requires": { "@octokit/types": "^2.0.0", "is-plain-object": "^3.0.0", "universal-user-agent": "^4.0.0" } }, + "@octokit/plugin-paginate-rest": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-1.1.2.tgz", + "integrity": "sha512-jbsSoi5Q1pj63sC16XIUboklNw+8tL9VOnJsWycWYR78TKss5PVpIPb1TUUcMQ+bBh7cY579cVAWmf5qG+dw+Q==", + "requires": { + "@octokit/types": "^2.0.1" + } + }, + "@octokit/plugin-request-log": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.0.tgz", + "integrity": "sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw==" + }, + "@octokit/plugin-rest-endpoint-methods": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-2.4.0.tgz", + "integrity": "sha512-EZi/AWhtkdfAYi01obpX0DF7U6b1VRr30QNQ5xSFPITMdLSfhcBqjamE3F+sKcxPbD7eZuMHu3Qkk2V+JGxBDQ==", + "requires": { + "@octokit/types": "^2.0.1", + "deprecation": "^2.3.1" + } + }, "@octokit/request": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.3.1.tgz", @@ -69,9 +99,9 @@ } }, "@octokit/request-error": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-1.2.0.tgz", - "integrity": "sha512-DNBhROBYjjV/I9n7A8kVkmQNkqFAMem90dSxqvPq57e2hBr7mNTX98y3R2zDpqMQHVRpBDjsvsfIGgBzy+4PAg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-1.2.1.tgz", + "integrity": "sha512-+6yDyk1EES6WK+l3viRDElw96MvwfJxCt45GvmjDUKWjYIb3PJZQkq3i46TwGwoPD4h8NmTrENmtyA1FwbmhRA==", "requires": { "@octokit/types": "^2.0.0", "deprecation": "^2.0.0", @@ -79,10 +109,14 @@ } }, "@octokit/rest": { - "version": "16.36.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.36.0.tgz", - "integrity": "sha512-zoZj7Ya4vWBK4fjTwK2Cnmu7XBB1p9ygSvTk2TthN6DVJXM4hQZQoAiknWFLJWSTix4dnA3vuHtjPZbExYoCZA==", - "requires": { + "version": "16.43.1", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.43.1.tgz", + "integrity": "sha512-gfFKwRT/wFxq5qlNjnW2dh+qh74XgTQ2B179UX5K1HYCluioWj8Ndbgqw2PVqa1NnVJkGHp2ovMpVn/DImlmkw==", + "requires": { + "@octokit/auth-token": "^2.4.0", + "@octokit/plugin-paginate-rest": "^1.1.1", + "@octokit/plugin-request-log": "^1.0.0", + "@octokit/plugin-rest-endpoint-methods": "2.4.0", "@octokit/request": "^5.2.0", "@octokit/request-error": "^1.0.2", "atob-lite": "^2.0.0", @@ -98,17 +132,17 @@ } }, "@octokit/types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.0.2.tgz", - "integrity": "sha512-StASIL2lgT3TRjxv17z9pAqbnI7HGu9DrJlg3sEBFfCLaMEqp+O3IQPUF6EZtQ4xkAu2ml6kMBBCtGxjvmtmuQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.1.1.tgz", + "integrity": "sha512-89LOYH+d/vsbDX785NOfLxTW88GjNd0lWRz1DVPVsZgg9Yett5O+3MOvwo7iHgvUwbFz0mf/yPIjBkUbs4kxoQ==", "requires": { "@types/node": ">= 8" } }, "@semantic-release/changelog": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-3.0.6.tgz", - "integrity": "sha512-9TqPL/VarLLj6WkUqbIqFiY3nwPmLuKFHy9fe/LamAW5s4MEW/ig9zW9vzYGOUVtWdErGJ1J62E3Edkamh3xaQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-5.0.0.tgz", + "integrity": "sha512-A1uKqWtQG4WX9Vh4QI5b2ddhqx1qAJFlbow8szSNiXn+TaJg15LSUA9NVqyu0VxQFy3hKUJYwbBHGRXCxCy2fg==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", @@ -122,9 +156,9 @@ "integrity": "sha512-9Tj/qn+y2j+sjCI3Jd+qseGtHjOAeg7dU2/lVcqIQ9TV3QDaDXDYXcoOHU+7o2Hwh8L8ymL4gfuO7KxDs3q2zg==" }, "@semantic-release/exec": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-4.0.0.tgz", - "integrity": "sha512-cOvPeWllHaTkwA0Y/Ffskrc1Fcu2VB5YmOYGfDmznTtUIPMk42UuwqsNVYwQPBsHYIggOFkjlnXvInZsGzEe2Q==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-5.0.0.tgz", + "integrity": "sha512-t7LWXIvDJQbuGCy2WmMG51WyaGSLTvZBv9INvcI4S0kn+QjnnVVUMhcioIqhb0r3yqqarMzHVcABFug0q0OXjw==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", @@ -135,9 +169,9 @@ } }, "@semantic-release/git": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-8.0.0.tgz", - "integrity": "sha512-CfjEXtxd4zmhAPtPfrerHQi5QkdMzDhoZY7bUi4zjz3S6PaAlJrpAt09/iV+JKmePEJWiWFla/+a0Y9Qull7YQ==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-9.0.0.tgz", + "integrity": "sha512-AZ4Zha5NAPAciIJH3ipzw/WU9qLAn8ENaoVAhD6srRPxTpTzuV3NhNh14rcAo8Paj9dO+5u4rTKcpetOBluYVw==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", @@ -150,20 +184,20 @@ } }, "@semantic-release/github": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-6.0.1.tgz", - "integrity": "sha512-4/xMKFe7svbv5ltvBxoqPY8fBSPyllVtnf2RMHaddeRKC8C/7FqakwRDmui7jgC3alVrVsRtz/jdTdZjB4J28Q==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.3.tgz", + "integrity": "sha512-4Y2nqruKHsdoayq/H/lMWudONXHLbYtSBDZPktoTrvdJZNQkLhjnxCwDUTKo8G29aI81RuoYKUHv6GSgyJDtGQ==", "requires": { - "@octokit/rest": "^16.27.0", + "@octokit/rest": "^16.43.0", "@semantic-release/error": "^2.2.0", "aggregate-error": "^3.0.0", "bottleneck": "^2.18.1", "debug": "^4.0.0", "dir-glob": "^3.0.0", "fs-extra": "^8.0.0", - "globby": "^10.0.0", - "http-proxy-agent": "^3.0.0", - "https-proxy-agent": "^4.0.0", + "globby": "^11.0.0", + "http-proxy-agent": "^4.0.0", + "https-proxy-agent": "^5.0.0", "issue-parser": "^6.0.0", "lodash": "^4.17.4", "mime": "^2.4.3", @@ -172,30 +206,15 @@ "url-join": "^4.0.0" } }, - "@types/events": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", - "integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==" - }, - "@types/glob": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.1.1.tgz", - "integrity": "sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w==", - "requires": { - "@types/events": "*", - "@types/minimatch": "*", - "@types/node": "*" - } - }, - "@types/minimatch": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", - "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" + "@tootallnate/once": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.0.0.tgz", + "integrity": "sha512-KYyTT/T6ALPkIRd2Ge080X/BsXvy9O0hcWTtMWkPvwAwF99+vn6Dv4GzrFT/Nn1LePr+FFDbRXXlqmsy9lw2zA==" }, "@types/node": { - "version": "13.1.8", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.8.tgz", - "integrity": "sha512-6XzyyNM9EKQW4HKuzbo/CkOIjn/evtCmsU+MUM1xDfJ+3/rNjBttM1NgN7AOQvN6tP1Sl1D1PIKMreTArnxM9A==" + "version": "13.7.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.7.1.tgz", + "integrity": "sha512-Zq8gcQGmn4txQEJeiXo/KiLpon8TzAl0kmKH4zdWctPj05nWwp1ClMdAVEloqrQKfaC48PNLdgN/aVaLqUrluA==" }, "@types/retry": { "version": "0.12.0", @@ -203,9 +222,12 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" }, "agent-base": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-5.1.1.tgz", - "integrity": "sha512-TMeqbNl2fMW0nMjTEPOwe3J/PRFP4vqeoNuQMG0HlMrtm5QxKqdvAkZ1pRBQ/ulIyDD5Yq0nJ7YbdD8ey0TO3g==" + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.0.tgz", + "integrity": "sha512-j1Q7cSCqN+AwrmDd+pzgqc0/NpC655x2bUf5ZjRIO77DcNBFmh+OgRNzF6OKdCC9RSCb19fGd99+bhXFdkRNqw==", + "requires": { + "debug": "4" + } }, "aggregate-error": { "version": "3.0.1", @@ -234,11 +256,6 @@ "resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz", "integrity": "sha1-D+9a1G8b16hQLGVyfwNn1e5D1pY=" }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, "before-after-hook": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz", @@ -249,15 +266,6 @@ "resolved": "https://registry.npmjs.org/bottleneck/-/bottleneck-2.19.5.tgz", "integrity": "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==" }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, "braces": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", @@ -299,11 +307,6 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" - }, "cross-spawn": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", @@ -415,11 +418,6 @@ "universalify": "^0.1.0" } }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" - }, "get-stream": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", @@ -428,19 +426,6 @@ "pump": "^3.0.0" } }, - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, "glob-parent": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz", @@ -450,17 +435,15 @@ } }, "globby": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.2.tgz", - "integrity": "sha512-7dUi7RvCoT/xast/o/dLN53oqND4yk0nsHkhRgn9w65C4PofCLOoJ39iSOg+qVDdWQPIEj+eszMHQ+aLVwwQSg==", + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.0.tgz", + "integrity": "sha512-iuehFnR3xu5wBBtm4xi0dMe92Ob87ufyu/dHwpDYfbcpYpIbrO5OnS8M1vWvrBhSGEJ3/Ecj7gnX76P8YxpPEg==", "requires": { - "@types/glob": "^7.1.1", "array-union": "^2.1.0", "dir-glob": "^3.0.1", - "fast-glob": "^3.0.3", - "glob": "^7.1.3", - "ignore": "^5.1.1", - "merge2": "^1.2.3", + "fast-glob": "^3.1.1", + "ignore": "^5.1.4", + "merge2": "^1.3.0", "slash": "^3.0.0" } }, @@ -475,20 +458,21 @@ "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "http-proxy-agent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-3.0.0.tgz", - "integrity": "sha512-uGuJaBWQWDQCJI5ip0d/VTYZW0nRrlLWXA4A7P1jrsa+f77rW2yXz315oBt6zGCF6l8C2tlMxY7ffULCj+5FhA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", "requires": { - "agent-base": "5", + "@tootallnate/once": "1", + "agent-base": "6", "debug": "4" } }, "https-proxy-agent": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-4.0.0.tgz", - "integrity": "sha512-zoDhWrkR3of1l9QAL8/scJZyLu8j/gBkcwcaQOZh7Gyh/+uJQzGVETdgT30akuwkpL8HTRfssqI3BZuV18teDg==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", "requires": { - "agent-base": "5", + "agent-base": "6", "debug": "4" } }, @@ -507,20 +491,6 @@ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, "is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", @@ -681,14 +651,6 @@ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "requires": { - "brace-expansion": "^1.1.7" - } - }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -785,11 +747,6 @@ "lines-and-columns": "^1.1.6" } }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" - }, "path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", diff --git a/setup.py b/setup.py index 0ea62d9c5..7f93f020b 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.2.1' +__version__ = '4.3.0' if sys.argv[-1] == 'publish': diff --git a/test/integration/test_compare_comply_v1.py b/test/integration/test_compare_comply_v1.py index d74f5ec46..28cca19fe 100644 --- a/test/integration/test_compare_comply_v1.py +++ b/test/integration/test_compare_comply_v1.py @@ -7,20 +7,17 @@ from ibm_watson.compare_comply_v1 import TableReturn -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class IntegrationTestCompareComplyV1(TestCase): compare_comply = None @classmethod def setup_class(cls): - cls.compare_comply = ibm_watson.CompareComplyV1( - '2018-10-15') + cls.compare_comply = ibm_watson.CompareComplyV1('2018-10-15') cls.compare_comply.set_default_headers({ - 'X-Watson-Learning-Opt-Out': - '1', - 'X-Watson-Test': - '1' + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' }) def test_convert_to_html(self): @@ -32,7 +29,8 @@ def test_convert_to_html(self): def test_classify_elements(self): contract = abspath('resources/contract_A.pdf') with open(contract, 'rb') as file: - result = self.compare_comply.classify_elements(file, file_content_type='application/pdf').get_result() + result = self.compare_comply.classify_elements( + file, file_content_type='application/pdf').get_result() assert result is not None def test_extract_tables(self): @@ -45,102 +43,97 @@ def test_extract_tables(self): def test_compare_documents(self): with open(os.path.join(os.path.dirname(__file__), '../../resources/contract_A.pdf'), 'rb') as file1, \ open(os.path.join(os.path.dirname(__file__), '../../resources/contract_B.pdf'), 'rb') as file2: - result = self.compare_comply.compare_documents(file1, file2).get_result() + result = self.compare_comply.compare_documents(file1, + file2).get_result() assert result is not None @pytest.mark.skip(reason="Temporarily skip") def test_feedback(self): feedback_data = { - 'feedback_type': 'element_classification', + 'feedback_type': + 'element_classification', 'document': { 'hash': '', 'title': 'doc title' }, - 'model_id': 'contracts', - 'model_version': '11.00', + 'model_id': + 'contracts', + 'model_version': + '11.00', 'location': { 'begin': '214', 'end': '237' }, - 'text': '1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.', + 'text': + '1. IBM will provide a Senior Managing Consultant / expert resource, for up to 80 hours, to assist Florida Power & Light (FPL) with the creation of an IT infrastructure unit cost model for existing infrastructure.', 'original_labels': { - 'types': [ - { - 'label': { - 'nature': 'Obligation', - 'party': 'IBM' - }, - 'provenance_ids': [ - '85f5981a-ba91-44f5-9efa-0bd22e64b7bc', - 'ce0480a1-5ef1-4c3e-9861-3743b5610795' - ] + 'types': [{ + 'label': { + 'nature': 'Obligation', + 'party': 'IBM' }, - { - 'label': { - 'nature': 'End User', - 'party': 'Exclusion' - }, - 'provenance_ids': [ - '85f5981a-ba91-44f5-9efa-0bd22e64b7bc', - 'ce0480a1-5ef1-4c3e-9861-3743b5610795' - ] - } - ], - 'categories': [ - { - 'label': 'Responsibilities', - 'provenance_ids': [] + 'provenance_ids': [ + '85f5981a-ba91-44f5-9efa-0bd22e64b7bc', + 'ce0480a1-5ef1-4c3e-9861-3743b5610795' + ] + }, { + 'label': { + 'nature': 'End User', + 'party': 'Exclusion' }, - { - 'label': 'Amendments', - 'provenance_ids': [] - } - ] + 'provenance_ids': [ + '85f5981a-ba91-44f5-9efa-0bd22e64b7bc', + 'ce0480a1-5ef1-4c3e-9861-3743b5610795' + ] + }], + 'categories': [{ + 'label': 'Responsibilities', + 'provenance_ids': [] + }, { + 'label': 'Amendments', + 'provenance_ids': [] + }] }, 'updated_labels': { - 'types': [ - { - 'label': { - 'nature': 'Obligation', - 'party': 'IBM' - } - }, - { - 'label': { - 'nature': 'Disclaimer', - 'party': 'Buyer' - } + 'types': [{ + 'label': { + 'nature': 'Obligation', + 'party': 'IBM' } - ], - 'categories': [ - { - 'label': 'Responsibilities' - }, - { - 'label': 'Audits' + }, { + 'label': { + 'nature': 'Disclaimer', + 'party': 'Buyer' } - ] + }], + 'categories': [{ + 'label': 'Responsibilities' + }, { + 'label': 'Audits' + }] } } add_feedback = self.compare_comply.add_feedback( - feedback_data, - user_id='wonder woman', + feedback_data, user_id='wonder woman', comment='test commment').get_result() assert add_feedback is not None assert add_feedback['feedback_id'] is not None feedback_id = add_feedback['feedback_id'] - self.compare_comply.set_default_headers({'x-watson-metadata': 'customer_id=sdk-test-customer-id'}) - get_feedback = self.compare_comply.get_feedback(feedback_id).get_result() + self.compare_comply.set_default_headers( + {'x-watson-metadata': 'customer_id=sdk-test-customer-id'}) + get_feedback = self.compare_comply.get_feedback( + feedback_id).get_result() assert get_feedback is not None list_feedback = self.compare_comply.list_feedback( feedback_type='element_classification').get_result() assert list_feedback is not None - delete_feedback = self.compare_comply.delete_feedback(feedback_id).get_result() + delete_feedback = self.compare_comply.delete_feedback( + feedback_id).get_result() assert delete_feedback is not None @pytest.mark.skip(reason="Temporarily skip") @@ -151,12 +144,9 @@ def test_batches(self): with open(os.path.join(os.path.dirname(__file__), '../../resources/cloud-object-storage-credentials-input.json'), 'rb') as input_credentials_file, \ open(os.path.join(os.path.dirname(__file__), '../../resources/cloud-object-storage-credentials-output.json'), 'rb') as output_credentials_file: create_batch = self.compare_comply.create_batch( - 'html_conversion', - input_credentials_file, - 'us-south', + 'html_conversion', input_credentials_file, 'us-south', 'compare-comply-integration-test-bucket-input', - output_credentials_file, - 'us-south', + output_credentials_file, 'us-south', 'compare-comply-integration-test-bucket-output').get_result() assert create_batch is not None diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index 566ccdb1d..6d842bd08 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -5,8 +5,9 @@ import random import pytest -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class Discoveryv1(TestCase): discovery = None environment_id = '62b0dd87-eefa-40bf-81d6-cf9bc82692ab' # This environment is created for integration testing @@ -21,7 +22,8 @@ def setup_class(cls): 'X-Watson-Test': '1' }) - collections = cls.discovery.list_collections(cls.environment_id).get_result()['collections'] + collections = cls.discovery.list_collections( + cls.environment_id).get_result()['collections'] for collection in collections: if collection['name'] == cls.collection_name: cls.collection_id = collection['collection_id'] @@ -31,15 +33,18 @@ def setup_class(cls): cls.collection_id = cls.discovery.create_collection( cls.environment_id, cls.collection_name, - description="Integration test for python sdk").get_result()['collection_id'] + description="Integration test for python sdk").get_result( + )['collection_id'] @classmethod def teardown_class(cls): - collections = cls.discovery.list_collections(cls.environment_id).get_result()['collections'] + collections = cls.discovery.list_collections( + cls.environment_id).get_result()['collections'] for collection in collections: if collection['name'] == cls.collection_name: print('Deleting the temporary collection') - cls.discovery.delete_collection(cls.environment_id, cls.collection_id) + cls.discovery.delete_collection(cls.environment_id, + cls.collection_id) break def test_environments(self): @@ -53,13 +58,16 @@ def test_environments(self): assert fields is not None def test_configurations(self): - configs = self.discovery.list_configurations(self.environment_id).get_result() + configs = self.discovery.list_configurations( + self.environment_id).get_result() assert configs is not None name = 'test' + random.choice('ABCDEFGHIJKLMNOPQ') new_configuration_id = self.discovery.create_configuration( - self.environment_id, name, - description='creating new config for python sdk').get_result()['configuration_id'] + self.environment_id, + name, + description='creating new config for python sdk').get_result( + )['configuration_id'] assert new_configuration_id is not None self.discovery.get_configuration(self.environment_id, new_configuration_id).get_result() @@ -75,7 +83,10 @@ def test_configurations(self): def test_collections_and_expansions(self): self.discovery.get_collection(self.environment_id, self.collection_id) updated_collection = self.discovery.update_collection( - self.environment_id, self.collection_id, self.collection_name, description='Updating description').get_result() + self.environment_id, + self.collection_id, + self.collection_name, + description='Updating description').get_result() assert updated_collection['description'] == 'Updating description' self.discovery.create_expansions(self.environment_id, @@ -83,14 +94,16 @@ def test_collections_and_expansions(self): 'input_terms': ['a'], 'expanded_terms': ['aa'] }]).get_result() - expansions = self.discovery.list_expansions(self.environment_id, - self.collection_id).get_result() + expansions = self.discovery.list_expansions( + self.environment_id, self.collection_id).get_result() assert expansions['expansions'] self.discovery.delete_expansions(self.environment_id, self.collection_id) def test_documents(self): - with open(os.path.join(os.path.dirname(__file__), '../../resources/simple.html'), 'r') as fileinfo: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/simple.html'), 'r') as fileinfo: add_doc = self.discovery.add_document( environment_id=self.environment_id, collection_id=self.collection_id, @@ -98,10 +111,13 @@ def test_documents(self): assert add_doc['document_id'] is not None doc_status = self.discovery.get_document_status( - self.environment_id, self.collection_id, add_doc['document_id']).get_result() + self.environment_id, self.collection_id, + add_doc['document_id']).get_result() assert doc_status is not None - with open(os.path.join(os.path.dirname(__file__), '../../resources/simple.html'), 'r') as fileinfo: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/simple.html'), 'r') as fileinfo: update_doc = self.discovery.update_document( self.environment_id, self.collection_id, @@ -110,7 +126,8 @@ def test_documents(self): filename='newname.html').get_result() assert update_doc is not None delete_doc = self.discovery.delete_document( - self.environment_id, self.collection_id, add_doc['document_id']).get_result() + self.environment_id, self.collection_id, + add_doc['document_id']).get_result() assert delete_doc['status'] == 'deleted' def test_queries(self): @@ -121,7 +138,8 @@ def test_queries(self): return_fields='extracted_metadata.sha1').get_result() assert query_results is not None - @pytest.mark.skip(reason="Temporary skipping because update_credentials fails") + @pytest.mark.skip( + reason="Temporary skipping because update_credentials fails") def test_credentials(self): credential_details = { 'credential_type': 'username_password', @@ -129,16 +147,19 @@ def test_credentials(self): 'username': 'user@email.com', 'password': 'xxx' } - credentials = self.discovery.create_credentials(self.environment_id, - source_type='salesforce', - credential_details=credential_details).get_result() + credentials = self.discovery.create_credentials( + self.environment_id, + source_type='salesforce', + credential_details=credential_details).get_result() assert credentials['credential_id'] is not None credential_id = credentials['credential_id'] - get_credentials = self.discovery.get_credentials(self.environment_id, credential_id).get_result() + get_credentials = self.discovery.get_credentials( + self.environment_id, credential_id).get_result() assert get_credentials['credential_id'] == credential_id - list_credentials = self.discovery.list_credentials(self.environment_id).get_result() + list_credentials = self.discovery.list_credentials( + self.environment_id).get_result() assert list_credentials is not None new_credential_details = { @@ -147,18 +168,27 @@ def test_credentials(self): 'username': 'user@email.com', 'password': 'xxx' } - updated_credentials = self.discovery.update_credentials(self.environment_id, credential_id, source_type='salesforce', credential_details=new_credential_details).get_result() + updated_credentials = self.discovery.update_credentials( + self.environment_id, + credential_id, + source_type='salesforce', + credential_details=new_credential_details).get_result() assert updated_credentials is not None - get_credentials = self.discovery.get_credentials(self.environment_id, credentials['credential_id']).get_result() - assert get_credentials['credential_details']['url'] == new_credential_details['url'] + get_credentials = self.discovery.get_credentials( + self.environment_id, credentials['credential_id']).get_result() + assert get_credentials['credential_details'][ + 'url'] == new_credential_details['url'] - delete_credentials = self.discovery.delete_credentials(self.environment_id, credential_id).get_result() + delete_credentials = self.discovery.delete_credentials( + self.environment_id, credential_id).get_result() assert delete_credentials['credential_id'] is not None def test_create_event(self): # create test document - with open(os.path.join(os.path.dirname(__file__), '../../resources/simple.html'), 'r') as fileinfo: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/simple.html'), 'r') as fileinfo: add_doc = self.discovery.add_document( environment_id=self.environment_id, collection_id=self.collection_id, @@ -167,9 +197,11 @@ def test_create_event(self): document_id = add_doc['document_id'] # make query to get session token - query = self.discovery.query(self.environment_id, - self.collection_id, - natural_language_query='The content of the first chapter').get_result() + query = self.discovery.query( + self.environment_id, + self.collection_id, + natural_language_query='The content of the first chapter' + ).get_result() assert query['session_token'] is not None # create_event @@ -179,44 +211,47 @@ def test_create_event(self): "collection_id": self.collection_id, "document_id": document_id, } - create_event_response = self.discovery.create_event('click', event_data).get_result() + create_event_response = self.discovery.create_event( + 'click', event_data).get_result() assert create_event_response['type'] == 'click' #delete the documment - self.discovery.delete_document(self.environment_id, - self.collection_id, + self.discovery.delete_document(self.environment_id, self.collection_id, document_id).get_result() @pytest.mark.skip(reason="Temporary disable") def test_tokenization_dictionary(self): result = self.discovery.get_tokenization_dictionary_status( - self.environment_id, - self.collection_id - ).get_result() + self.environment_id, self.collection_id).get_result() assert result['status'] is not None def test_feedback(self): - response = self.discovery.get_metrics_event_rate(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() + response = self.discovery.get_metrics_event_rate( + start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document').get_result() assert response['aggregations'] is not None - response = self.discovery.get_metrics_query(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() + response = self.discovery.get_metrics_query( + start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document').get_result() assert response['aggregations'] is not None - response = self.discovery.get_metrics_query_event(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() + response = self.discovery.get_metrics_query_event( + start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document').get_result() assert response['aggregations'] is not None - response = self.discovery.get_metrics_query_no_results(start_time='2018-07-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() + response = self.discovery.get_metrics_query_no_results( + start_time='2018-07-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document').get_result() assert response['aggregations'] is not None - response = self.discovery.get_metrics_query_token_event(count=10).get_result() + response = self.discovery.get_metrics_query_token_event( + count=10).get_result() assert response['aggregations'] is not None response = self.discovery.query_log(count=2).get_result() @@ -224,40 +259,35 @@ def test_feedback(self): @pytest.mark.skip(reason="Skip temporarily.") def test_stopword_operations(self): - with open(os.path.join(os.path.dirname(__file__), '../../resources/stopwords.txt'), 'r') as stopwords_file: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/stopwords.txt'), + 'r') as stopwords_file: create_stopword_list_result = self.discovery.create_stopword_list( - self.environment_id, - self.collection_id, - stopwords_file - ).get_result() + self.environment_id, self.collection_id, + stopwords_file).get_result() assert create_stopword_list_result is not None delete_stopword_list_result = self.discovery.delete_stopword_list( - self.environment_id, - self.collection_id - ).get_result() + self.environment_id, self.collection_id).get_result() assert delete_stopword_list_result is None def test_gateway_configuration(self): create_gateway_result = self.discovery.create_gateway( self.environment_id, - name='test-gateway-configuration-python' - ).get_result() + name='test-gateway-configuration-python').get_result() assert create_gateway_result['gateway_id'] is not None get_gateway_result = self.discovery.get_gateway( self.environment_id, - create_gateway_result['gateway_id'] - ).get_result() + create_gateway_result['gateway_id']).get_result() assert get_gateway_result is not None list_gateways_result = self.discovery.list_gateways( - self.environment_id - ).get_result() + self.environment_id).get_result() assert list_gateways_result is not None delete_gateways_result = self.discovery.delete_gateway( self.environment_id, - create_gateway_result['gateway_id'] - ).get_result() + create_gateway_result['gateway_id']).get_result() assert delete_gateways_result is not None diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index ed6e5f9a1..008902a1e 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -9,11 +9,15 @@ from glob import glob # tests to include -includes = ['assistant_v1.py', 'natural_language_understanding_v1.py', 'personality_insights_v3.py', 'tone_analyzer_v3.py'] +includes = [ + 'assistant_v1.py', 'natural_language_understanding_v1.py', + 'personality_insights_v3.py', 'tone_analyzer_v3.py' +] # examples path. /examples examples_path = join(dirname(__file__), '../../', 'examples', '*.py') + @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') def test_examples(): @@ -28,8 +32,7 @@ def test_examples(): service_name = name[:-6] if service_name not in vcap_services: - print('%s does not have credentials in VCAP_SERVICES', - service_name) + print('%s does not have credentials in VCAP_SERVICES', service_name) continue try: diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py index 3dccc8f34..5e0b6db04 100644 --- a/test/integration/test_language_translator_v3.py +++ b/test/integration/test_language_translator_v3.py @@ -5,39 +5,42 @@ import pytest import os -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class TestIntegrationLanguageTranslatorV3(unittest.TestCase): + @classmethod def setup_class(cls): cls.language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01') - cls.language_translator.set_default_headers({ - 'X-Watson-Test': - '1' - }) + cls.language_translator.set_default_headers({'X-Watson-Test': '1'}) def test_translate(self): - translation = self.language_translator.translate(text='Hello', model_id='en-es').get_result() + translation = self.language_translator.translate( + text='Hello', model_id='en-es').get_result() assert translation is not None def test_document_translation(self): - with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: + with open(join(dirname(__file__), '../../resources/hello_world.txt'), + 'r') as fileinfo: translation = self.language_translator.translate_document( - file=fileinfo, - file_content_type='text/plain', + file=fileinfo, file_content_type='text/plain', model_id='en-es').get_result() document_id = translation.get('document_id') assert document_id is not None - document_status = self.language_translator.get_document_status(document_id).get_result() + document_status = self.language_translator.get_document_status( + document_id).get_result() assert document_status is not None if document_status.get('status') == 'available': - response = self.language_translator.get_translated_document(document_id, 'text/plain').get_result() + response = self.language_translator.get_translated_document( + document_id, 'text/plain').get_result() assert response.content is not None list_documents = self.language_translator.list_documents().get_result() assert list_documents is not None - delete_document = self.language_translator.delete_document(document_id).get_result() + delete_document = self.language_translator.delete_document( + document_id).get_result() assert delete_document is None diff --git a/test/integration/test_natural_language_classifier_v1.py b/test/integration/test_natural_language_classifier_v1.py index a7506c45f..e3f71ad34 100644 --- a/test/integration/test_natural_language_classifier_v1.py +++ b/test/integration/test_natural_language_classifier_v1.py @@ -8,17 +8,24 @@ FIVE_SECONDS = 5 -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class TestNaturalLanguageClassifierV1(TestCase): + def setUp(self): - self.natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1() + self.natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1( + ) self.natural_language_classifier.set_default_headers({ 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) # Create a classifier - with open(os.path.join(os.path.dirname(__file__), '../../resources/weather_data_train.csv'), 'rb') as training_data: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/weather_data_train.csv'), + 'rb') as training_data: metadata = json.dumps({'name': 'my-classifier', 'language': 'en'}) classifier = self.natural_language_classifier.create_classifier( training_data=training_data, @@ -30,14 +37,16 @@ def tearDown(self): self.natural_language_classifier.delete_classifier(self.classifier_id) def test_list_classifier(self): - list_classifiers = self.natural_language_classifier.list_classifiers().get_result() + list_classifiers = self.natural_language_classifier.list_classifiers( + ).get_result() assert list_classifiers is not None @pytest.mark.skip(reason="The classifier takes more than a minute") def test_classify_text(self): iterations = 0 while iterations < 15: - status = self.natural_language_classifier.get_classifier(self.classifier_id).get_result() + status = self.natural_language_classifier.get_classifier( + self.classifier_id).get_result() iterations += 1 if status['status'] != 'Available': time.sleep(FIVE_SECONDS) @@ -45,10 +54,14 @@ def test_classify_text(self): if status['status'] != 'Available': assert False, 'Classifier is not available' - classes = self.natural_language_classifier.classify(self.classifier_id, 'How hot will it be tomorrow?').get_result() + classes = self.natural_language_classifier.classify( + self.classifier_id, 'How hot will it be tomorrow?').get_result() assert classes is not None - collection = ['{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}'] + collection = [ + '{"text":"How hot will it be today?"}', + '{"text":"Is it hot outside?"}' + ] classes = self.natural_language_classifier.classify_collection( self.classifier_id, collection).get_result() assert classes is not None diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index 01806447a..6a2a99cc3 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -5,8 +5,9 @@ import pytest import os -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class TestIntegrationTextToSpeechV1(unittest.TestCase): text_to_speech = None original_customizations = None @@ -16,12 +17,11 @@ class TestIntegrationTextToSpeechV1(unittest.TestCase): def setup_class(cls): cls.text_to_speech = ibm_watson.TextToSpeechV1() cls.text_to_speech.set_default_headers({ - 'X-Watson-Learning-Opt-Out': - '1', - 'X-Watson-Test': - '1' + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' }) - cls.original_customizations = cls.text_to_speech.list_voice_models().get_result() + cls.original_customizations = cls.text_to_speech.list_voice_models( + ).get_result() cls.created_customization = cls.text_to_speech.create_voice_model( name="test_integration_customization", description="customization for tests").get_result() @@ -34,7 +34,8 @@ def teardown_class(cls): def test_voices(self): output = self.text_to_speech.list_voices().get_result() assert output['voices'] is not None - voice = self.text_to_speech.get_voice(output['voices'][0]['name']).get_result() + voice = self.text_to_speech.get_voice( + output['voices'][0]['name']).get_result() assert voice is not None def test_speak(self): @@ -50,27 +51,32 @@ def test_pronunciation(self): def test_customizations(self): old_length = len(self.original_customizations.get('customizations')) - new_length = len( - self.text_to_speech.list_voice_models().get_result()['customizations']) + new_length = len(self.text_to_speech.list_voice_models().get_result() + ['customizations']) assert new_length - old_length >= 1 def test_custom_words(self): customization_id = self.created_customization.get('customization_id') - words = self.text_to_speech.list_words(customization_id).get_result()['words'] + words = self.text_to_speech.list_words( + customization_id).get_result()['words'] assert not words - self.text_to_speech.add_word( - customization_id, word="ACLs", translation="ackles") + self.text_to_speech.add_word(customization_id, + word="ACLs", + translation="ackles") words = [{"word": "MACLs", "translation": "mackles"}] self.text_to_speech.add_words(customization_id, words) self.text_to_speech.delete_word(customization_id, 'ACLs') - word = self.text_to_speech.get_word(customization_id, 'MACLs').get_result() + word = self.text_to_speech.get_word(customization_id, + 'MACLs').get_result() assert word['translation'] == 'mackles' def test_synthesize_using_websocket(self): file = 'tongue_twister.wav' + class MySynthesizeCallback(SynthesizeCallback): + def __init__(self): SynthesizeCallback.__init__(self) self.fd = None @@ -89,11 +95,11 @@ def on_close(self): self.fd.close() test_callback = MySynthesizeCallback() - self.text_to_speech.synthesize_using_websocket('She sells seashells by the seashore', - test_callback, - accept='audio/wav', - voice='en-GB_KateVoice' - ) + self.text_to_speech.synthesize_using_websocket( + 'She sells seashells by the seashore', + test_callback, + accept='audio/wav', + voice='en-GB_KateVoice') assert test_callback.error is None assert test_callback.fd is not None assert os.stat(file).st_size > 0 diff --git a/test/integration/test_visual_recognition_v3.py b/test/integration/test_visual_recognition_v3.py index b29ea31c1..b74fe6c3c 100644 --- a/test/integration/test_visual_recognition_v3.py +++ b/test/integration/test_visual_recognition_v3.py @@ -5,8 +5,9 @@ from os.path import abspath from unittest import TestCase -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class IntegrationTestVisualRecognitionV3(TestCase): visual_recognition = None classifier_id = None @@ -15,10 +16,8 @@ class IntegrationTestVisualRecognitionV3(TestCase): def setup_class(cls): cls.visual_recognition = ibm_watson.VisualRecognitionV3('2018-03-19') cls.visual_recognition.set_default_headers({ - 'X-Watson-Learning-Opt-Out': - '1', - 'X-Watson-Test': - '1' + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' }) cls.classifier_id = 'sdkxtestxclassifierxdoxnotxdel_1089651138' @@ -37,19 +36,24 @@ def test_custom_classifier(self): open(abspath('resources/trucks.zip'), 'rb') as trucks: classifier = self.visual_recognition.create_classifier( 'CarsVsTrucks', - positive_examples={'cars': cars}, + positive_examples={ + 'cars': cars + }, negative_examples=trucks, - ).get_result() + ).get_result() assert classifier is not None classifier_id = classifier['classifier_id'] - output = self.visual_recognition.get_classifier(classifier_id).get_result() + output = self.visual_recognition.get_classifier( + classifier_id).get_result() assert output is not None - output = self.visual_recognition.delete_classifier(classifier_id).get_result() + output = self.visual_recognition.delete_classifier( + classifier_id).get_result() @pytest.mark.skip(reason="temporay disable") def test_core_ml_model(self): - core_ml_model = self.visual_recognition.get_core_ml_model(self.classifier_id).get_result() + core_ml_model = self.visual_recognition.get_core_ml_model( + self.classifier_id).get_result() assert core_ml_model.ok diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 036e3510e..682170aef 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -6,8 +6,9 @@ from unittest import TestCase from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, TrainingDataObject, Location -@pytest.mark.skipif( - os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') + +@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, + reason='requires VCAP_SERVICES') class IntegrationTestVisualRecognitionV3(TestCase): visual_recognition = None @@ -15,21 +16,18 @@ class IntegrationTestVisualRecognitionV3(TestCase): def setup_class(cls): cls.visual_recognition = ibm_watson.VisualRecognitionV4('2019-02-11') cls.visual_recognition.set_default_headers({ - 'X-Watson-Learning-Opt-Out': - '1', - 'X-Watson-Test': - '1' + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' }) def test_01_colllections(self): collection = self.visual_recognition.create_collection( - name='my_collection', - description='just for fun' - ).get_result() + name='my_collection', description='just for fun').get_result() collection_id = collection.get('collection_id') assert collection_id is not None - my_collection = self.visual_recognition.get_collection(collection_id=collection.get('collection_id')).get_result() + my_collection = self.visual_recognition.get_collection( + collection_id=collection.get('collection_id')).get_result() assert my_collection is not None assert my_collection.get('name') == 'my_collection' @@ -38,43 +36,50 @@ def test_01_colllections(self): description='new description').get_result() assert updated_collection is not None - collections = self.visual_recognition.list_collections().get_result().get('collections') + collections = self.visual_recognition.list_collections().get_result( + ).get('collections') assert collections is not None self.visual_recognition.delete_collection(collection_id=collection_id) def test_02_images(self): collection = self.visual_recognition.create_collection( - name='my_collection', - description='just for fun' - ).get_result() + name='my_collection', description='just for fun').get_result() collection_id = collection.get('collection_id') add_images = self.visual_recognition.add_images( collection_id, - image_url=["https://upload.wikimedia.org/wikipedia/commons/3/33/KokoniPurebredDogsGreeceGreekCreamWhiteAdult.jpg", "https://upload.wikimedia.org/wikipedia/commons/0/07/K%C3%B6nigspudel_Apricot.JPG"], + image_url=[ + "https://upload.wikimedia.org/wikipedia/commons/3/33/KokoniPurebredDogsGreeceGreekCreamWhiteAdult.jpg", + "https://upload.wikimedia.org/wikipedia/commons/0/07/K%C3%B6nigspudel_Apricot.JPG" + ], ).get_result() assert add_images is not None image_id = add_images.get('images')[0].get('image_id') - list_images = self.visual_recognition.list_images(collection_id).get_result() + list_images = self.visual_recognition.list_images( + collection_id).get_result() assert list_images is not None - image_details = self.visual_recognition.get_image_details(collection_id, image_id).get_result() + image_details = self.visual_recognition.get_image_details( + collection_id, image_id).get_result() assert image_details is not None - response = self.visual_recognition.get_jpeg_image(collection_id, image_id).get_result() + response = self.visual_recognition.get_jpeg_image( + collection_id, image_id).get_result() assert response.content is not None self.visual_recognition.delete_image(collection_id, image_id) self.visual_recognition.delete_collection(collection_id) def test_03_analyze(self): - dog_path = os.path.join(os.path.dirname(__file__), '../../resources/dog.jpg') + dog_path = os.path.join(os.path.dirname(__file__), + '../../resources/dog.jpg') giraffe_path = os.path.join(os.path.dirname(__file__), '../../resources/my-giraffe.jpeg') - with open(dog_path, 'rb') as dog_file, open(giraffe_path, 'rb') as giraffe_files: + with open(dog_path, 'rb') as dog_file, open(giraffe_path, + 'rb') as giraffe_files: analyze_images = self.visual_recognition.analyze( collection_ids=['684777e5-1f2d-40e3-987f-72d36557ef46'], features=[AnalyzeEnums.Features.OBJECTS.value], @@ -82,21 +87,26 @@ def test_03_analyze(self): FileWithMetadata(dog_file), FileWithMetadata(giraffe_files) ], - image_url=['https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg']).get_result() + image_url=[ + 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg' + ]).get_result() assert analyze_images is not None print(json.dumps(analyze_images, indent=2)) - def test_04_training(self): + def test_04_objects_and_training(self): # create a classifier my_collection = self.visual_recognition.create_collection( name='my_test_collection', - description='testing for python' - ).get_result() + description='testing for python').get_result() collection_id = my_collection.get('collection_id') assert collection_id is not None # add images - with open(os.path.join(os.path.dirname(__file__), '../../resources/South_Africa_Luca_Galuzzi_2004.jpeg'), 'rb') as giraffe_info: + with open( + os.path.join( + os.path.dirname(__file__), + '../../resources/South_Africa_Luca_Galuzzi_2004.jpeg'), + 'rb') as giraffe_info: add_images_result = self.visual_recognition.add_images( collection_id, images_file=[FileWithMetadata(giraffe_info)], @@ -115,14 +125,40 @@ def test_04_training(self): ]).get_result() assert training_data is not None + # list objects metadata + object_metadata_list = self.visual_recognition.list_object_metadata( + collection_id=collection_id).get_result() + assert object_metadata_list is not None + + # update object metadata + object_metadata = object_metadata_list.get('objects')[0] + updated_object_metadata = self.visual_recognition.update_object_metadata( + collection_id=collection_id, + object=object_metadata.get('object'), + new_object='updated giraffe training data').get_result() + assert updated_object_metadata is not None + + # get object metadata + object_metadata = self.visual_recognition.get_object_metadata( + collection_id=collection_id, + object='updated giraffe training data', + ).get_result() + assert object_metadata is not None + assert object_metadata.get('object') == 'updated giraffe training data' + # train collection train_result = self.visual_recognition.train(collection_id).get_result() assert train_result is not None assert train_result.get('training_status') is not None # training usage - training_usage = self.visual_recognition.get_training_usage(start_time='2019-11-01', end_time='2019-11-27').get_result() + training_usage = self.visual_recognition.get_training_usage( + start_time='2019-11-01', end_time='2019-11-27').get_result() assert training_usage is not None + # delete object + self.visual_recognition.delete_object( + collection_id, object='updated giraffe training data') + # delete collection self.visual_recognition.delete_collection(collection_id) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 8dfa617fe..c3fbcabf0 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -277,7 +277,7 @@ def construct_full_body(self): "system_settings": WorkspaceSystemSettings._from_dict( json.loads( - """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""" + """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""" )), "intents": [], "entities": [], @@ -285,6 +285,7 @@ def construct_full_body(self): "counterexamples": [], "webhooks": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -442,7 +443,7 @@ def construct_full_body(self): "system_settings": WorkspaceSystemSettings._from_dict( json.loads( - """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}""" + """{"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""" )), "intents": [], "entities": [], @@ -451,6 +452,7 @@ def construct_full_body(self): "webhooks": [], }) body['append'] = True + body['include_audit'] = True return body def construct_required_body(self): @@ -682,6 +684,7 @@ def construct_full_body(self): "description": "string1", "examples": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -839,6 +842,8 @@ def construct_full_body(self): "new_description": "string1", "new_examples": [], }) + body['append'] = True + body['include_audit'] = True return body def construct_required_body(self): @@ -1082,6 +1087,7 @@ def construct_full_body(self): "text": "string1", "mentions": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -1240,6 +1246,7 @@ def construct_full_body(self): "new_text": "string1", "new_mentions": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -1482,6 +1489,7 @@ def construct_full_body(self): body.update({ "text": "string1", }) + body['include_audit'] = True return body def construct_required_body(self): @@ -1634,6 +1642,7 @@ def construct_full_body(self): body.update({ "new_text": "string1", }) + body['include_audit'] = True return body def construct_required_body(self): @@ -1876,6 +1885,7 @@ def construct_full_body(self): "fuzzy_match": True, "values": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -2041,6 +2051,8 @@ def construct_full_body(self): "new_fuzzy_match": True, "new_values": [], }) + body['append'] = True + body['include_audit'] = True return body def construct_required_body(self): @@ -2381,6 +2393,7 @@ def construct_full_body(self): "synonyms": [], "patterns": [], }) + body['include_audit'] = True return body def construct_required_body(self): @@ -2550,6 +2563,8 @@ def construct_full_body(self): "new_synonyms": [], "new_patterns": [], }) + body['append'] = True + body['include_audit'] = True return body def construct_required_body(self): @@ -2802,6 +2817,7 @@ def construct_full_body(self): body.update({ "synonym": "string1", }) + body['include_audit'] = True return body def construct_required_body(self): @@ -2964,6 +2980,7 @@ def construct_full_body(self): body.update({ "new_synonym": "string1", }) + body['include_audit'] = True return body def construct_required_body(self): @@ -3253,6 +3270,7 @@ def construct_full_body(self): "disambiguation_opt_out": True, }) + body['include_audit'] = True return body def construct_required_body(self): @@ -3493,6 +3511,7 @@ def construct_full_body(self): "new_disambiguation_opt_out": True, }) + body['include_audit'] = True return body def construct_required_body(self): @@ -3937,9 +3956,9 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_MessageResponse_json = """{"input": {"text": "fake_text"}, "intents": [], "entities": [], "alternate_intents": false, "context": {"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}, "output": {"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}, "actions": []}""" fake_response_WorkspaceCollection_json = """{"workspaces": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" -fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" -fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" -fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "fake_prompt", "none_of_the_above_prompt": "fake_none_of_the_above_prompt", "enabled": false, "sensitivity": "fake_sensitivity", "randomize": false, "max_suggestions": 15, "suggestion_text_policy": "fake_suggestion_text_policy"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "workspace_id": "fake_workspace_id", "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": []}""" fake_response_IntentCollection_json = """{"intents": [], "pagination": {"refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5, "matched": 7, "refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor"}}""" fake_response_Intent_json = """{"intent": "fake_intent", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_Intent_json = """{"intent": "fake_intent", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 8755ee6d5..46887549b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -256,7 +256,7 @@ def construct_full_body(self): "context": MessageContext._from_dict( json.loads( - """{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""" + """{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "skills": {}}""" )), }) return body @@ -343,4 +343,4 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_SessionResponse_json = """{"session_id": "fake_session_id"}""" -fake_response_MessageResponse_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}}""" +fake_response_MessageResponse_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "skills": {}}}""" diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index e567e8f07..18f6b0a08 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -19,7 +19,6 @@ import json import pytest import responses -import tempfile import ibm_watson.natural_language_understanding_v1 from ibm_watson.natural_language_understanding_v1 import * @@ -96,7 +95,7 @@ def construct_full_body(self): "features": Features._from_dict( json.loads( - """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" + """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" )), "text": "string1", @@ -125,7 +124,7 @@ def construct_required_body(self): "features": Features._from_dict( json.loads( - """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" + """{"concepts": {"limit": 5}, "emotion": {"document": true, "targets": []}, "entities": {"limit": 5, "mentions": true, "model": "fake_model", "sentiment": false, "emotion": false}, "keywords": {"limit": 5, "sentiment": false, "emotion": false}, "metadata": {}, "relations": {"model": "fake_model"}, "semantic_roles": {"limit": 5, "keywords": true, "entities": true}, "sentiment": {"document": true, "targets": []}, "categories": {"explanation": false, "limit": 5, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" )), "text": "string1", diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 8cc3a8c83..90225cdbb 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -18,7 +18,6 @@ import json import pytest import responses -import tempfile import ibm_watson.text_to_speech_v1 from ibm_watson.text_to_speech_v1 import * diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 0c06d3194..99dc2df07 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -852,6 +852,313 @@ def construct_required_body(self): # End of Service: Images ############################################################################## +############################################################################## +# Start of Service: Objects +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_object_metadata +#----------------------------------------------------------------------------- +class TestListObjectMetadata(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_object_metadata_response(self): + body = self.construct_full_body() + response = fake_response_ObjectMetadataList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_object_metadata_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ObjectMetadataList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_object_metadata_empty(self): + check_empty_required_params(self, fake_response_ObjectMetadataList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/objects'.format(body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) + service.set_service_url(base_url) + output = service.list_object_metadata(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_object_metadata +#----------------------------------------------------------------------------- +class TestUpdateObjectMetadata(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_object_metadata_response(self): + body = self.construct_full_body() + response = fake_response_UpdateObjectMetadata_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_object_metadata_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_UpdateObjectMetadata_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_object_metadata_empty(self): + check_empty_required_params(self, + fake_response_UpdateObjectMetadata_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/objects/{1}'.format( + body['collection_id'], body['object']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) + service.set_service_url(base_url) + output = service.update_object_metadata(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + body.update({ + "new_object": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + body.update({ + "new_object": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_object_metadata +#----------------------------------------------------------------------------- +class TestGetObjectMetadata(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_object_metadata_response(self): + body = self.construct_full_body() + response = fake_response_ObjectMetadata_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_object_metadata_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ObjectMetadata_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_object_metadata_empty(self): + check_empty_required_params(self, fake_response_ObjectMetadata_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/objects/{1}'.format( + body['collection_id'], body['object']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) + service.set_service_url(base_url) + output = service.get_object_metadata(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_object +#----------------------------------------------------------------------------- +class TestDeleteObject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_object_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_object_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_object_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/objects/{1}'.format( + body['collection_id'], body['object']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) + service.set_service_url(base_url) + output = service.delete_object(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['object'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Objects +############################################################################## + ############################################################################## # Start of Service: Training ############################################################################## @@ -1241,6 +1548,9 @@ def send_request(obj, body, response, url=None): fake_response_ImageSummaryList_json = """{"images": []}""" fake_response_ImageDetails_json = """{"image_id": "fake_image_id", "updated": "2017-05-16T13:56:54.957Z", "created": "2017-05-16T13:56:54.957Z", "source": {"type": "fake_type", "filename": "fake_filename", "archive_filename": "fake_archive_filename", "source_url": "fake_source_url", "resolved_url": "fake_resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [], "training_data": {"objects": []}}""" fake_response_BinaryIO_json = """Contents of response byte-stream...""" +fake_response_ObjectMetadataList_json = """{"object_count": 12, "objects": []}""" +fake_response_UpdateObjectMetadata_json = """{"object": "fake_object", "count": 5}""" +fake_response_ObjectMetadata_json = """{"object": "fake_object", "count": 5}""" fake_response_Collection_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "description": "fake_description"}}}""" fake_response_TrainingDataObjects_json = """{"objects": []}""" fake_response_TrainingEvents_json = """{"start_time": "2017-05-16T13:56:54.957Z", "end_time": "2017-05-16T13:56:54.957Z", "completed_events": 16, "trained_images": 14, "events": []}"""